Scrivio Interview library
ScenarioIntermediate8 min read · updated 12 November 2026

About 3 percent of CI builds fail on random tests that pass on retry. How do you investigate and reduce flakiness?

First I would measure: collect test results from every CI run so we know exactly which tests flake and how often, instead of guessing from memory. Then I would reproduce suspects locally by running them many times and in random order, and fix the root causes, which are usually timing and sleeps, shared state, test order, port and time zone assumptions, or calls to external services. While a fix is pending, a known flaky test is quarantined with an owner and a deadline, not silently retried, because automatic retries hide real concurrency bugs.

Why this question is asked

A 3 percent build failure rate sounds small until we do the arithmetic. With 200 builds a day, that is 6 red builds daily that cost someone a rerun and a context switch, and every red build teaches the team that red might not mean broken. Interviewers ask this scenario because it is a systematic problem that rewards a systematic approach: data first, then reproduction, then fixes, with a policy that stops the problem from growing back. In this answer, we will see how to measure flakiness, go through the common causes with examples, reproduce a flaky test on purpose, handle tests that cannot be fixed immediately, and explain why blanket retries make things worse.

1Measure Before Guessing

The first step is data. Every CI run already produces JUnit XML reports. If we keep them, with the commit, the branch, the agent and the timestamp, we can answer the important questions: which tests failed and then passed on the same commit, how often each one fails, and whether failures cluster on certain agents, at certain times or after certain other tests.

Usually the result is a long tail. In a suite of 4,000 tests, perhaps 25 tests account for nearly all the flaky failures, and five of them cause more than half. That tells us where to start. It also gives us a baseline: if the flake rate per test is tracked weekly, we can see whether a fix worked and whether new flaky tests are appearing. Many CI systems and build tools, such as Gradle's build scans or a test analytics service, can do this tracking; a simple script that loads the XML reports into a table also works.

A flake report from one month of CI runs
TestRunsFlaky failuresRatePattern
ShipmentListenerIT.storesShipment6,1001222.0%Slow agents, uses Thread.sleep
OrderApiIT.listsOrders6,100611.0%Only after CustomerApiIT
InvoiceDateTest.dueDate6,100180.3%Runs near midnight UTC
PaymentClientIT.retries6,100120.2%Fixed port 8089 in use
21 other tests6,100 each45 in totalunder 0.1%Mixed
A few tests cause most of the pain; the pattern column points at the cause.

2The Usual Causes

Flaky tests are rarely random. A test fails intermittently because its result depends on something that changes between runs, and in practice that something is one of a small set of usual suspects. The data usually points at which one. Timing is the most common. A test that sleeps for 500 ms before checking asynchronous work, or a timeout that is generous on a laptop, passes as long as the machine is fast enough. On a busy CI agent, the same work occasionally takes longer, and the test fails. The fix is to wait for a condition with a tool like Awaitility instead of waiting for a fixed time.

Shared state comes next, and it explains the 'only after CustomerApiIT' pattern in the report. When one test leaves rows in a shared database, fills a static cache, changes a singleton bean or sets a system property without restoring it, the next test sees a world it did not expect. Whether it fails then depends on which tests ran before it, which is why order dependence and shared state usually appear together. Environment assumptions are a third source: a fixed port that is sometimes already taken, the machine's default time zone or locale, or the current date, which makes a test fail only near midnight or at the end of a month. Finally, any test that calls a real third-party sandbox or a shared staging environment fails whenever that service is slow or down, which has nothing to do with our code.

Java
// Order dependence: passes alone, fails after a test that created customers
assertThat(customerRepository.count()).isEqualTo(1); // sometimes 4
// Clock dependence: fails when run close to midnight UTC
assertThat(invoice.dueDate()).isEqualTo(LocalDate.now().plusDays(30)); // now() read twice, may differ
// Fix: inject a Clock and use a fixed one in the test
Clock clock = Clock.fixed(Instant.parse("2026-03-31T23:59:59Z"), ZoneOffset.UTC);

3Reproducing a Flaky Test on Purpose

A test that fails once in fifty runs is hard to fix if we can only observe it on CI. So we make it fail locally. The simplest technique is repetition: run the suspect many times in a loop, which JUnit 5 supports directly with @RepeatedTest, or with a build tool option to rerun tests. If it fails one time in fifty, 200 runs show at least one failure about 98 percent of the time, because the chance of 200 passes in a row is 0.98 to the power 200, under 2 percent.

Java
// Temporarily, while investigating
@RepeatedTest(200)
void storesShipment() { /* the suspect test */ }
# junit-platform.properties: run test methods and classes in random order to expose order dependence
junit.jupiter.testmethod.order.default=org.junit.jupiter.api.MethodOrderer$Random
junit.jupiter.testclass.order.default=org.junit.jupiter.api.ClassOrderer$Random

Random ordering exposes order dependence, and the random seed is logged so that a failing order can be replayed. To expose timing problems, we can add load: run the tests in parallel, run them while a CPU-heavy process runs, or limit the CPUs available to the container that runs them. Once the failure reproduces reliably, the fix is usually quick, because the cause is now visible in front of us.

4Quarantine With an Owner, Not Silent Retries

Some flaky tests cannot be fixed the same day. Leaving them in place keeps breaking builds; deleting them loses coverage. The middle path is quarantine: the test is tagged, excluded from the blocking build, still run in a separate non-blocking job so we keep collecting data, and recorded with an owner and a deadline.

Java
@Tag("quarantine") // FLAKY-412, owner: payments team, fix by 2026-12-01
@Test
void retriesOnConnectionReset() { /* ... */ }
// Gradle: the main build excludes the tag, a separate job runs only quarantined tests
tasks.test { useJUnitPlatform { excludeTags("quarantine") } }

The owner and deadline are what make quarantine a policy rather than a graveyard. A quarantined test that passes its deadline is either fixed, deleted on purpose, or escalated. And the quarantine list is kept small and visible, so that it never becomes the place where hard tests go to be forgotten.

5Why Automatic Retries Make It Worse

The quick fix that many teams reach for is to retry every failed test automatically, for example up to three times. The build turns green and the problem seems solved. But a test that fails 2 percent of the time may be telling us something true: a race condition in the listener, a missing transaction boundary, a cache that is not thread-safe. Those bugs will also fail 2 percent of the time in production, under real load, where nobody retries them. Blanket retries turn a visible signal into an invisible one.

Retries also hide the trend. If the flake rate quietly doubles over six months, nobody notices, because every build is still green, only slower. If a team uses retries at all, the retried failures should be recorded and reported as flakes, so that retries are a temporary cushion with the data still flowing, not a way to stop looking.

6Follow-up questions

How do you tell a flaky test from a flaky product?

By finding the root cause rather than assuming. If the failure comes from the test's own timing, shared data or environment, it is a test problem. If it reproduces with the test fixed, for example a lost update under concurrency, it is a product bug that the test was right to catch. Many apparently flaky tests turn out to be the second kind, which is exactly why they should not be retried blindly.

What target flake rate would you set?

I would set it per build rather than per test: for example, fewer than 1 in 200 builds failing for reasons unrelated to the change. That number is meaningful to developers, and with thousands of tests it forces each individual test to be very reliable. The baseline from the measurement step shows how far we are from it.

Should a flaky test block a merge?

A known, quarantined test should not, because it no longer carries a reliable signal. Any other test failure should block the merge, because otherwise people learn to merge on red. That is why the quarantine mechanism matters: it lets the blocking build stay strict.

7Conclusion

In this answer, we treated a 3 percent flaky build rate as a data problem first. Collecting test results across runs shows which few tests cause most failures and what patterns they follow. The usual causes are timing and sleeps, shared state and test order, ports, time zones and clocks, and external services. We reproduce suspects locally by repeating them and running them in random order, fix the root causes, and quarantine tests we cannot fix yet with an owner and a deadline. Blanket retries are avoided, because they hide real concurrency bugs and the growth of the problem.

What to say in the interviewAbout 90 seconds aloud

Open with

I'd start with data rather than guesses. CI already produces JUnit XML for every run, so I'd collect it with the commit and agent, and find tests that failed and passed on the same commit.

Then, if they want more

Usually a small number of tests cause most of the failures, and the patterns, like slow agents, a certain test order, or failures near midnight, point at the cause.

The common causes are timing, especially Thread.sleep and tight timeouts; shared state like leftover database rows, static caches or system properties; order dependence; fixed ports; default time zones and LocalDate.now; and calls to real external services.

To fix a test I first make it fail locally: run it a few hundred times with @RepeatedTest, enable random method and class order in JUnit, and add load or parallelism for timing issues. Once it reproduces, the fix is usually clear: Awaitility instead of sleeps, unique test data, injected Clocks, random ports, and stubs instead of real services.

For tests I can't fix right away, I'd quarantine them with a tag, an owner and a deadline, excluded from the blocking build but still run so we keep data. What I would avoid is blanket automatic retries. They make the build green but hide real race conditions, which then happen in production, and they hide the trend. I'd track flaky failures per build as a metric to show progress.

About this answer

Last updated
12 November 2026
Versions it names
JUnit 5
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 "About 3 percent of CI builds fail on random tests that pass on retry. How do you...": https://scrivio-interview-library.netlify.app/java/integration-testing/a41b3977fa/