Sub topic 11
Keeping flaky tests from blocking merges
This chapter assumes you know how required status checks and branch protection work, and that you can read a GitHub Actions workflow. Earlier chapters placed fast checks on pull requests. Here the question is what to do when one of those checks fails for reasons unrelated to the change.
What a flaky test is
A flaky test is a test that gives different results on the same code. It fails on one run and passes on the next, with no change to the commit or the test.
A flaky test is not the same as a broken test. A broken test fails every time and points at a real defect. A flaky test fails sometimes, so its failure carries little information. If a test fails 5% of the time without a cause, most of its failures are noise.
Flakiness matters more on pull requests than anywhere else. A required check that fails at random blocks merges, wastes reruns, and teaches developers to click "re-run" without reading the log. Once people do that, real failures get rerun too, and a real regression can slip through.
Common causes
Knowing the cause tells you whether to fix the test or move it.
- Timing. Fixed sleeps, race conditions, and assertions that run before async work finishes.
- Shared state. Tests that depend on execution order, a shared database, or files left by an earlier test.
- Time and randomness. Tests that use the current date, time zones, or unseeded random values.
- External services. Calls to real networks, third-party APIs, or rate-limited endpoints.
- Resource limits. Tests that pass on a fast laptop and time out on a loaded shared runner.
- Test infrastructure. Runner out of disk, image pull failures, or a dependency registry outage. These are not test bugs, but they look the same in the merge UI.
The last category needs separate handling. A failure in npm ci because the registry timed out is an infrastructure flake. Retrying the step fixes it, and quarantining a test does not.
Measuring before acting
Do not label a test flaky because it failed once. Collect evidence in two ways.
- History on the same commit. If a job fails and then passes on a rerun of the same commit SHA, one of those runs was a flake. Count these events per test over the last 30 days.
- Repeated local or CI runs. Run the suspect test many times against one commit and count failures.
This script gives a failure rate for any command:
#!/usr/bin/env bash
# Usage: ./flake-rate.sh 20 npx jest tests/checkout.test.js
set -u
runs="$1"
shift
failures=0
for i in $(seq 1 "$runs"); do
if ! "$@" > /dev/null 2>&1; then
failures=$((failures + 1))
fi
done
echo "failed ${failures} of ${runs} runs"A result such as failed 3 of 20 runs is a 15% failure rate. A test with that rate will fail at least one of every few pull request runs. A test that fails 1 in 500 runs is a smaller problem, but it still matters if it runs on hundreds of pull requests a week.
Run the script under conditions close to CI. Flakes that depend on a slow, shared runner often vanish on a local machine. Running tests in random order or in parallel can also expose shared-state flakes.
The flaky test lifecycle
Treat flakiness as a state a test can enter and leave, not a permanent label.
The deadline in the last step is important. A quarantine without an expiry date becomes a graveyard of tests that nobody runs and nobody trusts.
Quarantine: keep running the test, stop blocking on it
Quarantine means the test still runs and still reports, but its result no longer gates the merge. This keeps the signal you can gather (failure rate, error messages) while removing the cost.
Do not just delete the test, and do not just add skip. A skipped test produces no data, and nobody notices when it is forgotten.
One practical approach is a file naming convention. Tests that are quarantined move to files ending in .quarantine.test.js. Two npm scripts then split the suite. This example uses Jest:
{
"scripts": {
"test": "jest --testPathIgnorePatterns \"\\.quarantine\\.test\\.js$\"",
"test:quarantine": "jest --testPathPattern \"\\.quarantine\\.test\\.js$\""
}
}The workflow then has one required job for the stable tests and one non-blocking job for quarantined tests:
name: pr
on:
pull_request:
branches: [main]
jobs:
fast-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm run lint
- run: npm test
quarantine:
runs-on: ubuntu-latest
continue-on-error: true
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm run test:quarantineMark only fast-checks as a required status check in branch protection. The quarantine job runs on every pull request, but a failure does not block the merge.
Running quarantined tests only in the nightly workflow is often the better choice. It removes their runtime from pull requests and gives you one run per day of clean, repeatable data. The cost is slower evidence: you get one data point per night instead of many per day.
Retries: useful, but use them carefully
Automatic retries reduce the number of flaky failures reaching developers. They also hide the problem. Compare the options:
| Approach | Effect on merges | Effect on visibility | Main risk |
|---|---|---|---|
| Rerun the whole job by hand | Unblocks after a delay | None, unless someone logs it | Developers stop reading failures |
| Automatic retry of a failed test | Unblocks without human action | Low, unless retries are reported | Hides a 30% flake that passes on the third try |
| Quarantine | Unblocks permanently for that test | High, if results are published | Quarantine grows with no deadline |
| Fix the test | Removes the cause | Not applicable | Costs engineering time |
If you use retries, follow three rules:
- Retry only individual tests, not whole jobs, so one flake does not repeat a ten-minute build.
- Limit retries to one or two. A test that needs more is not a minor flake.
- Report every test that passed only after a retry. Treat that as a flaky event for the measurements above.
A retried-and-passed test is still a flaky test. Retries change who feels the pain, not whether the pain exists.
Handling infrastructure flakes separately
Retry infrastructure steps at the step level, where the failure is clearly not a test result. Downloading dependencies is the usual case. Use the retry features your package manager provides, or a small wrapper, rather than rerunning the whole workflow. Keep that separate from test retries, so a registry timeout never gets counted against a test.
If the runner itself is the problem, such as running out of memory under parallel tests, no quarantine will help. Reduce parallelism, raise resource limits, or split the job. The chapter on runtime budgets covers that.
Policies that keep trust intact
A few rules make quarantine work in practice:
- Every quarantined test has an owner and a ticket. The owner is a person or team, not "everyone."
- Every quarantine has an expiry. Two to four weeks is typical. At expiry the test is fixed, rewritten, or deleted.
- Set a visible cap. If more than a small fraction of tests are quarantined, stop adding to the list and fix existing ones first.
- New flaky tests do not enter main. If a new test is flaky in review, fix it there. Quarantine is for tests already in the suite.
- Do not quarantine to hide a real bug. If a test fails because of a race condition in the product code, the test is doing its job. Check this before moving it.
Relationship to the other stages
Flaky tests affect each stage differently. On pull requests, a flake blocks one developer and wastes minutes. At merge time with a merge queue, a flake ejects a candidate commit and delays everyone behind it in the queue. In nightly builds, a flake produces a false alarm that someone has to triage. That is why merge queues are the least forgiving place for flaky tests, and why the next chapter on nightly triage depends on knowing which failures are known flakes.
A test that is flaky because it is slow or because it uses real external services often belongs in a later stage anyway. Moving it from pull requests to nightly applies the placement framework from earlier chapters, and it is a legitimate fix when the test cannot be made deterministic cheaply.
Exercise
A required fast-checks job fails on a pull request. A developer reruns it on the same commit and it passes. Over the past month this has happened 12 times, always for the same test, checkout.test.js. The test calls a real payment sandbox API. Name two sensible actions, and explain why adding continue-on-error: true to the required job would be the wrong response.
Show answer
First, measure the failure rate with repeated runs, then quarantine the test with an owner, a ticket, and an expiry date, or move it to the nightly workflow, since it depends on an external service. Then fix it by replacing the sandbox call with a stub or mock in unit tests, and keep a smaller real-API check in a later stage. Adding continue-on-error: true to the whole required job would make every failure in that job non-blocking, including real lint and unit test failures, and the job would report as passing. Only the single flaky test should be moved out of the blocking path.
Exercise
Your team enables automatic retries of up to five attempts for every test, and the number of developer complaints about flaky failures drops. Why might the suite be less healthy than before?
Show answer
Retries hide flakiness instead of fixing it. A test that fails 40% of the time will usually pass within five attempts, so it stays in the suite unnoticed, adds runtime, and may mask real intermittent bugs in the product. To keep retries useful, limit them to one or two attempts and report every test that needed a retry so it counts as a flaky event.