QA AND TEST AUTOMATION · PART 3 · AUTOMATION FUNDAMENTALS · RELIABILITY · 35 OF 112

Flaky Tests: Causes, Quarantine and How to Fix Them

What a flaky test is and why it is so costly, the usual causes (fixed waits, shared data, test order, time and randomness, unstable environments and external services, leaked state), how to prove and diagnose a flake by repeating runs and reading traces, and how to fix it, quarantine it and track flake rates. Worked on ShopRung's slow-search bug and a shared-stock collision.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 13

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Timing
  • shared data and order
  • environment
  • time and random
  • prove, diagnose, fix
  • quarantine with an owner

Notes

Why it hurts

Why do flaky tests hurt so much? Because people learn to ignore red. Developers re run the pipeline until it goes green, and soon they re run real failures too, so real bugs ship. Hours go into investigating failures that were not bugs. Retries slow every pipeline down. A suite nobody trusts can be worse than no suite at all, because it gives false confidence and still costs money to run.

The real cost
  • devs re-run until green → real failures get re-run too → bugs ship
  • time lost investigating "failures" that are not pipelines slow down with retries
  • a suite nobody trusts is worse than no suite

Cause 1: timing

The most common cause is timing. A test searches for mug, sleeps for two seconds, then checks for two results. Usually the search is fast and it passes. Switch on ShopRung's slow search bug, or run on a busy CI machine, and the search takes two and a half seconds: the test checks too early and fails. The fix is never a longer sleep. Wait for the condition itself, the result count showing two, with a timeout. Part five shows how.

ShopRung slow-search
page.fill("#q", "mug");
page.click("text=Search");
Thread.sleep(2000);   // guess
assert count == 2;

bug "slow-search": ~2.5 s
→ count not updated yet: FAIL
fast machine, quiet CI: PASS

fix: wait FOR the condition,
not for a time

Cause 2: data and order

The second cause is shared state. Test A buys all three diaries; test B expects three in stock. B passes alone and fails after A, so its result depends on the order the runner happens to choose. Shared state hides in many places: static variables, shared browser sessions, leftover cookies, caches and files written to disk. The fixes come from the test data episode: own your data, reset, and use unique values.

Shared state
  • test A buys all 3 diaries
  • test B expects stock 3 → passes alone, fails after A
  • also: static variables, shared browser sessions, leftover cookies, caches, files written to disk
  • fix: own data, reset, unique

Cause 3: environment

The third cause is the environment. A third party API times out. Someone redeploys the shared staging environment in the middle of your run. The CI machine is overloaded, so everything is slower. Rate limits kick in. The CI machine has a different time zone or language setting, so dates print differently. Fixes include stubbing third parties, giving each run its own environment, and setting sensible timeouts with clear error messages.

Environment causes
  • a third-party API times out shared staging redeployed mid-run
  • CI machine overloaded: everything is slower
  • DNS, certificates, rate limits
  • different time zone or locale on the CI machine
  • fix: stub third parties, own environments, timeouts

Cause 4: time and random

The fourth cause is time and randomness. A test about a coupon expiring today fails when it runs just after midnight in universal time. Month ends, leap years and daylight saving changes break date logic. Random data without a seed produces a different case every run. Assuming hash set order, as you saw in the collections episode. And parallel threads touching one object. Inject the clock, seed random generators, and compare collections by content.

Hidden non-determinism
  • "expires today" tests that fail after midnight UTC
  • month-end, leap years, DST
  • random data without a seed
  • HashSet order assumed
  • parallel threads touching one object
  • fix: inject clock, seed
  • random, compare sets as sets

Prove it

First prove the flake. Run the test many times in a row: Playwright has repeat each, and pytest has a plugin that adds a count option. Forty nine passes out of fifty is a flaky test, not a passing one. Run the suite in a random order to expose order dependence: recent Playwright versions have a shuffle option, and pytest has random order plugins. Then isolate: does it fail alone, or only after a certain other test?

Reproducing a flake
# repeat 50 times
npx playwright test search
  --repeat-each=50
pytest -q --count=50
  (pytest-repeat)

# random order to expose
# order dependence
npx playwright test --shuffle

pass 49 of 50 = flaky

Diagnose

Then diagnose with evidence, not guesses. Keep a trace, video or screenshot from the moment of failure. Look at the network log for slow or failed calls, and at timestamps for what was slow. Note which tests ran just before. Check the CI machine's load and time. Comparing a passing run and a failing run side by side usually shows the difference within minutes. Part five shows Playwright's trace viewer, which records exactly this.

Evidence from failures
  • trace / video / screenshot at the moment of failure
  • network log: slow or failed calls?
  • timestamps: what was slow?
  • which tests ran just before CI machine load and time
  • compare a passing and a failing run side by side

Fix or quarantine

Fix the cause: wait for conditions, own the data, stub third parties, inject the clock. If you cannot fix it today, quarantine it: move it out of the suite that blocks merges, but keep running it so you collect evidence, file a ticket, name an owner, and set a date. Never delete it silently, and never hide it behind endless retries. A quarantined test that nobody owns is just a deleted test that still costs money.

What to do
  • fix the cause: wait for conditions, own data, stub third parties
  • cannot fix today? quarantine: move it out of the blocking suite, keep running it, file a ticket, name an owner, set a date
  • never: delete silently or retry forever

Retries

Retries are useful as a signal, not as a cure. Many teams allow two retries in CI and none locally. Playwright then marks a test that failed and then passed as flaky in its report, separate from passed and failed. Track the flake rate per test, and treat every flaky mark as a bug to fix. With zero retries on your own machine, you see flakes while you are still writing the test, which is the cheapest time to fix them.

Retries, used well
// playwright.config.ts
retries: process.env.CI ? 2 : 0

report shows: "flaky"
  = failed, then passed

track flake rate per test
treat every "flaky" as a bug
zero retries locally, so you
see flakes while developing

Common mistakes

Responses that make things worse. Adding longer sleeps, which makes the suite slower and still flaky. Re running until green. Setting retries to five and forgetting. Quietly deleting the test. Saying it is just the environment without evidence. Quarantine without an owner or a date. And blaming the tool instead of the test design. Most flakes come from how the test was written, which is good news: you can fix them.

Avoid these
  • adding longer sleeps
  • re-running until green
  • retries: 5 and forget
  • deleting the test quietly
  • "it is just the environment" with no evidence
  • quarantine with no owner
  • blaming the tool, not the test design

Say it like this

In the interview: first I prove it is flaky, by repeating the test and running the suite in random order. Then I find the cause from traces and logs, usually timing, shared data, the environment or time. I fix the cause: wait for conditions instead of sleeping, isolate data, stub third parties, inject the clock. If I cannot fix it today, I quarantine it with a ticket and an owner, and we track flake rates so they go down.

In the interview
  • "First prove it: repeat runs
  • and random order. Then find
  • the cause from traces and logs: usually timing, shared
  • data, environment or time.
  • Fix it: wait for conditions, isolate data, stub third
  • parties. If not today, quarantine with an owner, and track flake rate."

Interview questions

Q1What is a flaky test?

A test that passes and fails on the same code without any change, due to non-determinism in the test, data or environment.

Q2What are the most common causes of flaky tests?

Timing issues (fixed sleeps, races, missing waits), shared or leftover data and test-order dependence, unstable environments and third-party services, and uncontrolled time or randomness.

Q3How do you prove a test is flaky?

Run it many times (repeat-each, pytest-repeat) and in random order (shuffle, random-order plugins), comparing passing and failing runs.

Q4Should you add retries to fix flaky tests?

No, not as a fix. Retries can keep a pipeline moving and flag tests as flaky, but each flaky result should be tracked and fixed at the cause.

Q5What is test quarantine?

Moving a known flaky test out of the blocking suite while it keeps running for evidence, with a ticket, an owner and a deadline to fix or remove it.

Q6Why is Thread.sleep a bad fix?

A fixed wait is either too short on slow runs (still flaky) or too long on fast runs (slow suite); waiting for the actual condition is both faster and reliable.

Q7How do you find order-dependent tests?

Run the suite in random order, run the failing test alone, and bisect which earlier test leaves state behind.

Q8What metrics help manage flakiness?

Flake rate per test and per suite, number of quarantined tests and their age, and time lost to re-runs.