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 cause | Hidden input | Typical symptom |
|---|---|---|
| Asynchronous waits | Response or rendering time | Timeout or missing element in slow runs |
| Concurrency and races | Thread or event-loop scheduling | Wrong value or deadlock under load |
| Test order dependency | State left by earlier tests | Fails only when run in a full suite |
| Shared resources | Database rows, files, ports | Conflicts during parallel execution |
| Time and dates | System clock and time zone | Fails near midnight or month end |
| Randomness | Unseeded random generators | Rare failures with unusual values |
| External services | Network latency and availability | Connection errors or rate limits |
| Unordered collections | Hash or set iteration order | Assertion on order fails occasionally |
How flaky tests differ from related test failures
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 kind | Reproducible on rerun | Where the defect lives | Correct response |
|---|---|---|---|
| Broken test | Yes, every time | Test code or outdated expectation | Update the test |
| Real regression | Yes, every time | Production code | Fix the code change |
| Flaky test | No, intermittent | Test design or environment | Remove the hidden input |
| Intermittent product bug | No, intermittent | Production code timing or state | Fix the race in the code |
| Infrastructure failure | Usually not | CI runner, network or disk | Repair the pipeline |
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.
| Technique | What it reveals | Cost |
|---|---|---|
| Rerun on failure tracking | Tests that pass after failing on one commit | Low, uses existing CI data |
| Repeated execution | Low-probability timing failures | Medium, many runs per test |
| Randomized test order | Order dependency and leaked state | Low to medium |
| Parallel stress runs | Shared resource conflicts and races | Medium to high |
| Fault and delay injection | Missing waits and timeout assumptions | High, needs tooling |
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 cause | Recommended remedy | Why it works |
|---|---|---|
| Fixed sleeps | Wait for an explicit condition or event | Timing no longer depends on machine speed |
| Real clock | Inject a fake or frozen clock | Dates and durations become deterministic |
| Unseeded randomness | Fix and log the seed | Failures can be replayed exactly |
| Shared state | Isolated test fixture per test | No test sees another test’s data |
| External service | Mock, test stub or contract test | Network behavior is removed from the test |
| Order assertions on sets | Compare sorted or unordered values | Iteration order stops mattering |
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.