Skip to main content

Understanding Flaky Tests

Almost every team that writes automated tests eventually runs into the same maddening experience: a test fails, you re-run it without changing anything, and it passes. Nothing was fixed. Nothing was different. The test simply gave two different answers to the same question.

That is a flaky test, and it is one of the most corrosive problems in software engineering โ€” not because any single flaky test is catastrophic, but because flakiness quietly erodes the one thing a test suite exists to provide: trust. A suite you cannot trust is barely better than no suite at all.

This guide builds an understanding of flaky tests from the ground up. It starts with what flakiness actually is, moves through how you encounter it in real projects and the damage it does, then works through the common root causes, how to detect and diagnose flaky tests, and finally how to fix and prevent them. Read straight through to build the full picture, or stop at the depth that answers your question.


What is a flaky test, exactly?โ€‹

A flaky test is a test that produces different results โ€” pass or fail โ€” without any change to the code being tested or the test itself. Run it ten times against the exact same commit and it might pass eight times and fail twice.

The key word is non-deterministic. A normal test is deterministic: same input, same code, same result, every time. A flaky test has some hidden source of variability that the test's outcome secretly depends on โ€” timing, ordering, environment, shared state โ€” so its result is partly a matter of luck.

The crucial point is that a flaky test is not giving you real information. When it fails, you do not know if it found a bug or just lost a coin toss. That ambiguity is the entire problem.


Is a flaky test the same as a failing test?โ€‹

No, and the distinction matters.

A failing test is doing its job. It consistently reports a problem: the code is wrong, or the test's expectation is wrong. Either way, it is telling you something true and actionable.

A flaky test is failing to do its job. It reports a problem sometimes, regardless of whether a problem exists. It is not a signal โ€” it is noise that occasionally looks like a signal.

This is why flaky tests are arguably worse than tests that are simply broken. A consistently broken test gets noticed and fixed. A flaky test lingers, because "just run it again" makes the pain disappear just often enough that nobody deals with the root cause.


How do I encounter flaky tests in a real project?โ€‹

Flakiness rarely announces itself. It shows up as a series of small, familiar frustrations:

  • A pull request's CI run fails. You read the error, see it is unrelated to your change, hit "re-run," and it passes. You merge and move on.
  • The same test name shows up red across many unrelated pull requests over a few weeks.
  • A test passes reliably on your laptop but fails intermittently in CI โ€” or the reverse.
  • The full suite fails, but running that one test in isolation always passes.
  • A test starts failing only after the team parallelised the test run to make it faster.
  • A nightly build is red roughly a third of mornings, and the team has stopped reading the report.

Notice that none of these feels like a crisis in the moment. That is exactly how flakiness takes hold โ€” each instance is individually easy to dismiss, so it accumulates instead of getting fixed.


How common is this, really? Is my team unusual?โ€‹

It is extremely common, and no, your team is not unusual.

Flaky tests are a well-documented problem at organisations of every size, including the largest and most sophisticated software companies in the world, all of which have published about fighting it. Any test suite of meaningful size, exercised long enough, will develop flaky tests. The probability is effectively 100% given enough tests and enough time.

So the realistic goal is not a permanently flake-free suite. It is building the practices โ€” detection, diagnosis, quarantine, fixing โ€” that keep flakiness controlled instead of letting it take over. Treat flakiness as an ongoing condition to manage, not a one-time bug to eliminate.


Why are flaky tests such a serious problem? It is just one re-run.โ€‹

Because the cost is never one re-run. The damage compounds across several dimensions:

  • Eroded trust. Once developers learn a suite has flaky tests, they stop believing any failure. The natural response to a red build becomes "just re-run it" rather than "investigate it."
  • Masked real bugs. This is the dangerous part. When the team's reflex is to re-run on failure, a genuine failure gets the same treatment โ€” re-run, maybe pass by luck, merge the bug. Flakiness trains people to ignore the exact signal the suite exists to send.
  • Wasted time and money. Every re-run consumes CI compute and, more expensively, human attention and context-switching. Across a team this adds up to a serious, continuous tax.
  • Slower delivery. Flaky failures block pull requests, delay merges, and stretch out release cycles.
  • Demoralised engineers. Few things are as draining as being blocked by a failure that is not your fault and not even real.

The single worst consequence is the second one. A suite with enough flakiness does not just waste time โ€” it actively conceals the bugs it was built to catch.


What is "the boy who cried wolf" got to do with flaky tests?โ€‹

It is the most accurate mental model for the real danger.

A flaky test cries "failure!" so often, and so often falsely, that the team learns to ignore it. Then one day the failure is real โ€” a genuine regression โ€” and it gets ignored exactly like all the false alarms before it. The bug ships.

This is why a flaky test is not a neutral annoyance. It does measurable harm: it systematically lowers the team's sensitivity to real failures. A test that lies often enough makes the whole suite less trustworthy, and an untrusted suite cannot do its job.


What actually causes a test to be flaky?โ€‹

Almost all flakiness traces back to a hidden dependency on something non-deterministic โ€” something the test's result quietly relies on, but which is not guaranteed to be the same on every run. The usual culprits:

  • Timing and asynchrony โ€” the test assumes an operation finishes within some window, and sometimes it does not.
  • Test-order dependency โ€” the test only passes if another test ran (or did not run) before it.
  • Shared mutable state โ€” tests reuse a database, a file, a cache, or a global variable and interfere with each other.
  • Concurrency and race conditions โ€” parallel execution exposes ordering bugs that serial runs hide.
  • External dependencies โ€” a real network call, third-party API, or remote service that is occasionally slow or down.
  • Environment differences โ€” time zone, locale, OS, screen size, CPU speed, available memory.
  • Randomness and unstable data โ€” unseeded random values, timestamps, "today's date," auto-generated IDs.
  • Resource limits โ€” a slow or overloaded CI machine that misses timeouts a fast laptop meets.

The following questions take the most important of these in turn.


How does timing cause flakiness?โ€‹

Timing is the single most common cause, especially in tests that touch UIs or asynchronous code.

The classic mistake is the fixed sleep: the test says "wait 2 seconds, then check the result." That 2 seconds is a guess. On a fast run the operation finishes in 200 ms and the test wastes time but passes. On a slow run the operation takes 2.5 seconds, the test checks too early, sees nothing, and fails. Same code, different machine load, different result.

The deeper issue is that the test assumes a duration when what it actually cares about is a state. It does not really want "two seconds to pass" โ€” it wants "the data has loaded." The fix, covered later, is to wait for the condition, not the clock.


How does test order cause flakiness?โ€‹

A test should be a self-contained statement: given this setup, this is true. An order-dependent test breaks that contract โ€” it secretly relies on something a different test did.

For example: Test A creates a user record and does not clean it up. Test B assumes that user exists. As long as A runs before B, B passes. Then the test runner shuffles the order, or runs tests in parallel, or someone runs B alone โ€” and B fails, because the thing it depended on was never created.

This kind of flakiness is sneaky because the test is not "wrong" in isolation; it is wrong about its own boundaries. It often surfaces the day a team randomises test order or turns on parallel execution โ€” the tests did not change, but their hidden assumptions were exposed.


How does shared state cause flakiness?โ€‹

Shared mutable state is order-dependency's bigger sibling. When multiple tests read and write the same resource โ€” a shared database, a file on disk, a cache, an environment variable, an in-memory singleton โ€” they can corrupt each other's assumptions.

Test A writes 100 rows and expects a count of 100. Test B, running just before or in parallel, adds a row. Now A sees 101 and fails. Neither test is individually wrong; they are wrong together, because they share a resource that neither fully controls.

The fix in principle is isolation: each test should get its own clean state โ€” its own transaction rolled back at the end, its own temporary directory, its own fresh fixtures โ€” so no test can ever see another test's leftovers.


How do external dependencies cause flakiness?โ€‹

If a test makes a real call to something outside its control โ€” a third-party API, a payment sandbox, a remote service, even DNS โ€” then the test's reliability is now capped by that thing's reliability.

The external service might be briefly down, rate-limit you, return a slow response, or have its data change underneath you. None of that is a bug in your code, but all of it makes your test fail intermittently.

The deeper principle: a test should fail only when the thing it is testing is broken. If a test for your checkout logic fails because someone else's API had a bad minute, that test is testing the wrong thing. The fix is usually to replace the real dependency with a controlled stand-in โ€” covered later.


How do randomness and environment differences cause flakiness?โ€‹

Both are hidden inputs the test author did not realise they were depending on.

Randomness: a test that uses unseeded random data, the current timestamp, or an auto-generated ID will occasionally produce a value that hits an edge case โ€” an empty string, a leap-second date, a number that happens to round differently. It passes most of the time and fails when the dice land badly.

Environment: a test can quietly assume a time zone ("the date is the same before and after this operation" โ€” true in UTC, false near midnight elsewhere), a locale (decimal commas vs points), an OS (file path separators), or a screen size. It passes on the developer's machine and fails on CI because CI is configured differently.

Both share a cure: make the hidden input explicit and fixed. Seed the random generator. Inject a fixed "current time." Pin the time zone and locale. Remove the variability instead of hoping it lands well.


My test passes locally but fails in CI. Why?โ€‹

This is one of the most common flakiness reports, and it almost always means the test depends on an environment difference between the two places. Likely causes:

  • CI is slower (or under more load), so timing-sensitive tests miss their windows.
  • CI runs tests in parallel or in a different order, exposing order- and state-dependencies your local serial run hid.
  • CI is configured differently โ€” different time zone, locale, OS, environment variables, or screen resolution.
  • CI starts from a clean slate every time, while your local machine has accumulated state โ€” leftover database rows, cached files โ€” that the test secretly relies on.
  • CI has different resource limits โ€” less memory or CPU than your laptop.

The takeaway: "passes on my machine" is not evidence the test is sound. It is evidence the test depends on something your machine happens to provide. The honest fix is to make the test independent of all of it.


How do I even detect which tests are flaky?โ€‹

You cannot fix what you cannot see, and flakiness is hard to see because it hides in noise. The core detection techniques:

  • Re-run failures automatically. Configure CI so that a failed test is retried. If it fails then passes with no change, that retry is itself a flakiness signal โ€” record it.
  • Track results over time. Store the pass/fail history of every test across every run. A test that has both passed and failed on the same commit is, by definition, flaky.
  • Run tests repeatedly on a stable commit. Periodically execute the suite many times against a known-good commit. Anything that is not 100% green is flaky.
  • Randomise test order deliberately. Regularly shuffle the execution order; tests that only fail under shuffling are order-dependent.
  • Compute a flakiness score. Rank tests by how often they flip, so you can prioritise the worst offenders.

The shared principle: make flakiness measurable. Flakiness that is only ever felt as vague frustration never gets fixed. Flakiness that shows up as a number on a dashboard does.


A test is flagged as flaky. How do I diagnose the cause?โ€‹

Diagnosis is detective work. A practical sequence:

  1. Reproduce it. Run the test in a loop โ€” dozens or hundreds of times โ€” until it fails. A flaky test you cannot reproduce, you cannot confidently fix.
  2. Run it in isolation. If it passes alone but fails in the full suite, the cause is external: order-dependency or shared state, not the test's own logic.
  3. Vary one thing at a time. Change the order, the parallelism, the machine speed, the locale. Whichever change makes it flip points straight at the cause.
  4. Read it for the usual suspects. Look specifically for fixed sleeps, real network calls, shared fixtures, unseeded randomness, and reliance on the current date or time.
  5. Capture evidence on failure. Logs, screenshots, the full state at the moment of failure. Because the failure is intermittent, you must grab the evidence the one time it happens.

The goal is to convert "this test is flaky" into a specific sentence: "this test fails when it runs after the import test, because they share a database row." Once the cause is that concrete, the fix is usually obvious.


What do I do with a flaky test right now, before I have time to fix it?โ€‹

This is where quarantine comes in, and it is a genuinely important practice.

Quarantining means moving a known-flaky test out of the path where it can block work โ€” for example, into a separate group that still runs and is still reported, but does not fail the build or block a pull request.

Quarantine deliberately makes two trade-offs:

  • It stops the test from blocking the team and from training everyone to ignore failures. That is the benefit, and it is real.
  • It gives up that test's coverage until the test is fixed. That is the cost, and it is also real.

Two rules keep quarantine healthy. First, quarantine is a waiting room, not a graveyard โ€” a quarantined test must come with a ticket and an owner, or it will be forgotten forever. Second, watch the size of the quarantine. A handful of tests is managing the problem; a hundred is hiding it. A growing quarantine is a warning sign in its own right.


How do I actually fix a flaky test?โ€‹

The fix always follows from the cause โ€” which is why diagnosis matters so much. The standard remedies, matched to the standard causes:

  • Timing flakiness โ†’ replace fixed sleeps with waiting for a condition. Instead of "sleep 2 seconds," poll: "wait until the element is visible, up to 10 seconds." The test now adapts to whatever speed the machine actually runs at.
  • Order-dependency โ†’ make each test self-contained. It must create everything it needs and assume nothing from other tests.
  • Shared state โ†’ enforce isolation. Each test gets its own clean fixtures โ€” its own database transaction rolled back afterward, its own temp directory โ€” so nothing leaks between tests.
  • External dependencies โ†’ replace the real service with a controlled test double: a mock, stub, or fake that returns predictable responses instantly. Test your code, not someone else's uptime.
  • Randomness โ†’ seed the random source and inject a fixed clock so "now" is a value you control.
  • Concurrency bugs โ†’ here, pause. A test that flakes under parallel execution may have found a real race condition in the production code. Investigate before you "fix" it โ€” see the next question.

The meta-pattern across all of these is the same: find the hidden non-deterministic input and make it deterministic โ€” control it, fix it, or replace it.


Should I ever just delete a flaky test?โ€‹

Sometimes โ€” but it should be a deliberate decision, not a shortcut.

Deleting is reasonable when the test genuinely provides little value: it is redundant with other tests, it tests something trivial, or it is so poorly written that rewriting is cheaper than repairing. Removing a low-value test that produces high noise can be a net improvement.

Deleting is the wrong move when it is really coverage abandonment in disguise โ€” quietly dropping a test for important behaviour because diagnosing it is annoying. That does not remove the risk; it just removes your ability to see the risk. The bug the test would have caught can still ship; now nothing will warn you.

The honest rule: delete a flaky test only if you would be comfortable deleting it even if it were perfectly reliable. If the answer is no, the test is worth keeping โ€” so fix it or quarantine it instead.


Could a flaky test be revealing a real bug?โ€‹

Yes โ€” and this is the most important idea in the whole guide, the one that should change how you react to flakiness.

It is tempting to treat every flaky test as a bad test. But sometimes the test is fine and the product code is the thing that is non-deterministic. A test that fails intermittently under parallel execution may have uncovered a genuine race condition in your application โ€” a real bug that will eventually bite real users, just less predictably than the test.

So "flaky" is a description of a symptom, not a diagnosis of fault. Before you dismiss a flaky test as merely annoying, ask honestly: is the test unreliable, or is it correctly reporting that my code is unreliable? If it is the latter, that test is one of the most valuable in your suite, and "fixing the flakiness" by silencing the test would be hiding a real defect.


How do I prevent flaky tests in the first place?โ€‹

Prevention is cheaper than cure, and it comes down to writing tests that have no hidden non-deterministic inputs to begin with. The durable habits:

  • Make every test independent. It sets up its own state, cleans up after itself, and assumes nothing about order or about other tests.
  • Never use fixed sleeps. Always wait for an observable condition, never for a guessed duration.
  • Isolate state. Fresh fixtures per test; no shared mutable resources.
  • Control all the inputs. Seed randomness, inject a fixed clock, pin time zone and locale.
  • Avoid real external calls in anything but a small, clearly-labelled set of integration tests. Default to test doubles.
  • Run tests in random order and in parallel from day one, so hidden dependencies are exposed immediately rather than discovered months later.
  • Treat a new flaky test as a defect. The cheapest flaky test to fix is the one caught the week it was introduced.

What does a healthy long-term approach to flakiness look like?โ€‹

Because some flakiness is inevitable in any large, long-lived suite, the mature goal is not zero flaky tests forever โ€” it is a system that keeps flakiness controlled. That system has four parts, working continuously:

  1. Detection โ€” flakiness is measured and visible on a dashboard, not just felt.
  2. Containment โ€” newly-discovered flaky tests are quarantined fast, so they never get the chance to erode trust in the build.
  3. Resolution โ€” quarantined tests have owners and tickets, and get fixed or deliberately removed; the quarantine does not grow unbounded.
  4. Prevention โ€” the team writes deterministic tests by habit and treats new flakiness as a real defect.

A team that does all four can trust its test suite even though individual tests will always occasionally misbehave. A team that does none of them slowly slides toward a suite nobody believes โ€” which is the real failure state, far worse than any single flaky test.

That is the whole point. Fighting flakiness is not about chasing perfection. It is about protecting trust โ€” because a test suite is only worth running if the team believes what it says.


Where to go nextโ€‹