How to Find and Fix Flaky Tests in CI
A repeatable way to reproduce, diagnose, and fix flaky tests before they erode trust in your pipeline.
On this page 8 sections
Flaky tests are automated tests that pass and fail on the same code with no change in between. The fix is to reproduce the failure by rerunning the test in a loop, find the source of nondeterminism such as timing, shared state, or the network, and remove it. Quarantine what you cannot fix today and track the flake rate.
Flaky tests waste more engineering time than most teams admit, because each one looks small in isolation. This guide is for developers and engineering leads who own a CI pipeline and want a repeatable way to find and fix flaky tests. Backtrace covers the tooling behind shipping software, and few problems cost more trust than a red build nobody believes.
What Are Flaky Tests and Why Do They Matter?
A flaky test is a test that gives different results on the same code and the same environment. It might pass on your laptop and fail in CI, or fail one run in twenty for no visible reason. The cause is nondeterminism, which means the outcome depends on something the test does not control.
Scale makes the problem worse. In a 2016 post, the Google Testing Blog reported that almost 16% of its tests showed some level of flakiness, and that 84% of observed pass-to-fail transitions involved a flaky test. That means most red builds on a large codebase were not real regressions.
The damage is mostly social. Once engineers learn that a failure is probably noise, they stop reading failures. A real bug then ships behind a rerun button.
How Do You Confirm a Test Is Actually Flaky?
Run the single test many times in isolation on the same commit. If it passes 200 times in a row, the flake probably depends on other tests or on the CI environment. If it fails even a few times, you have a reproducible target.
Use a short loop first, then widen the conditions. The steps below move from the cheapest check to the most realistic one.
- Run the test alone in a loop of 100 or more iterations on your machine.
- Run the whole file, then the whole suite, so you see order effects.
- Shuffle the test order if your runner supports it.
- Limit CPU on a container to mimic a busy CI runner.
- Rerun the failing CI job with debug logging turned on.
Most runners can do this without plugins. Pytest has the pytest-repeat plugin, Jest has --runInBand plus a shell loop, and Go has the -count flag. Write down the failure rate you measure, because you will need it to prove the fix worked.
What Causes Flaky Tests?
Four causes account for most flakes: timing, shared state, test order, and external dependencies. Martin Fowler's article on eradicating non-determinism in tests lists the same families, including lack of isolation, asynchronous behavior, and remote services. Name the family before you touch the code.
Timing and async waits
The classic bad pattern is a fixed sleep. A test that waits 500 milliseconds for a background job passes on a fast machine and fails on a loaded one. Replace the sleep with a wait on the actual condition, such as a polled status or an awaited event, with a generous timeout.
Clocks cause a quieter version of the same bug. Tests that compare against the current time break at midnight, at month end, and across daylight saving changes. Inject a fake clock and the problem disappears.
Shared state and test order
Tests that share a database row, a file, a global variable, or a cache can pass alone and fail together. One test leaves data behind, and the next one reads it. Give each test its own data, or wrap it in a transaction that rolls back.
Order dependence is the same bug in disguise. If test B only passes after test A has run, a parallel runner will eventually schedule B first. Randomizing order in CI turns that hidden dependency into a loud failure on day one.
Network and external services
A test that calls a real third-party API inherits that API's uptime. It also inherits rate limits and slow responses. Stub the network at the boundary and keep a small, separate set of contract tests that run against the real service on a schedule.
Resource limits matter too. Port collisions, full disks, and exhausted file handles show up only when many jobs share one runner. Request random free ports instead of hard-coding them.
How Do You Fix Flaky Tests Step by Step?
Fix the cause, not the symptom, and prove the fix with numbers. A test that failed 3 times in 100 runs should fail 0 times in 500 after your change. Anything less is a guess.
Work through the same sequence for each flake so the process stays boring and repeatable.
- Capture the failure with logs, a seed, and the exact commit.
- Classify the cause as timing, state, order, or external.
- Make the smallest change that removes the nondeterminism.
- Rerun the test in a loop and compare against your baseline failure rate.
- Add a note to the commit message that names the cause.
Good logs shorten this a lot. If your tests only print "assertion failed," you will spend your time reproducing instead of fixing. Backtrace's guide to setting up structured logging in production applies just as well to test output, since a request ID or seed in every log line makes a failure traceable.
Seeds deserve special attention. Print the random seed at the start of every run and accept it as an environment variable. A failure that depends on random data then becomes a reproducible one.
Should You Retry or Quarantine Flaky Tests?
Retries and quarantine are both short-term tools, and neither one is a fix. A retry hides a flake and costs CI minutes. Quarantine removes the test from the blocking path but keeps it running so you can watch it.
Automatic retries are fine when they report. Configure the runner so a test that passed on retry is marked as flaky in the results, not as a clean pass. GitHub documents how to re-run failed jobs in a workflow, but that is a manual rerun and not a flake policy.
| Approach | Blocks the build | Hides the problem | Best used for |
|---|---|---|---|
| Fix the root cause | No | No | Every flake you can reproduce |
| Retry with reporting | No | Partly | Known network blips |
| Quarantine | No | Partly | Flakes you cannot fix this week |
| Delete the test | No | Yes | Tests that cover nothing useful |
Quarantine needs rules or it becomes a graveyard. Each quarantined test gets a ticket, an owner, and a due date of two weeks or less. If nobody fixes it by then, delete it, because a test nobody trusts protects nothing.
How Do You Keep Flaky Tests From Coming Back?
Measure the flake rate and treat it like any other reliability number. Count the share of CI runs that fail and then pass on rerun with no code change. Review that number weekly, and set a target your team agrees on, such as under 1%.
Prevention is cheaper than cleanup. Randomize test order, run tests in parallel on purpose, and block merges that add fixed sleeps or real network calls. A short lint rule catches the most common patterns before review.
Speed and trust are linked. Slow suites push teams toward fewer, bigger tests, and those are the flakiest kind. Backtrace's piece on why AI coding is creating a CI bottleneck explains how a flood of generated code makes an unreliable pipeline hurt more. Keep a fast layer of unit tests, a small layer of integration tests, and a thin layer of end-to-end checks.
Post-deploy checks are a separate job. A handful of smoke tests that catch broken deployments should stay deterministic and cheap, so a red result always means something. Your choice of runner also shapes how you split and parallelize jobs, which is covered in the comparison of GitHub Actions and GitLab CI.
Where Should You Start This Week?
Pick the five tests that failed most often in the last month and fix those first. Your CI history already holds the list, and most teams find that a handful of tests cause most of the noise. Fixing those five usually restores enough trust to make the rest of the work feasible.
Then turn on three habits: print the seed, randomize the order, and report passes-after-retry as flakes. Backtrace's editors recommend starting with reporting, because you cannot fix what the dashboard hides. For another example of a careful pre-production test plan, see how to test a Node.js major version upgrade before production.
Conclusion
Flaky tests are not a mystery. They come from a short list of causes, and each has a standard fix. Reproduce first, name the cause, fix it, and measure the result.
Your next step is small: open your CI history, sort by most frequent failure, and reproduce the top test in a loop today. One fixed flake is worth more than a policy document about flakes.