AUTOMATION FRAMEWORKS

Parallelizing a Python Test Suite Without Flaky Failures

Turning on parallel execution is one of the most useful changes you can make to a slow Python test suite. Faster feedback means people run the suite more often, and that habit is worth protecting. But I've seen teams install pytest-xdist, add -n auto, enjoy one fast run, and then spend the following weeks chasing failures that only happen in parallel. The moment you can't trust a red build, the speed is worth nothing.

The cause is nearly always the same: tests that look independent but quietly share something. A file on disk, a database row, a module-level variable, a fixed username, a port. Run serially, the execution order hides the problem. Run on four workers, two tests collide and one fails at random.

There's a newer twist. When GitHub Copilot or a coding agent writes a good share of your tests, it copies whatever patterns it sees in the repository, including the ones that leak state. So in this article I'll cover the three collision patterns I see most, the pytest tools that fix them, and how I tell an agent the isolation rules so it stops reintroducing them.

Build an API Automation Framework With Node.js

Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.

Learn more

Why parallel runs expose problems serial runs hide

pytest-xdist starts several worker processes and hands tests out between them. Each worker is a separate Python process, so module-level variables are not shared between workers. What is shared is everything outside the process: the file system, the test database, the API under test and any external service. Those are where collisions happen.

The three failure patterns I see most often:

  • Fixed resource names. Two tests both create a user called test_user. Serially, the second test reuses or recreates it. In parallel, one gets a 409 Conflict or deletes the other's user mid-test.
  • Shared files. Tests write to ./output/report.json or a fixed download path. Two workers overwrite each other's file and an assertion reads the wrong content.
  • Order dependence. Test B only passes because test A ran first and left data behind. xdist distributes tests across workers, so B can run first, or on a different worker, and fail.

Before turning on parallelism, I run the suite serially in random order with the pytest-randomly plugin. If tests fail when shuffled, they will fail in parallel too, and a single-process run is far easier to debug.

Give every test its own data

The most effective fix is to stop using fixed names. Generate unique identifiers per test so collisions are impossible rather than unlikely:

import uuid

import pytest
import requests


@pytest.fixture
def unique_user(api_base_url, auth_headers):
    email = f"qa-{uuid.uuid4().hex[:12]}@example.test"
    response = requests.post(
        f"{api_base_url}/users",
        json={"email": email, "name": "Parallel Test"},
        headers=auth_headers,
        timeout=10,
    )
    assert response.status_code == 201, response.text
    user = response.json()
    yield user
    requests.delete(f"{api_base_url}/users/{user['id']}", headers=auth_headers, timeout=10)

A predictable prefix like qa- also lets you sweep up anything a crashed run left behind. For files, use pytest's built-in tmp_path fixture, which gives every test its own directory. Never write to a fixed path in the repository.

Know what each worker shares

A session-scoped fixture runs once per worker, not once per run. With four workers, your "run once" setup runs four times. For cheap setup like building a session object, that's fine. For expensive or non-repeatable setup, such as seeding a database or creating a shared tenant, it causes exactly the collisions you were trying to avoid.

xdist provides a worker_id fixture ("gw0", "gw1" and so on, or "master" when not running in parallel). I use it to namespace anything a worker owns:

import pytest


@pytest.fixture(scope="session")
def tenant_name(worker_id):
    # One tenant per worker: tests on the same worker share it, workers never do.
    return f"qa-tenant-{worker_id}"

When setup genuinely must happen once per run, the xdist documentation describes using tmp_path_factory with a file lock so the first worker does the work and the others read the result. I treat that as a last resort, because it reintroduces a shared resource on purpose.

Group the tests that can't be separated

Some tests really do need to run together, for example a set that exercises a single global configuration endpoint. Rather than forcing the whole suite to run serially, group them. The --dist loadgroup mode sends every test with the same xdist_group name to the same worker:

import pytest


@pytest.mark.xdist_group(name="global_settings")
def test_enable_feature_flag(settings_client):
    ...


@pytest.mark.xdist_group(name="global_settings")
def test_disable_feature_flag(settings_client):
    ...

Run with pytest -n auto --dist loadgroup. If you find yourself grouping a large part of the suite, that's a sign the tests share too much, not that you need more groups. I go into the data side of this in how much test data isolation is actually enough.

Agents copy your isolation habits, good or bad

This is where AI-assisted test writing changes the picture. An agent asked to "add tests for the orders endpoint" looks at your existing tests and matches them. If three existing tests use a hard-coded test_user, the next ten generated tests will too. Each one passes locally and in a serial run, which is all the agent usually checks, and the parallel failures show up later in CI where they're expensive to trace.

Two things help. First, write the rules down where the assistant reads them. Copilot picks up repository-wide guidance from .github/copilot-instructions.md, and most coding agents have an equivalent instructions file:

## Parallel-safe tests
- Tests run with pytest -n auto. Every test must pass in any order, on any worker.
- Never use fixed names for created resources. Use the unique_user / unique_order
  fixtures or a uuid-based name with the qa- prefix.
- Write files only under tmp_path.
- Do not add session-scoped fixtures that create server-side data without review.
- Never fix a parallel-only failure by adding a retry or a sleep.

Second, make the check the agent runs match the check CI runs. If the agent verifies its work with plain pytest, it never sees a collision. Tell it to verify with the same parallel command, ideally twice with shuffled order. A failure that appears only under -n is then caught while the change is still small.

The same thinking applies when your suite includes tests that call a model or an agent. Running them on many workers multiplies the request rate, and you can hit provider rate limits that look like random failures. I put those tests behind a marker and run them in a separate job with fewer workers, so a 429 from the provider is never confused with a real regression.

Triage a parallel-only failure properly

When something fails only in parallel, resist the urge to rerun until it passes. The steps I follow:

  1. Note the worker and the tests that ran on it just before the failure. The -v output shows worker ids.
  2. Rerun the failing test alone. If it passes, the problem is interaction, not the test itself.
  3. Reproduce with the same order. pytest-randomly prints its seed at the start of a run, and --randomly-seed replays it. Then bisect the tests that ran alongside the failure.
  4. Look for the shared thing: a name, a file, a tenant, a global setting. Fix the isolation, not the symptom.

An AI assistant is genuinely useful at step four if you give it the two tests and the failure output and ask "what state could these share?" It's not useful if you ask it to "make the test pass", because the quickest path to green is a retry or a skip. If the failure only reproduces in CI, my notes on debugging a flaky API test that only fails in CI cover the environment differences to check.

Roll it out gradually

I don't flip the whole suite to parallel in one go. Start with -n 2, fix what breaks, then increase. Keep a serial job available for a while so you can compare. Once the suite is stable at full parallelism, treat isolation as a review rule for every new test, whether a person or an agent wrote it.

Parallel execution is worth the effort, but only when the tests were designed to be independent. If you want to build an API suite with that discipline from the start, using Python or Node with VS Code and GitHub Copilot, my API testing courses walk through it step by step.