Scrivio Interview library
DebuggingFoundations7 min read · updated 12 November 2026

An asynchronous test sometimes fails because a message listener has not processed the event yet. The test uses Thread.sleep(500). How would you fix it?

A fixed sleep is a guess about how long the listener needs: on a slow CI machine 500 ms is too short and the test flakes, and on a fast laptop it wastes time on every run. The fix is to wait for the outcome instead of waiting for time, with Awaitility: await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> ...) polls until the assertion passes or the limit is reached. We poll for something observable, such as a row in the database or a call to a stub, and make the test's data unique so it waits for its own event, not someone else's.

Why this question is asked

Asynchronous code is everywhere in Spring applications: Kafka and RabbitMQ listeners, @Async methods, application events published after commit, scheduled jobs. Testing it means the test thread has to wait for work happening on another thread, and the first thing most people reach for is Thread.sleep(). Interviewers ask this question because the answer separates people who have fought flaky tests from people who have only written them. In this answer, we will see why the sleep fails, replace it with Awaitility step by step, decide what to wait for, and make sure the test waits for its own event.

1Why Thread.sleep(500) Is Both Flaky and Slow

The test publishes an event, and a listener running on another thread processes it, perhaps saving a row or calling another service. The test cannot know when that happens, so it sleeps for a fixed time and then checks.

Java
@Test
void storesShipmentWhenOrderIsPaid() throws Exception {
kafka.send("orders.paid", "order-1001", "{\"orderId\":1001}");
Thread.sleep(500); // a guess
assertThat(shipments.findByOrderId(1001L)).isPresent(); // fails about 1 run in 30 on CI
}

How long the listener needs depends on things the test does not control: whether the consumer has finished joining its group, how busy the CI machine is, garbage collection pauses, how many other tests run in parallel. On a laptop the listener might finish in 40 ms; on a loaded CI agent it might take 900 ms on a bad run. So 500 ms is too short some of the time, and the test flakes. The usual reaction is to raise it to 2,000 ms, which makes the flake rarer but makes every run of every such test slower by two seconds, even when the work was done in 40 ms. A fixed sleep can only be too short or too long; it is never right.

2Waiting for the Outcome With Awaitility

Awaitility is a small library for exactly this problem. Instead of sleeping for a fixed time, it repeatedly checks a condition, by default every 100 milliseconds, and returns as soon as the condition holds. If the condition still does not hold after the maximum time, it fails with a clear message.

Java
import static org.awaitility.Awaitility.await;
@Test
void storesShipmentWhenOrderIsPaid() {
kafka.send("orders.paid", "order-1001", "{\"orderId\":1001}");
await().atMost(Duration.ofSeconds(5))
.untilAsserted(() -> assertThat(shipments.findByOrderId(1001L)).isPresent());
// returns after about 40 ms on a laptop, about 900 ms on a slow CI run,
// and fails only if nothing arrives within 5 seconds
}
Step throughHow await().untilAsserted() waits
  1. Send the eventThe test thread continues immediately
  2. Run the assertionLook for the shipment row
  3. Did the assertion pass?
    YesReturn: the test continuesNoCheck the time limit
  4. Has 5 seconds passed?
    YesFail with the last assertion errorNoWait 100 ms and run the assertion again

4 steps in order. Play them, or step through them one at a time.

Notice how the two numbers changed meaning. The 5 seconds is no longer how long the test waits; it is the point at which we decide something is really broken. The test waits only as long as the work takes. So we can choose a generous limit for slow machines without slowing down fast ones.

untilAsserted() takes any code that throws an AssertionError when the condition is not met, so the usual AssertJ assertions work inside it. Awaitility catches the error, waits for the poll interval, and tries again. When it finally gives up, it reports the last assertion failure, which tells us what the state was. We can tune the polling with pollInterval() and add pollDelay() when the condition might be true too early, but the defaults are good for most tests.

3Wait for Something Observable

The next question is what to wait for. The best condition is the observable outcome the feature promises: a row in the database, a message on an output topic, a request received by a WireMock stub, an HTTP endpoint returning the new state. These are the things a user or another system would see, so the test checks the behaviour rather than how it is implemented.

It is tempting to wait on internal state instead, such as a counter field in the listener, a CountDownLatch added only for the test, or a mock verifying that a method was called. Those tests pass when the method was called even if the outcome was wrong, for example if the save failed afterwards, and they break when we refactor the listener even though the behaviour stayed the same. Sometimes an internal signal is the only option, but the observable outcome should be the first choice.

Java
// Observable outcome: the downstream call happened
await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
wireMock.verify(postRequestedFor(urlEqualTo("/shipments"))
.withRequestBody(matchingJsonPath("$.orderId", equalTo("1001")))));

4Make Sure the Test Waits for Its Own Event

There is one more trap. Suppose another test, running earlier or in parallel, also sends an order 1001, or the shipments table already holds a row for it from a previous run. Our await succeeds immediately, before our event is processed, and the test passes for the wrong reason. Later, when that other test changes, ours starts failing mysteriously.

The fix is to make the test's data unique, so the condition can only be satisfied by the test's own event.

Java
long orderId = ThreadLocalRandom.current().nextLong(1_000_000, Long.MAX_VALUE); // unique to this test
kafka.send("orders.paid", "order-" + orderId, "{\"orderId\":" + orderId + "}");
await().atMost(Duration.ofSeconds(5))
.untilAsserted(() -> assertThat(shipments.findByOrderId(orderId)).isPresent());

The same thinking applies to negative checks such as 'no email is sent for a cancelled order'. Awaitility's during() can assert that a condition stays true for a period, but a negative check over time is always a compromise. A better pattern is to send a second, positive event with the same key after the one that should be ignored, wait for the positive one to be processed, and then check that the first left no trace, since a Kafka listener processes the events of one partition in order.

5Follow-up questions

Why not use a CountDownLatch in the listener instead?

A latch counted down by the listener tells us that the listener method ran, not that the outcome is correct, and it requires test-only code inside or around production code. It is acceptable when there is no observable outcome to poll, but waiting on the database row or the downstream call tests the real behaviour without touching the listener.

How do you choose the atMost value?

Choose a limit well above the slowest normal run, because it only matters when something is broken. A few seconds is typical for a local listener; a Kafka test that includes consumer group start-up may need 10 to 30 seconds for the first message. Since Awaitility returns as soon as the condition holds, a generous limit costs nothing on passing runs.

Can Awaitility hide a real performance problem?

It can if the limit is very large and nobody looks at durations. If the processing must happen within 200 ms in production, write a separate test or a metric for that latency instead of relying on the await limit. The await limit is for correctness, not for performance.

6Conclusion

In this answer, we saw that a fixed Thread.sleep() is always either too short, which makes the test flaky on slow machines, or too long, which slows every run. Awaitility replaces it by polling a condition until it holds, with atMost() as a generous failure limit rather than a wait time. The condition should be an observable outcome, such as a database row or a call to a stub, rather than internal state. And the test should use unique data, so that the await is satisfied only by its own event.

What to say in the interviewAbout 90 seconds aloud

Open with

The problem with Thread.sleep is that it guesses how long the listener needs. On a loaded CI agent the consumer might take longer than 500 milliseconds, so the test flakes, and if we raise it to two seconds every run gets slower even when the work finishes in 40 milliseconds.

Then, if they want more

A fixed sleep can only be too short or too long. I'd replace it with Awaitility: await, atMost five seconds, untilAsserted with the normal AssertJ assertion inside. Awaitility polls, every 100 milliseconds by default, and returns as soon as the assertion passes, so the five seconds is just the point where we decide it's broken, not a wait time.

If it gives up, it reports the last assertion error, which shows the state. I'd also be careful about what I wait for. I prefer the observable outcome, like the shipment row in the database or a request verified on a WireMock stub, rather than a counter or a latch inside the listener, because that tests behaviour and survives refactoring.

And I'd make sure the test waits for its own event: generate a unique order id per test, so a row left by another test or a previous run can't satisfy the condition early. For negative checks, I'd send a later positive event and wait for that, rather than sleeping and hoping nothing happens.

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 "An asynchronous test sometimes fails because a message listener has not processed the...": https://scrivio-interview-library.netlify.app/java/integration-testing/b737a6830e/