Why tests become flaky

A flaky test passes when it wants and fails without a code change. It is not "going to fix itself": every flaky test erodes trust in the whole run.

Where instability comes from

  • Time. A fixed sleep is not connected to data readiness.
  • Order. Tests share state and depend on who ran first.
  • Network. A live API or a database that is sometimes slower.
  • Races. Two threads write to the same place without synchronisation.

How to treat it

  1. Replace sleep with waiting for a condition.
  2. Isolate data: each test prepares its own environment.
  3. Mock external services: the test should verify your logic, not the internet.
  4. Make the race reproducible: a barrier at the start and a controlled switch point instead of "run it a hundred times and hope".

What to do in production

Find the cause first, then fix it. A timeout failure is not a reason to increase the timeout forever; it is a signal that the condition is not being checked.