Flaky test

On this page 7

A flaky test is an automated test that produces different outcomes on identical code, passing on one run and failing on the next without any change to the program, the test or its declared inputs. In software testing and programming practice, flakiness is treated as a defect of the test or its environment, because a result that cannot be reproduced carries no reliable information about whether the code is correct.

Flaky tests appear at every level of the test pyramid, but they are most common in integration and end-to-end tests, where timing, networks, shared data and external services add sources of nondeterminism. Their cost is rarely the single failed run; it is the gradual loss of trust in the test suite, which leads teams to rerun, ignore or disable failures until a real regression slips through.

Why a flaky test gives inconsistent results

A flaky test gives inconsistent results because its outcome depends on a hidden input that the test does not control. The visible inputs, such as the code under test and the assertions, stay the same, while an uncontrolled factor such as thread scheduling, wall-clock time, random seeds or the state left by a previous test changes between runs.

The defining property is non-reproducibility under identical conditions. A test that fails every time on a broken build is a correct test. A test that fails one run in fifty on a healthy build is flaky, even when the underlying cause is a genuine race condition in production code, because the failure signal is intermittent and unattributable to a specific change.

The following table lists the most frequent root causes, grouped by the hidden input that varies between runs.

Root causeHidden inputTypical symptom
Asynchronous waitsResponse or rendering timeTimeout or missing element in slow runs
Concurrency and racesThread or event-loop schedulingWrong value or deadlock under load
Test order dependencyState left by earlier testsFails only when run in a full suite
Shared resourcesDatabase rows, files, portsConflicts during parallel execution
Time and datesSystem clock and time zoneFails near midnight or month end
RandomnessUnseeded random generatorsRare failures with unusual values
External servicesNetwork latency and availabilityConnection errors or rate limits
Unordered collectionsHash or set iteration orderAssertion on order fails occasionally
Common root causes of flaky tests

A flaky test is distinct from a broken test and from a test that correctly detects an intermittent product bug, although the three can look identical in a single build log. The distinction matters because each one demands a different owner and a different fix.

Failure kindReproducible on rerunWhere the defect livesCorrect response
Broken testYes, every timeTest code or outdated expectationUpdate the test
Real regressionYes, every timeProduction codeFix the code change
Flaky testNo, intermittentTest design or environmentRemove the hidden input
Intermittent product bugNo, intermittentProduction code timing or stateFix the race in the code
Infrastructure failureUsually notCI runner, network or diskRepair the pipeline
Flaky tests compared with other failing tests

The last two rows explain why automatic retries are risky. A retry hides a flaky test, but it also hides an intermittent product bug that customers will eventually hit. Experienced teams therefore investigate every new flaky failure at least once before classifying it as a test problem.

Detecting and measuring flakiness

Flakiness is detected by observing the same test on the same commit producing both passing and failing results. Continuous integration systems make this visible when a failed job passes after a rerun with no new commit, and many test platforms record such pairs automatically.

The usual metric is the flake rate, the share of runs on unchanged code that fail. Because a single test with a 1% flake rate looks harmless, the important figure is the suite-level probability of a false failure: with 200 tests at 0.5% each, roughly 63% of full runs contain at least one spurious failure.

The detection techniques below differ in cost and in the kind of flakiness they reveal.

TechniqueWhat it revealsCost
Rerun on failure trackingTests that pass after failing on one commitLow, uses existing CI data
Repeated executionLow-probability timing failuresMedium, many runs per test
Randomized test orderOrder dependency and leaked stateLow to medium
Parallel stress runsShared resource conflicts and racesMedium to high
Fault and delay injectionMissing waits and timeout assumptionsHigh, needs tooling
Techniques for finding flaky tests

Frameworks support these techniques directly or through plugins. In pytest, for example, plugins can repeat a test many times or shuffle execution order, and JUnit offers repeated tests and configurable ordering, which makes order dependency visible long before it reaches the main branch.

Fixing and preventing flaky tests

The durable fix for a flaky test is to make the hidden input explicit and controlled. Raising a timeout or adding a sleep only changes the probability of failure; it does not remove the cause and usually makes the suite slower.

Root causeRecommended remedyWhy it works
Fixed sleepsWait for an explicit condition or eventTiming no longer depends on machine speed
Real clockInject a fake or frozen clockDates and durations become deterministic
Unseeded randomnessFix and log the seedFailures can be replayed exactly
Shared stateIsolated test fixture per testNo test sees another test’s data
External serviceMock, test stub or contract testNetwork behavior is removed from the test
Order assertions on setsCompare sorted or unordered valuesIteration order stops mattering
Root cause and recommended remedy

Prevention works best as team policy. Common rules include quarantining a flaky test within a defined time, assigning an owner, tracking it as a defect with a deadline, and refusing to merge new tests that fail a short repeated-execution check. A quarantine without an owner tends to become permanent loss of coverage.

  • Prefer hermetic tests that start from a known state and clean up after themselves.
  • Keep the bulk of checks in fast unit tests, where nondeterminism is easiest to remove.
  • Log seeds, timestamps and environment details so that a failure can be reproduced locally.
  • Treat a rising flake rate as a quality metric with the same weight as test coverage.

Consequences of tolerating flaky tests

Tolerated flakiness damages a team in ways that grow over time. The most serious effect is alert fatigue: once developers learn that red builds are often false alarms, they rerun or ignore failures, and genuine regressions pass unnoticed.

Flaky tests also waste compute and developer time through reruns, block merge queues, and slow down release pipelines that require a green build. In regression testing, a disabled flaky test silently removes protection for the feature it covered, so the apparent stability of the suite can mask shrinking real coverage.

Stripped to the essentials

A flaky test is a check that gives random answers. Sometimes it says the program works. Sometimes it says the program is broken. Nothing has changed in between. It is like a smoke alarm that goes off at random. After a few false alarms, people stop reacting. Then they miss the real fire.

The cause is usually something the test forgot to control. Timing, the clock or leftover data are typical culprits. The fix is to control that hidden factor. Running the test again until it passes is not a fix.

Where it is applied

A web team runs about 1,800 tests on every pull request. One browser-based checkout test fails roughly once in 40 runs, and developers have learned to press the rerun button. Over a month, the team counts more than 300 reruns, each adding about 12 minutes to the pipeline.

An engineer runs the test 500 times in a loop and finds that it fails only when the payment confirmation page loads slower than a fixed two-second sleep. Replacing the sleep with a wait for the confirmation element, and replacing the live payment sandbox with a mock, brings the failure count to zero in 2,000 repeated runs. The team then adds a rule that every new browser test must pass 50 consecutive runs before merging.