What usually breaks when a pytest suite is parallelized with `pytest-xdist`, and how do you design the suite to remain reliable?
Answer
`pytest-xdist` runs tests in separate worker processes, so hidden shared state becomes visible quickly: reused accounts, fixed filenames or ports, shared database rows, order dependencies and session fixtures that assumed one process can all break. Make tests independently seed and clean their data, give workers unique resources when required, avoid relying on execution order, and choose a distribution mode that respects expensive or shared fixtures. Parallelism should expose coupling, not be fixed with sleeps or broad retries.
Strong answer includes
- recognizes that xdist workers are separate processes with independent pytest execution
- identifies shared data, fixed resources and order dependence as common parallel failures
- uses isolated test data or worker-specific resources and understands distribution modes
Practical example
After switching to
pytest -n 8, account tests fail randomly because all workers update the same user. The fix is to provision a unique user per worker or per test and clean it deterministically; changing the command to `-n 2` merely makes the race rarer and does not solve it.