Flaky tests

Worse than no test, because they teach a team that red does not mean broken — with a real one from this codebase, diagnosed rather than retried.

10 min read🧪 Testing Java Services

A flaky test is one that passes and fails on the same code. It is worse than having no test at all, and the reason is not the time it wastes — it is what it does to everybody's reading of a red build.

A suite with no test for something tells you nothing. A suite with a flaky test teaches people that red does not mean broken, and once that is learned it applies to every other test in the suite, including the ones that are telling the truth.

One from this project, last week

The deploy stopped here:

plaintext
✗ fix-the-race-condition — THE STARTER PASSES EVERY CASE. The fixture does not test what the problem asks for.
  deploy failed before the switch — removing /srv/code10x/releases/20260912-204250

That guard checks that a practice problem's broken starter code actually fails its own tests — otherwise the problem is not testing what it claims. The starter's bug is a data race on count++.

It had passed five deploys that day. Run locally immediately afterwards, it passed six times out of six on the same image.

Which is the exact shape of the problem: the failure carried no information about the change being deployed, and the temptation — run it again, it will probably pass — is precisely how a team learns to ignore red.

Diagnose, do not retry

Re-running is not a diagnosis, and "it passed the second time" is not a result. What the investigation established:

  1. The change could not be the cause. The deploy carried four markdown lessons. Nothing Java.
  2. It was not reproducible locally — 6 of 6. So the difference was the environment, not the code.
  3. A mechanism that explains both. A lost update needs a thread preempted between the read and the write of count++. On a laptop with real parallelism that happens constantly. On a small VM the pool's threads do not truly overlap, and a JIT-compiled loop over a non-volatile field can be hoisted to a single read-add-write — at which point the broken code produces the correct total.

Only with a mechanism is a fix more than a guess. The general shape:

  • What is different between the runs that pass and the runs that fail? Machine, core count, time of day, order, load.
  • Can you make it fail on demand? Run it a hundred times, on one core, under load. A flake you can reproduce is a bug you can fix.
  • Is the test wrong, or the code? Sometimes the flake is the only honest thing in the suite, and there is a real race in production.

The usual causes

Nearly every flaky test is one of these:

  • Time. LocalDate.now() in a test that fails on the last day of the month, at midnight, or in another timezone. Inject a Clock; never read the real one in a test.
  • Order dependence. Test A leaves a row behind, test B assumes an empty table. It passes until the runner reorders or parallelises. Run your suite in random order deliberately — JUnit 5 has @TestMethodOrder(MethodOrderer.Random.class) — and find these before CI does.
  • Shared state. A static field, a cache, a singleton with memory. Two tests pass alone and fail together.
  • Concurrency. Both directions: a race that does not manifest (the one above), and a race that does. The second is a real bug.
  • Thread.sleep. The most common flake there is. A sleep is a bet on how long something takes; CI is slower than your laptop and the bet loses. Await a condition — Awaitility, a latch, a poll with a timeout — never a duration.
  • The network. Any test that reaches something real is one outage away from red. That is what Testcontainers and WireMock exist to prevent.
  • Unordered results. select ... with no order by returns rows in whatever order it likes, and a test asserting on the first row passes until the plan changes. This is the pagination lesson's warning arriving as a test failure.

Quarantine is a decision, not a drawer

When one cannot be fixed today, the options are:

  1. Fix it. Always first.
  2. Quarantine it — tagged, excluded from the blocking run, still executed and reported. With an owner and a date.
  3. Delete it. A legitimate choice. A test nobody trusts and nobody will fix is costing attention and giving nothing.

The failure mode is @Disabled with no comment, which is deletion pretending to be quarantine — the test is gone and everyone believes it is covered.

Retrying, and doing it honestly

Automatic retries are the standard response and usually the wrong one, because they hide the number above. A suite with retries on looks green while getting steadily worse.

There is one case where retrying is correct, and the distinction is worth stating precisely: when the property being asserted is genuinely probabilistic.

The race fixture is that case. It asserts this broken code fails its tests, and a data race may legitimately not manifest in a given run. So the guard now runs the starter up to three times before declaring the fixture broken.

What makes that honest rather than a cover-up:

  • The assertion did not weaken. A fixture that genuinely fails to discriminate passes all three attempts and still fails the check — verified by pointing a starter at its own reference solution, which reported THE STARTER PASSES EVERY CASE, in 3 attempt(s).
  • The retries are only spent on the path that was about to fail, so a green run costs nothing.
  • It is written down — in the guard, in the fixture, and in the project's testing document, with the reason, so the next person does not remove it as clutter.

A retry you can explain in those terms is engineering. A retry added because the build was annoying is how a suite stops meaning anything.

Under the hood: why the same race passes on a laptop and fails on a small VM

The mechanism behind "on a laptop with real parallelism that happens constantly, on a small VM it does not" has a name: the Java Memory Model permits a compiler or the JIT to reorder or coalesce reads and writes to a field that is not volatile and not otherwise synchronized, as long as no reordering is observable from the one thread running that code. The JMM's guarantees are about what a single thread can observe, not about literal instruction order — with no volatile, no synchronized, and no other happens-before edge between two threads touching a shared field, the JIT is free to treat repeated reads of it inside a tight loop as if nothing else could possibly be changing it, because nothing in the code told it otherwise. That is how a loop over count++ can get compiled down to something closer to a single read-add-write for the whole loop, on the one thread that runs it — a transformation that is only ever incorrect when a second thread is genuinely interleaving with the first, which is precisely the situation the race depends on. Fewer real cores also independently make a thread pool's tasks run closer to sequentially than to genuinely overlapping, so on a small VM the interleaving the race needs is rarer and the JIT is likelier to have "proven" (for that one thread's view) that nothing else touches the field — the two effects compound.

Randomised test ordering works on a related but separate principle. @TestMethodOrder(MethodOrderer.Random.class) takes a seed — reproducible if you set junit.jupiter.execution.order.random.seed, otherwise chosen once per run — and uses it to produce a shuffled ordering of test methods within a class, the same way Collections.shuffle would with that seed. The point is to convert order-dependence from a rare accident of whatever order a test runner happens to use into something that fails reliably enough to notice: two tests that only pass in declaration order fail on most random orderings rather than passing every single run by coincidence, and a logged seed lets a failure be reproduced exactly.

Try it yourself

Reason about a random seed and order-dependence

A suite has two tests: createsCustomer (inserts a row, does not clean it up) and countIsZeroOnEmptyTable (asserts the table is empty). Declaration order happens to always run the second one first, so the suite has been green for months. The team turns on @TestMethodOrder(MethodOrderer.Random.class) with no fixed seed. What should they expect the next time CI runs, and why would running the suite once by hand in a random order last week not have caught this?

Why one manual try is not the same guarantee as repeated sampling

They should expect the suite to start failing intermittently: roughly half of the possible two-test orderings run createsCustomer first, and any run that does leaves a row behind for countIsZeroOnEmptyTable to trip over. With only two tests, a single manual random draw actually has decent odds (about 50%) of hitting the bad ordering — but with a class of ten tests there are 10! possible orderings, and one hand-run sample is a poor substitute for MethodOrderer.Random drawing a fresh random seed on every single CI invocation. That repetition is the entire point of the mechanism: an order-dependence bug is found the same way this lesson says any flake's true rate is found — by many runs over time, never by one spot check — and a single manual try, however random, is one data point pretending to be a distribution.

Misconceptions

  • "A test that fails once and passes on rerun without any code change is probably fine." That is the definition of flaky, not evidence of fine — this lesson's own incident passed 6 of 6 locally after failing once in CI, and the right response was finding a mechanism, not shrugging at the rerun.
  • "Thread.sleep is fine as long as the duration is generous." No duration is safe in general — a longer sleep only lowers the probability of the race, it does not remove the dependency on timing. A race that fails one run in a thousand is still a certainty over a year of CI; only awaiting a real condition removes timing from the equation entirely.

Sources

  • The Java Language Specification, Chapter 17 (Threads and Locks) — the Java Memory Model.
  • JUnit 5 User Guide — test execution order (MethodOrderer).
  • Google Testing Blog, "Flaky Tests at Google and How We Mitigate Them".
Progress is saved on this device and to your account when signed in.