Skip to content
Latchkey

How to Avoid Flaky Failures From Shared State Under Parallelism

Tests that pass serially but fail in parallel almost always share mutable state: a fixed port, a temp file path, or a global singleton.

Parallelism exposes hidden coupling. Give each worker its own ports, temp directories, and fixtures so no two tests contend over the same resource.

Common culprits

  • A hardcoded port that two workers bind at once.
  • A shared temp file or fixed output path multiple tests write.
  • A global singleton or module-level cache mutated by several tests.

Fixes

  • Allocate an ephemeral port (bind to :0) per worker instead of a fixed one.
  • Use a per-worker temp directory keyed on the worker id.
  • Reset or namespace global state in setup and teardown.

Terminal

Terminal
# quickly confirm a parallelism-induced flake by forcing serial execution
pytest -p no:xdist -q     # passes serially?
pytest -n auto -q         # fails in parallel? then it is shared state

Gotchas

  • Re-running until green hides the race instead of fixing the shared resource.
  • Managed runners that auto-heal transient infra flakes do not fix a real shared-state race in your tests.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →