A flaky test is one whose result depends on something it does not control: event order, other tests' data, the environment, the clock. Causes fall into four sources: the test (synchronisation, order), the data, the environment and the product itself, where it can be a real race condition. The cause is found by repeated runs with one and several workers and by the trace, not by a retry or a pause.
System design · Flaky tests
A test fails one run in ten and explains nothing. Is the bug in the test or in the product?
A test checks the balance after a transfer. In CI it passes nine runs out of ten, and on the tenth it fails with "Expected 70.00, received 100.00". A rerun is green. Someone writes "flaky, rerun" and moves on. A month later there are ten such tests, nobody reads the red pipeline, and a real regression drowns in the noise. This lesson is about where instability comes from, how to find the cause in a few runs, and why "just add a retry" is not an answer.
How it works and why. A flaky test is a test whose result depends on something the test does not control: the order of events, somebody else's data, the state of the environment, the clock. The code is the same, the inputs differ, so the result differs. The causes fall into four sources: the test itself (synchronisation, order dependence), the data (a shared account, leftovers of a previous run), the environment (an overloaded staging, a slow third-party sandbox, the network) and the product (a real race condition). The first three are cured in the test or the infrastructure; the fourth is a bug that the test catches by accident.
Four sources of instability
Figure 1. The first three rows are fixed in the test, the data or the infrastructure. The last one is fixed by development, and a retry must not hide it.
The most common concrete causes, most frequent first:
Synchronisation. The test reads the state before the UI or the backend has updated it. A manual textContent() read is not retried, and waitForTimeout guesses the time.
Shared data. Parallel workers change one account: one withdraws, another finds no money.
Order. The test only works after another test has created the record it needs.
Asynchronous backend. The transfer goes through a queue, and the test checks the balance at once.
Time. The test fails at midnight, on the last day of the month or in another time zone, because it compares with the real date.
Environment. A loaded staging, a third-party sandbox timeout, a slow CI agent.
Example: from flaky to fixed. The test from the start of the lesson looks like this:
What: a plain toBe check: it compared once and failed. There is no Timeout and no Call log, which a check with a wait would show.
Values:Received is the old balance the test read at the moment of the call. Whether it updated later is visible only in the trace.
Where: line 4: expect received an already read text, so there is nothing to retry.
What to do
Open the trace and see what the balance showed at that moment. Old, then correct: replace the read with await expect(locator).toHaveText('70.00'). Wrong even after waiting: a product defect.
Figure 2. A typical Playwright error text (shortened): the numbers lead to the explanations.
textContent() returns the value at the moment of the call and does not wait. If the UI updates 200 ms after the click, the test is green on a fast machine and red on a loaded CI. First we reproduce the failure instead of guessing:
# 1. the single test, 20 times, no retries, in parallel
npx playwright test transfer.spec.ts -g "updates the balance" \
--repeat-each=20 --retries=0 --workers=4
# 2. the same with one worker
npx playwright test transfer.spec.ts -g "updates the balance" \
--repeat-each=20 --retries=0 --workers=1
We read the result as a diagnosis. It fails in both modes: the problem is in the test or the product (synchronisation, time). It fails only with several workers: shared data or order dependence. It fails only in CI: the environment or the agent's resources. For our test it fails in both, so we open the trace: at the moment of the check the balance is still old, and a moment later it is 70.00. That is synchronisation. The fix is a web-first assertion that retries the check until the timeout:
If instead the failure disappears with --workers=1, the cause is data. It is cured by a separate account for every test through a fixture, not by the run order:
(createAccount and deleteAccount are hypothetical project helpers that call its API.)
A product bug or a flaky test. This is the main fork. If in the trace the UI really showed a wrong amount, not just "not updated yet", it may be a race condition in the product. The signs: the failure does not go away after a correct wait, it depends on parallel requests, it produces a wrong value rather than a missing one. Some "unstable" tests are in fact the only thing that sees a real concurrency problem.
The same red test, two diagnoses
Test
The value appears later
In the trace the state is first old, then correct. Cured by waiting for a condition or by isolating data.
Product
The value is wrong
The balance is wrong even after waiting, or depends on parallel requests. This is a bug: file a defect.
Figure 3. Not everything unstable is a test mistake. Diagnose first, fix second.
Limits and alternatives. Web-first assertions do not help when the wait is already right and the source itself is unstable: a third-party sandbox with random timeouts is cured by a mock or stub at the test level, not by a longer timeout. Time is cured by a controlled clock (page.clock in Playwright), not by "do not run at night". Order is cured by independent tests; if the steps are truly sequential there is a serial mode, but it repeats the whole block on failure and costs more. The logic is the same in Cypress and Selenium: Cypress's automatic command retries and Selenium's explicit waits replace fixed pauses.
Common mistakes.
waitForTimeout(3000) instead of a condition: it wastes time on a fast machine and is still too short on a slow one.
Reading a value through textContent() or isVisible() and comparing by hand: these calls are not retried.
One shared test account for all workers: the failure depends on who got there first.
Curing the symptom with a longer timeout: the test gets slower and the cause stays.
Calling a test flaky without looking at the trace: a real race condition can be missed.
Check yourself
A test passes 20 times in a row with --workers=1 and fails in a third of the runs with --workers=4. What is the most likely cause and what to check first?
Answer
Shared state between tests: one account or record changed by parallel workers, or an order dependence. Check whether the test creates its own data and whether it relies on another test's record. The cure: unique data per test through a fixture.
In the trace the test fails because the balance is 100.00 instead of 70.00, and a second later the balance is already right. Can we add retries: 2 and close the matter?
Answer
No. This is synchronisation: the check runs before the update. A retry hides the problem and the test stays wrong. We need a web-first assertion (toHaveText) or expect.poll for a backend value. But if the balance stayed wrong after waiting, it would be a product bug.
Related lessons: "The process of fighting flakiness: detect, isolate, fix", "Retries: when they help and when they hurt", "Test data strategies".
In the interview.Junior: The most common causes of flakiness are synchronisation, shared data, order dependence and an asynchronous backend. Instead of fixed pauses I wait for a condition with web-first assertions. Middle/Senior: I split the cause into test, data, environment and product, reproduce the failure with --repeat-each using one and several workers, and read the trace. If the value is wrong even after waiting, it may be a race condition in the product, so I treat the "unstable" test as a potential defect, not as noise.
The process of fighting flakiness: detect, isolate, fix
Fighting flakiness is a process with four states and an owner for each test: detect, isolate, fix, return. A flaky test is taken off the blocking path into quarantine, but with an owner and a deadline, otherwise quarantine becomes a graveyard. After the fix a test returns to the gate only after many runs: ten clean runs at a 10% failure rate prove almost nothing.
System design · Flaky tests
Ten flaky tests in the gate, and the team already hits "Re-run". How to stop the decay?
One engineer fixing tests one at a time does not scale: new unstable tests appear faster than old ones get fixed. So you need a process with four states and an owner for each test: detect, isolate, fix, return. This lesson shows how to set it up without a hand-kept list of "who knows what" and where the process usually breaks.
How it works and why. The flaky problem is not technical but social: as soon as a red run stops being read, the gate loses its meaning. So the process solves two tasks. First: take unstable tests off the blocking path so red again means "something broke". Second: do not let them get lost, so that each one has an owner and a deadline. Quarantine without that only postpones the problem.
Life cycle of a flaky test
Figure 1. Quarantine is a temporary station, not a destination: it has a deadline.
Detection. Playwright marks a test that failed and then passed on a retry as flaky in the report; these results must be stored between runs, otherwise you only see today's noise. A test with several such marks in a week is a quarantine candidate. In addition, a nightly job runs the suite with --repeat-each=5 and finds unstable tests before they land in other people's PRs. The --fail-on-flaky-tests flag makes a run red if even one test passed only on a retry: useful in the nightly run where a retry exists for diagnostics, not for a green colour.
Quarantine. The simplest way in Playwright is a tag that excludes the test from the blocking run and a separate non-blocking job that runs it. The test stays visible, it just does not stop the merge:
# blocking gate: everything except quarantined tests
npx playwright test --grep-invert @quarantine
# non-blocking job: only quarantined tests, with diagnostics
npx playwright test --grep @quarantine --retries=0 --trace=on
An annotation with a ticket number appears in the report, so the owner and the deadline are visible right next to the test. The alternative test.fixme() turns the test off completely and it is easier to forget it: a tag with a separate job keeps the test in sight.
A quarantine record for a test
Typical
Test transfer shows the new balance
Cause flaky
Owner none
Deadline none
Return none
The test has simply left the gate. Half a year later nobody will come back to it.
Better
Test transfer shows the new balance
Cause data: a shared account
Owner the test author
Deadline two weeks
Return 30 runs with no retries
The cause class, the owner and the deadline are written down, so quarantine stays a temporary station.
Figure 2. The same test in two records: the difference is in the fields that must be filled in.
Analysis. The trace from the non-blocking job, the video, backend logs by correlation id. The goal is not to "fix" but to classify: test, data, environment or product. The class decides who fixes it: the test author, the data owner, the infrastructure team or development. Write the class into the ticket: after a month you can see where most instability comes from.
Return. After the fix the test is run many times and only then returned to the gate:
npx playwright test transfer.spec.ts --repeat-each=30 --retries=0
How many runs are enough depends on the failure rate. If the test failed one run in ten, ten clean runs prove nothing: the chance of passing all of them at a true rate of 10% is about 35%. So thirty or more are used, and for rare failures also a run in CI, where they happened.
Rules that hold the process together.
A quarantine limit, for example two weeks. After that the test is fixed or deleted: a test nobody fixes is needed by nobody.
Flaky rate as a team metric on a dashboard, next to pipeline time.
A new test is run several times before merge (--repeat-each) so that instability does not enter the gate.
--only-changed and --last-failed speed up checking a fix but do not replace a repeated run.
Limits and alternatives. A tag-based quarantine works only while somebody watches it: the limit and the owner are organisational things a tool cannot enforce. Some teams automatically move a test to quarantine after N unstable results and open a ticket; it is convenient but needs result history in storage (Allure TestOps, a custom database, CI reports). Another approach is to have no quarantine at all and block merges until the flaky test is fixed. It works in small teams with quick fixes and breaks in a large suite where one unstable test stops everyone.
Common mistakes.
Quarantine without an owner and a deadline: after half a year it holds a hundred tests nobody opens.
Returning a test to the gate after one green run: the instability simply had no time to show.
Not storing result history: "flaky" becomes a feeling, not a number.
Deleting an unstable test without analysis: if it caught a real race condition, the risk is left uncovered.
Check yourself
A test that failed in 10% of runs passed ten times in a row after the fix. Can it go back to the gate?
Answer
Not yet. If the true failure rate is 10%, the chance of ten clean runs is about 35%, so the result proves almost nothing. You need thirty or more runs with --repeat-each and no retries, ideally also a run in CI.
Why is a @quarantine tag with a separate job better than test.fixme()?
Answer
fixme disables the test entirely, so the instability is no longer observed and the test is forgotten. A tag takes the test off the blocking path but it still runs in a separate job: you see how it behaves and can collect traces for analysis.
Related lessons: "Where flaky tests come from", "Retries: when they help and when they hurt", "Test system metrics".
In the interview.Junior: An unstable test is moved from the blocking run to quarantine, a ticket is opened and it is fixed, not just rerun. Middle/Senior: I build a process: detection from result history and a nightly --repeat-each, quarantine by tag with an owner and a deadline, analysis from traces and logs with a cause class, return after a repeated stable run. The key is that every unstable test has an owner and a deadline, and the flaky rate is visible as a metric.
Retries: when they help and when they hurt
A retry restarts a failed test from the beginning in a new worker, and if it then passes, its status is flaky. It is a fallback for random failures, not a fix. It helps with infrastructure failures and collecting traces, but hurts when it hides a real bug, such as a race condition in a debit. Waiting for a condition, like expect.poll, is synchronisation that a retry does not replace.
System design · Retries
A retry turned the pipeline green. What did it hide: an unstable test or a money bug?
The config has retries: 2, the pipeline is green, and the transfer test is marked as flaky. The team got used to it: "passed on the second attempt, so it is fine". In reality one run in ten debits the money twice, and the retry neatly repaints red as green. A retry is a useful tool when you know what it does and what it does not. The lesson covers where it helps, where it hurts and how it differs from waiting for a condition.
How it works and why. If a test fails and retries is above zero, Playwright discards the worker the test failed in, starts a new process with a clean browser state and runs the test from the beginning. There are three final statuses: passed (on the first attempt), flaky (failed, then passed) and failed (failed on all attempts). A fresh worker is needed so that the bad state of the previous attempt does not leak into the next. This is both the strength and the weakness: a test that depends on random state or time may pass on a retry simply because the conditions changed.
What a retry does in Playwright
Figure 1. A green run does not mean there was no problem: the flaky status is the signal.
When a retry helps.
As temporary protection against infrastructure failures in CI: an overloaded agent, a network failure while loading dependencies.
For collecting diagnostics: trace: 'on-first-retry' records a trace of the first retry, so normal runs do not spend time on traces and one appears for a failed test. If you need the trace of the failure itself, use 'retain-on-failure' or 'retain-on-first-failure'.
As a source of instability data: the flaky status goes into history and metrics.
When a retry hurts.
When it hides a product bug. A race condition in debiting may show in one run out of ten. A retry makes the pipeline green and the bug goes to production.
When retries are large (3-5): run time grows while stability does not improve.
When the test repeats a non-idempotent action not only in the browser but also through the API: a repeated POST of a transfer may create a second transfer in the same database if the test does not clean up.
Example: a retry versus a wait. The transfer is processed asynchronously and the test checks its status. The wrong approach is to rely on a retry of the whole test, because the first attempt often checks the status before processing.
// before: relies on retries: 2 to hide the race with the queueconst res = await api.getTransfer(id);
expect(res.status).toBe('COMPLETED');
The right approach is waiting for a condition inside the test. expect.poll repeats the function at intervals until the value matches or the timeout runs out:
The difference is fundamental. A wait is a normal part of the test: the system is asynchronous by design and the test waits for the final state. A retry is a restart of the whole test from scratch: a fallback for random failures. The first is correct synchronisation, the second is insurance. If a test without a wait passes only on a retry, it must be fixed, not left on a retry.
Configuration. Globally a small retry only in CI, and for a group where instability is known and the cause is already in a ticket it can be changed separately:
// playwright.config.tsexportdefaultdefineConfig({
retries: process.env.CI ? 1 : 0,
use: { trace: 'on-first-retry' },
});
// one group only
test.describe('payments sandbox', () => {
test.describe.configure({ retries: 2 });
});
Locally retries are kept at zero: the developer should see a failure at once. Inside a test the attempt number is available as testInfo.retry, but branching test behaviour on it is not advisable: a test that behaves differently on a retry no longer checks the same thing.
Limits and alternatives. A test-level retry does not cure the cause, it only lowers the chance of red. For external dependencies (a payment sandbox) a mock or stub is more reliable than a repeat. For a blocking gate on money many teams forbid relying on a retry: the --fail-on-flaky-tests flag makes a run red if a test passed only on a retry. Cypress has a similar mechanism, test retries (retries in the config, separately for runMode and openMode); in the Selenium world retries come from the test runner or a plugin, and the risks are the same.
Common mistakes.
Relying on a retry instead of a wait: the test passes "the second time" and stays wrong.
Ignoring the flaky status in the report: a green run creates a feeling that all is well.
Setting retries to 3-5 "for reliability": the pipeline gets slow and instability grows unnoticed.
A retry on a test that creates records without cleanup: a repeat leaves duplicates.
Check yourself
The transfer test passes only on the second attempt in 1 of 10 runs, retries: 2. The pipeline is green. What next?
Answer
The flaky status is a signal, not a success. We check in the trace whether it is synchronisation in the test or a wrong result in the product (for example a double debit). If the test simply does not wait for asynchronous processing, we add expect.poll. If the result is wrong, we file a defect. We do not remove the retry until the cause is understood, and we do not consider the problem closed either.
How does trace: 'on-first-retry' differ from 'retain-on-failure' and when to use which?
Answer
on-first-retry records a trace only on the first retry: runs without failures pay nothing for recording, and the retry trace shows behaviour after the failure. retain-on-failure records a trace of every attempt and keeps the ones that failed: it is the failure itself, but recording always runs. For normal CI the first is used, and for investigating a specific unstable test the second.
Related lessons: "Where flaky tests come from", "The process of fighting flakiness: detect, isolate, fix", "Idempotency, retries and rate limiting".
In the interview.Junior: A retry reruns a failed test and if it passes the status is flaky. It helps with infrastructure failures but does not replace fixing the cause. Middle/Senior: I set one or two retries in CI and always track tests that pass only on a retry, because in fintech a retry can hide a race condition in debiting. Waiting for a condition (expect.poll, web-first assertions) is synchronisation inside the test, and a retry is a fallback at the level of the whole test; the two must not be confused.