QA Interview Hub · Knowledge base · Quizzes · Українська

System Design › Stability and flaky tests

Where flaky tests come from

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

Testwaits, order, locatorsDatashared account, leftoversEnvironmentstaging, sandbox, networkProducta race condition: a real bug
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:

  1. 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.
  2. Shared data. Parallel workers change one account: one withdraws, another finds no money.
  3. Order. The test only works after another test has created the record it needs.
  4. Asynchronous backend. The transfer goes through a queue, and the test checks the balance at once.
  5. 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.
  6. 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:

test('transfer updates the balance', async ({ page }) => {
  await page.getByRole('button', { name: 'Send' }).click();
  const text = await page.getByTestId('balance').textContent();
  expect(text).toBe('70.00');
});

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:

await page.getByRole('button', { name: 'Send' }).click();
await expect(page.getByTestId('balance')).toHaveText('70.00');

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:

export const test = base.extend<{ account: Account }>({
  account: async ({ request }, use, testInfo) => {
    const acc = await createAccount(request, 'acc-' + testInfo.testId);
    await use(acc);
    await deleteAccount(request, acc.id);
  },
});

(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 2. 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.

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.

More articles in this chapter