Test data, environments and flaky tests
Most flaky tests are not mysteries. They are a wait that is too short, a shared account, a clock nobody controlled or a staging environment someone else deployed to an hour ago: fix the data and the environment, then find, quarantine and measure the rest
Luo et al. studied commits that fixed flaky tests in 51 open-source Apache projects and sorted the root causes. Which cause do you think was the most common?
The test-automation chapter covers flake as a property of a suite: causes, retries, the budget. This chapter goes underneath it. Flake rarely lives in the assertion. It lives in what the test starts from (data), where it runs (environment) and how you find and hold what remains. The artefact is a flaky-test triage log and a test-data plan. The running example is Ojaline, a marketplace with 1,400 staff, about 150 services and 300 engineers, where the checkout team has a gating suite that engineers have stopped trusting.
The model: a test is a function of three inputs
A test passes or fails as a function of the code, the data and the environment. A deterministic test holds the last two constant, so red means the code changed. A flaky test lets one move. Ask three questions of every flake:
- Did the data differ? Another test changed the account, the seed was random, or a fixture aged past its expiry date.
- Did the environment differ? Another team deployed to staging mid-run, a service was a version behind, or the machine was loaded.
- Did the code behave differently with the same inputs? Real non-determinism: a race, an unordered collection, a load-dependent timeout.
Only the third is a product bug. The first two are bugs in your testing system, and they are most of the work. Triage in that order, because the cheap checks rule out most failures before anyone opens a debugger.
Test data
Synthetic, masked or copied
You have three sources of data for tests, and none is free of cost.
| Source | Realism | Privacy risk | Edge cases | Upkeep |
|---|---|---|---|---|
| Synthetic, built by factories | Only as real as you make it | None, if no real record seeds it | You choose them, so you get the ones you thought of | Code, kept with the tests |
| Masked copy of production | High | Residual: depends on how good the masking is | Real oddities you did not think of | Masking rules break whenever the schema changes |
| Statistics from production, then generated | Medium to high | Low | Shaped like production’s real distribution | A data job plus a generator |
The test strategy chapter advises synthetic data, and privacy is not the only reason. Production rarely contains the cases you need: the order with 100 line items, the address with no street number, the wallet that is exactly ₦0. A factory produces them on demand. A masked copy earns its place for slow-query and migration tests and for bugs that only appear in messy data.
Masking fails in recognisable ways. Names are replaced and phone numbers are not. Delivery notes are free text (“leave it with the guard at the blue gate, ask for Mr Ade”) and survive every column rule. Pseudonymised IDs still join across tables, so a record can be rebuilt from its neighbours. Location traces are the worst case: a rider’s overnight GPS trace points to a home. At Ojaline, rider traces should never be a masked copy. Generate them. The Privacy and Data Protection course, not yet written, will cover why re-identification works.
The law that makes copies risky
A copy of production in a test environment is processing of personal data for a new purpose, in a place with weaker controls and many more people with access. A staging database is rarely held to production’s standard.
The Nigeria Data Protection Act 2023 (NDPA) defines personal data in its interpretation section (65) as information relating to an identified or identifiable individual. Section 24 sets out the principles of processing, among them purpose limitation, data minimisation and storage limitation. Section 29 makes a controller that uses a processor, such as a hosted test-data or CI vendor, take reasonable measures, including a written agreement, to ensure the processor complies. Section 41 allows transfers outside Nigeria only where the recipient gives adequate protection or one of the conditions in section 43 applies.as of 2026-11Three consequences for a QA engineer, none of them legal advice. First, badly masked data is still personal data, because the people in it are still identifiable. Whether a masking meets the standard is a question for the data protection officer or counsel, asked before the copy exists. Second, “we need it for testing” is a purpose, so take the fewest fields and rows that serve it and delete the copy on a schedule. Third, a vendor that hosts your copy is a processor, and staging in a foreign cloud region can be a cross-border transfer. Put both questions to the privacy owner in week zero.
For card data the stricter rule is the payment card industry’s: card numbers do not belong in any test database. Use the processor’s sandbox cards, as API, contract and integration testing describes.
Seeding and factories
The cure for most data flake is that every test builds the data it needs, with a unique identity, through the same API or factory the product uses. A shared “test buyer” account is a race waiting for two parallel runs. Where a value is generated, make it replayable: a logged random seed turns “failed once last night” into a failure you can run again.
// test-support/seed.ts: one seed per run, printed so a failure can be replayed
import { randomUUID } from 'node:crypto';
export const SEED = Number(process.env.TEST_SEED ?? Date.now() % 2 ** 31);
console.log(`TEST_SEED=${SEED}`);
// mulberry32, a small seeded generator: same seed, same sequence
export function rng(seed = SEED) {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// test-support/factories.ts: every order is new, money is in kobo
export function buildOrder(overrides: Partial<Order> = {}, next = rng()): Order {
const lines = 1 + Math.floor(next() * 5);
return {
id: `ord_${randomUUID()}`,
buyerId: `buyer_${randomUUID()}`,
lines: Array.from({ length: lines }, () => ({ sku: `sku_${Math.floor(next() * 1000)}`, priceKobo: 50_000 + Math.floor(next() * 9_000_000) })),
...overrides,
};
}
Identity comes from a UUID, so parallel tests never collide. Variation comes from a seeded generator, so a failing order can be rebuilt exactly. A test that needs an edge case passes an override (buildOrder({ lines: [] })) instead of hoping the generator finds it.
Data that ages
Tests pass in March and fail in October because the data aged while the code did not. Four kinds are common at Ojaline:
- Absolute dates in fixtures. A card with expiry
2026-10, a promo code valid until 31 October, a “delivered 10 days ago” order stored with a fixed date. The fixture was correct when written. - Windows in the product. A 7-day return window, a token that lives for 15 minutes. A fixture created at set-up and used after a slow queue can outlive its token.
- Reference data copied once. A catalogue snapshot with last year’s prices and categories that no longer exist.
- Volume. A seed of 200 rows passes the query test that production’s 40 million rows would fail.
The fixes are boring and effective. Express time relative to a pinned clock (daysAgo(8)) instead of in absolute dates; the automation chapter shows how to control the clock. Give long-lived fixtures a valid until and run a nightly check that fails when one is within 30 days of it. Name an owner and a refresh date for every reference dataset. Keep a separate, deliberately large dataset for performance and migration tests.
Environments
Shared staging and its contention
A shared staging environment has a particular failure signature. Tests pass in the morning and fail at 14:00, when another team deploys. A service is two versions behind because its owners have not deployed since Tuesday. Two teams run the same suite against the same accounts. One broken service blocks everyone, and nobody owns it because everyone uses it. With about 150 services, keeping Ojaline’s staging recent and consistent is a coordination problem. A shared staging works for rehearsals and smoke tests. It is poor for gating a pull request, because the result depends on what others did. If a failure rate changes with the time of day, suspect staging before the test.
Ephemeral per-pull-request environments
The alternative is an environment per change, created when the pull request opens and destroyed when it closes, usually a namespace in a cluster deployed by the production pipeline. The design decisions matter more than the tooling:
- Slice, do not clone. You cannot run 150 services per pull request. Deploy the service you changed and its direct dependencies at the pull request’s version, and point everything else at stable stubs or at a shared baseline kept at the main branch.
- Seed it with factories. An ephemeral environment starts empty, which is a feature: it forces tests to build their own data.
- Give it a lifetime. Destroy on merge, on close and after a fixed idle time, or abandoned environments become another shared staging.
- Do not share the sandboxes. Per-pull-request environments multiply calls to a payment sandbox that is rate-limited. Use recorded stubs in the gating run and keep the sandbox for the scheduled check described in API, contract and integration testing.
- Budget it. Measure a month of cost before promising it company-wide.
Ephemeral environments have their own flake, such as a database not ready when the test begins. Make readiness an explicit health check the test waits on.
Parity with production
Parity means behaving like production in the ways that matter to the test, not being a copy. The question is which differences hide which bugs.
| What differs | The bug it hides |
|---|---|
| Replicas: one in staging, many in production | Races, duplicate processing, cache incoherence |
| Data volume | Slow queries, lock contention, migration time |
| Configuration and secrets | The release that works everywhere except where the secret is wrong |
| Feature flags in a different state | A release that was never run in its production flag state |
| Third parties in sandbox mode | Rate limits, signing, latency, error shapes |
| CPU and memory limits | Throttling that only appears under production limits |
| Clock and timezone | Month-end and midnight bugs |
Write the differences down, then decide which to close, which to stub around, and which to accept and cover in production with canaries; testing in production covers the last. Some practitioners argue parity is a trap and production is the only production. They have a point, which argues for testing the differences deliberately.
Flaky tests
Root causes, as Luo et al. name them
Luo, Hariri, Eloussi and Marinov, “An Empirical Analysis of Flaky Tests” (FSE 2014), studied commits that fixed flaky tests in 51 open-source projects and sorted them into ten root-cause categories: Async Wait, Concurrency, Test Order Dependency, Resource Leak, Network, Time, IO, Randomness, Floating Point Operations and Unordered Collections. The three biggest, in order, were Async Wait, Concurrency and Test Order Dependency. Async Wait alone was 45% of the commits classified (74 of 161). Two cautions. The projects are open-source, and a browser suite at a marketplace may rank the causes differently. And the sample is tests someone fixed, which is the flakes that were found, reported and judged worth the effort.
Fowler’s Eradicating Non-Determinism in Tests reaches an overlapping list from practice: lack of isolation, asynchronous behaviour, remote services, time and resource leaks. Use the paper’s names in your triage log, because a shared vocabulary lets you count. This is how the main categories look in a marketplace.
| Category (Luo et al.) | What it looks like at Ojaline | Usual cure |
|---|---|---|
| Async Wait | The test checks the order status before the capture event has been consumed | Wait on a condition or an event, never a fixed sleep; see the automation chapter |
| Concurrency | Two threads race on the wallet balance; the test passes unless the interleaving is unlucky | Treat it as a possible product bug first, since a test failing once in two hundred runs may be the only witness; see data races and check-then-act |
| Test Order Dependency | A test only passes after another test created the seller account | Each test builds its own data; run the suite in random order |
| Resource Leak | A test leaves a connection open, and the 400th test starves | Close in teardown; fail the run when handles leak |
| Network | A call to a stubbed provider goes to the real one when the stub is missing | Fail closed when no stub matches; keep the sandbox for the scheduled suite |
| Time | The test passes except in the minute after midnight or at month end | Pin the clock |
| Unordered Collections | A test compares a list the API returns in no guaranteed order | Sort before comparing, or compare as sets |
| Randomness | A generated value hits an edge case once in a hundred runs | Log the seed; make the edge case its own test |
Detection by rerun
Micco’s working definition is a test that both passes and fails on the same code. The way to see it is to rerun, so a detection plan is a rerun plan, and rerun plans have arithmetic you should know.
If a test fails with probability p on each independent run, n reruns see at least one failure with probability 1 − (1 − p)^n. For a test that fails 2% of the time, 10 reruns find it only about 18% of the time. A hundred find it about 87% of the time. To be 95% sure you need 149. That is why “I reran it and it passed” is weak evidence, and why detection works best as a nightly background job, not as an act of a developer at 10:40. The caveat is independence: runs on the same dirty environment are not independent, so reset it between reruns or you measure contamination.
Rerun in different shapes, one per cause:
- Alone, then in the suite, then in random order. Passing alone and failing in the suite means order dependence.
- Under load and in parallel. Failing only when the machine is busy points at timing: Async Wait, Concurrency or a timeout.
- With the logged seed. A failure that repeats with the same seed is a data problem, not a timing one.
- On a clean ephemeral environment. Passing there and failing on shared staging is an environment problem.
The triage log
Detection produces a list; triage turns it into decisions. The log has one row per flaking test: when and how it failed, the category, the input that moved, the owner, the action and the expiry. Spend a fixed time on each (thirty minutes is a rule of thumb), then fix it or quarantine it with a date. Open-ended investigation is how a flake list grows to four hundred entries. The order of questions is the three inputs again, and only if all come back clean do you suspect the product.
Quarantine with an owner and an expiry
The automation chapter sets the rule: a quarantine with no expiry is where tests go to die. Make the expiry mechanical. A small file lists each quarantined test:
[
{ "test": "capture sweep retries after processor timeout", "owner": "checkout-payments", "ticket": "CHK-412", "since": "2026-11-23", "expires": "2026-12-07", "category": "Async Wait" }
]
The gate excludes those tests (Playwright does it with grepInvert against a tag) and a nightly job still runs them, so results keep arriving. A second small script makes the date bite:
import { readFileSync } from 'node:fs';
const today = new Date().toISOString().slice(0, 10);
const expired = JSON.parse(readFileSync('quarantine.json', 'utf8')).filter((q) => q.expires < today);
if (expired.length) {
console.error(`Quarantine expired for: ${expired.map((q) => `${q.test} (${q.owner})`).join('; ')}`);
process.exit(1);
}
When the date passes, the build fails and the owner chooses: fix, rewrite at a lower level, or delete with a note of what coverage is lost. List each quarantined test’s risk in the risk register, because that risk is uncovered while the test sits there. And bring a test back only on evidence. By the statistician’s rule of three, zero failures in n runs only bounds the failure rate at about 3 / n with 95% confidence, so 300 consecutive passes in the environment where it flaked shows a rate below 1%. Fewer proves little.
Measuring flake rate
Keep the budget measure from the automation chapter: the share of gating runs with a fail-then-pass on the same commit. Add three more, because it cannot tell you where to work.
- Per-test flake rate. Flaky outcomes over executions in a window, reported only for tests with enough executions to mean something. This ranks the list for triage.
- Rate by category and owner. This picks the cure: a framework fix for Async Wait, a data fix for Order Dependency.
- Cost. Reruns multiplied by queue time multiplied by the engineers waiting. It belongs on the dashboard described in quality metrics.
Mind the arithmetic. Small per-test rates compound. If 1,200 tests each flake one run in 10,000, the chance that a whole run contains at least one flake is 1 − 0.9999^1200, about 11%: a suite that looks healthy test by test fails a run in nine. Keep the environment out of the test’s score too. A failure that coincides with a staging deploy is the environment’s flake, and charging it to a test teaches owners to ignore the log.
Day to day
Every morning, fifteen minutes. Read the overnight runs as in the automation chapter. For each failure, ask the three questions in order, starting with the staging deploy log, and log every flake.
During the week. Work the log from the top: highest per-test rate, then highest cost. Spend up to thirty minutes on each: replay with the logged seed, rerun alone and in the suite, check the deploy log for the time of the failure. Then fix it, or quarantine it with an owner, a ticket and an expiry date.
In pull request review. Look for fixed sleeps, shared accounts, absolute dates in fixtures, reliance on another test’s data, unordered comparisons and unstubbed third-party calls. Each is a flake that has not happened yet.
Weekly, thirty minutes, with the engineering leads. Bring the measures, the quarantine list sorted by age and any expiry due that week. Decide each: fix, rewrite, delete. Review environment health: ephemeral environments that failed to start, and how long a broken service blocked staging.
Monthly and quarterly. Monthly, refresh reference data, read the ageing report and check the privacy owner’s list of production-derived copies for deletion dates. Quarterly, re-run the parity table (which difference caused an escape?) and check that per-pull-request environments still pay for themselves.
There is one staging environment and nobody fights over it, because there is one team. Flake comes from sleeps and shared accounts. Write a factory for each core object, pin the clock, and forbid production data in tests: a masked copy is more risk than a ten-person company can manage. Keep the triage log as a page in the repository with five columns. You do not need per-pull-request environments yet. A fresh database per test run, started by the CI job, gets you most of the benefit.
Staging is now contested, and flake is the symptom engineers complain about first. Your first quarter goes on data isolation and the clock, then the log and the quarantine file with real expiry dates. Pilot per-pull-request environments for the two busiest services, sliced and not cloned, and measure what they cost. Agree one flake measure across teams. Ask the privacy owner for a rule on production-derived data before somebody quietly restores a backup into staging for a performance test.
Environments and test data are a platform with owners, a booking queue and a data-masking service, and the problems are scale and politics. With 150 services and 300 engineers, nobody can hold a global staging in a consistent state, so the work is standards: a factory library, a quarantine format, a sliced-environment template, and per-team flake dashboards. Test data touches the data protection officer, procurement for any vendor and the cloud region of every environment. Expect an audit to ask where the production-derived data is, who accessed it and when it was deleted.
Template
# Flaky-test triage log and test-data plan: <team or product>
Author · Date · Review date · Status
## Flake measure
Measure: <share of gating runs with a fail-then-pass on the same commit> · Window: <4 weeks>
Before: <x of y runs = %> · Target: <%> and the source of the target
Per-test rate reported for tests with at least <n> executions.
## Triage log
| Test | First seen | Failures / executions | Category (Luo et al.) | Input that moved (data / environment / code) | Evidence (CI run link) | Owner | Action | Expiry |
|---|---|---|---|---|---|---|---|---|
## Quarantine
Rule: <trigger, owner, ticket, maximum age> · Cap: <% of suite>
Mechanism: <tag or file> · Check on expiry: <what fails or pages>
Return rule: <number of consecutive clean runs, where>
Risks uncovered while quarantined: <risk> -> <mitigation>
## Test data
| Dataset | Source (synthetic / masked / generated) | Owner | Refresh | How it ages | Notes |
|---|---|---|---|---|---|
Production-derived data: <purpose, fields, who can see it, deletion date, privacy owner's answer>
Never in tests: <card numbers, location traces, ...>
Time: <pinned clock; fixtures expressed relative to it>
## Environments
| Environment | Purpose | Real vs stubbed | Shared with | Reset by | Lifetime |
|---|---|---|---|---|---|
## Parity with production
| Difference | Bug it can hide | Closed / stubbed / accepted | Where it is covered instead |
|---|---|---|---|
## Review
Weekly flake review: <who, when> · Monthly data check: <who> · Quarterly parity review: <date>
Re-measure: <date> · If the target is missed: <what changes> WORKED EXAMPLE
Ojaline’s checkout team has 11 engineers and owns 9 of the company’s roughly 150 services. Ebi, the QA engineer, wrote this after four weeks ending Friday 20 November 2026.
Flake measure. The gating suite has 1,200 tests (API and end-to-end). There were 2,400 gating runs in four weeks, and 168 needed a rerun to go green: 7.0%. Thirty-one distinct tests flaked. The top four account for 96 of the 168 runs, 57%. Quarantining those four leaves 72 runs, 3.0%. Target: 2% by the end of December, the ceiling already in the team’s flake budget. Re-measure on Friday 18 December; if the rate is still above 2%, the next four flakiest tests are quarantined and Async Wait is escalated as a framework fix. Every log row links its CI run.
Triage, by category. Async Wait 12, Test Order Dependency 7, Concurrency 5, Time 3, Network 3, Resource Leak 1: 31 in all. All three Network flakes were a missing stub that reached the real processor sandbox; the fix is a stub that fails closed. The five Concurrency flakes all touch the seller wallet. They stay in the log and go to the wallet team first, because a race on a balance may be a product bug.
Quarantine. The top four go into quarantine.json on Monday 23 November, each with an owner, a ticket and an expiry of Monday 7 December, ten working days on. A CI check fails the build on 8 December if any remain. A test returns after 300 clean runs on an ephemeral environment.
Test data. Buyers, baskets and orders: synthetic, built per test. Seller wallets: synthetic, kobo integers. Catalogue: a monthly copy with seller contact fields replaced; the catalogue holds no buyer data. Rider GPS traces: generated by a seeded random walk, never copied, because overnight traces point to homes. Cards: processor sandbox cards only, with expiry set relative to the pinned clock. Fixtures carry valid until, and a nightly job warns 30 days ahead.
Environments. Pull requests get a sliced namespace: the changed service and its direct dependencies, everything else stubbed, destroyed on merge or after 24 hours idle. Staging is booked for release rehearsal only. Parity gaps: staging runs 3 replicas against 24 in production (accepted, covered by a canary), and holds about 2% of production’s order volume (stubbed by a separate large-data suite).
Now you
You have joined Ojaline’s dispatch team, which owns dispatch routing, one of the company’s tier-1 services, and has 14 engineers. The gating suite has 460 tests and a third of runs need a rerun; engineers merge on red. Six teams share one staging environment, and dispatch’s end-to-end tests fail most often between 14:00 and 16:00. The suite uses a masked copy of last year’s rider and order data restored into staging by a former colleague: rider names are replaced, but phone numbers, home-zone fields and overnight GPS traces are not. The data protection officer has asked who can see that copy. Fixtures include delivery slots dated 2026-10-31, and the first scheduled-delivery tests fail every night. The VP of engineering wants flake under 2% by January and a decision on per-pull-request environments. Write the triage log and test-data plan, and say what you will do about the copy.
Self-check
It is Thursday, 09:30, and Ojaline's checkout release goes at 11:00. The release changes how the nightly capture sweep retries after a processor timeout. Ebi has the capture suite's history: 9 of its 38 tests are flaky, each failing about one run in 12 on main for months. Six of the nine cover code the release does not touch, such as receipt emails and ledger posting. Three cover the retry logic that changes. Those three passed 200 of 200 reruns on the last release but failed 2 of 5 runs on this candidate, each time in a different test and passing on rerun. Erhire, the release owner, has to decide in 90 minutes whether the suite blocks the release.
- PAPER An Empirical Analysis of Flaky Tests Qingzhou Luo, Farah Hariri, Lamyaa Eloussi and Darko Marinov, 2014
The source of the root-cause categories used in this chapter: Async Wait, Concurrency, Test Order Dependency and the rest. Read the categories and how the authors fixed each, and keep in mind that the sample is open-source projects. Read: Proceedings of the 22nd ACM SIGSOFT International Symposium on Foundations of Software Engineering (FSE 2014).
- POST Eradicating Non-Determinism in Tests Martin Fowler, 2011
The practitioner's list of causes (isolation, asynchrony, remote services, time, resource leaks) with a cure for each, and the case for a quarantined area. Read it next to the paper to see where the two lists agree.
- POST Flaky Tests at Google and How We Mitigate Them John Micco, 2016
The definition of a flaky test used here, the scale of the problem at Google, and how automated quarantine and flakiness monitoring work. Note what the post says about retries making developers ignore flake.
- DOC Nigeria Data Protection Act 2023 National Assembly of Nigeria, 2023
The primary text. Read the definition of personal data and the principles of processing before you ask for a production copy.
- BOOK Software Engineering at Google, chapter 14: Larger Testing Winters, Manshreck and Wright (eds.), 2020
How Google thinks about the fidelity of test environments, test data and the flakiness of large tests. Read the sections on test data and on flakiness to see the same trade-offs at scale. Read: Chapter 14, free online.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.