Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A Kafka integration test passes locally but fails about 1 run in 10 in CI: the consumer sometimes sees no record, and sometimes a record from another test. Tests share one broker container. What causes this, and how do you make the tests reliable?

The two symptoms have two causes. A missing record is a startup race: the test sends before the consumer has been assigned its partitions, and with auto.offset.reset=latest the new consumer starts after the record. A foreign record comes from shared state: tests using the same topics, group ids and committed offsets on one reused broker, or listeners from another cached test context still consuming. We fix it with earliest or ContainerTestUtils.waitForAssignment, unique topics, keys and group ids per test, Awaitility instead of sleeps, and stopping listeners that do not belong to the test.

Why this question is asked

A test that fails one run in ten is worse than a test that always fails, because people learn to press rerun and stop trusting the suite. Kafka tests are especially prone to this, since they combine asynchronous consumers, group coordination that takes time, and a broker whose state outlives each test. Interviewers ask this debugging question to see whether we can explain flakiness from first principles instead of adding longer sleeps. In this answer, we will recap what a consumer does when it starts, explain the missing record and the stray record separately, fix each one, and then look at how to share one broker container safely and how to test the dead-letter path.

1A Quick Recap: What Happens When a Test Consumer Starts

When a Spring Kafka listener container starts, its consumer does not read records immediately. It joins its consumer group, the broker's group coordinator runs a rebalance, and only then does the consumer learn which partitions it owns. Next it decides where to start reading in each partition: at the group's committed offset if there is one, otherwise according to auto.offset.reset, which is latest by default, meaning the current end of the partition.

This takes from a few hundred milliseconds to a few seconds, longer on a loaded CI machine. Meanwhile the test method may already be running. So the test and the consumer race, and the outcome depends on timing, which is exactly what makes the failure intermittent.

2Why the Record Is Sometimes Missing

If the test sends its record before the consumer has its partitions, the record is written at, say, offset 0. A moment later the consumer gets the partition, finds no committed offset, applies latest and starts at offset 1. The record sits behind it forever, and the assertion times out. On a laptop the consumer usually wins the race, so the test passes; on a slower CI runner it loses about one time in ten.

Step throughThe startup race
TestBrokerConsumer
join group (rebalance takes 2 s on CI)
send record: written at offset 0
assigned partition 0
no committed offset, reset=latest: start at 1
await 10 s ... timeout, record never read

5 messages in order. Play them, or step through them one at a time.

On a fast laptop the assignment arrives before the send and the test passes.

There are two fixes, and they combine well. Setting spring.kafka.consumer.auto-offset-reset=earliest in tests means a new group starts at the beginning, so a record sent before assignment is still read. And when a test really must know the consumer is ready, for example because it uses a shared topic where earliest would read old data, it waits for the assignment explicitly before sending.

3Waiting for Assignment Before Sending

spring-kafka-test provides ContainerTestUtils.waitForAssignment, which blocks until a listener container owns the expected number of partitions. We look the container up by its listener id.

Java
@Autowired KafkaListenerEndpointRegistry registry;
@BeforeEach
void waitForConsumer() {
MessageListenerContainer c = registry.getListenerContainer("paymentListener");
ContainerTestUtils.waitForAssignment(c, 3); // topic has 3 partitions; returns once assigned
}
@Test
void storesPayment() {
String key = "p-" + UUID.randomUUID(); // unique per test
template.send(topic, key, payload(key));
await().atMost(Duration.ofSeconds(30))
.untilAsserted(() -> assertThat(payments.findById(key)).isPresent());
}

Notice the generous 30 second timeout. With Awaitility it costs nothing when the system is fast, because the assertion passes as soon as it can, and it gives a slow CI runner enough room. Fixed Thread.sleep calls do the opposite: they slow every run and are still sometimes too short. Logging the partition assignment, which Spring Kafka does at INFO, also makes a failed run explain itself.

4Why a Record From Another Test Appears

The second symptom comes from shared state. One broker container serves the whole suite, which is good for speed, but anything one test leaves behind is visible to the next. If two tests send to the same topic, a listener in the second test can receive the first test's record. If two test classes use the same group id, the second one resumes from offsets the first committed, or, with earliest, rereads everything still in the topic.

There is a less obvious source as well. Spring's test framework caches application contexts between test classes, and a cached context's listener containers keep running. If an earlier context subscribed to the same topic with the same group id, its consumer is a member of the group too, and the broker may assign it the partition where our record lands. Our test then sees nothing, or a cached listener writes something unexpected into the shared database.

Shared state and its isolation
Shared thingSymptomIsolation
Topicrecords from other tests arriveunique topic per test class, or unique keys
Group idresumes from old committed offsetsnew group id per test class
Cached contextits listener steals partitionsunique group ids, or stop its containers
Database rowsassertion finds old rowsunique ids, clean tables per test
Fixed sleepstoo short on slow CIAwaitility with a generous timeout

5Sharing One Broker Without Sharing Data

The goal is to keep one container per suite, since starting Kafka for every class is slow, while making every test's data private. We generate topic names and group ids per test class, for example with ${random.uuid} in the test properties, and generate keys per test method, asserting only on our own key. Tests that need a specific topic name filter by a test id header or key. If a test class must reuse a group id, @DirtiesContext on the earlier class closes its context and stops its listeners, at the cost of a fresh context. With these rules the order of tests no longer matters, and running them in parallel becomes possible.

6Follow-up questions

How would you test that a poison record goes to the dead-letter topic?

I would send bytes that the deserializer cannot parse, for example the string not-json to a topic whose consumer uses ErrorHandlingDeserializer with a JSON delegate and a DefaultErrorHandler with DeadLetterPublishingRecoverer. Then I would create a plain test consumer subscribed to the dead-letter topic, which is the original name plus .DLT by default, with a unique group id and earliest, and use KafkaTestUtils.getSingleRecord to read the dead-lettered record within a timeout. The assertions check the original bytes, the key, and the exception headers the recoverer adds, such as the exception class name. I would also assert that a valid record sent after it is still processed, to prove the partition was not blocked.

Is it acceptable to mark the test as flaky and retry it in CI?

Only as a short-term measure while the cause is fixed. Automatic retries hide real races, and a race in a test is often a race in production too, such as a consumer that misses records because of auto.offset.reset=latest on a new group.

7Conclusion

In this answer, we split the flaky test into two problems. The missing record is a race between the send and the consumer's partition assignment, made worse by auto.offset.reset=latest, and fixed with earliest or ContainerTestUtils.waitForAssignment. The stray record comes from shared topics, group ids, committed offsets and cached contexts with running listeners, fixed with unique names and keys per test and stopping listeners that do not belong. Awaitility with generous timeouts replaces sleeps, and one broker per suite stays fast once the data is isolated.

What to say in the interviewAbout 80 seconds aloud

Open with

I see two different causes. When the consumer sees no record, it is a startup race: the test sends before the listener's consumer has joined the group and been assigned partitions, and a new group with auto offset reset latest starts at the end of the partition, after our record.

Then, if they want more

On a laptop the assignment usually wins; on a slower CI runner it sometimes loses. I would set auto offset reset to earliest in tests and, where needed, call ContainerTestUtils.waitForAssignment on the listener container before sending.

When a test sees a record from another test, it is shared state on the reused broker: same topics, same group ids, so offsets committed by an earlier test, or records another test sent. There is also a subtle one: Spring caches test contexts, and listeners from an earlier cached context keep running and can be assigned our partitions.

So I give every test class its own topic and group id, every test its own keys, and stop or isolate listeners from other contexts. I replace any fixed sleeps with Awaitility and a generous timeout, and log partition assignment so a failure explains itself.

That way I can keep one broker container for the whole suite, which keeps it fast, while each test's data stays private.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A Kafka integration test passes locally but fails about 1 run in 10 in CI: the consumer...": https://scrivio-interview-library.netlify.app/spring-boot/kafka/2e71bdf452/