A suite that takes 40 minutes on one CPU core can take 10 on four. pytest-xdist runs your Playwright Python tests in several worker processes at once, each with its own browser. Speed is the easy part; the real skill is keeping tests correct when they run at the same time. In this lesson you will measure the speed-up on a real suite, choose how tests are distributed, keep related tests on one worker, understand what happens to session fixtures, run one-time setup safely with a file lock, generate parallel-safe test data, and avoid the most common parallel pitfalls.
📖 What You’ll Learn: how pytest-xdist works (controller and workers), installing it, -n 4, -n auto and -n logical, measuring the speed-up, –dist load, loadscope, loadfile, loadgroup and worksteal, xdist_group and a current version caveat, session fixtures running once per worker, worker_id and testrun_uid, one-time setup shared by all workers with filelock, unique test data per worker, parallel pitfalls (shared accounts, files, order), combining -n with browsers and reruns, and turning it off with -p no:xdist.
⚙️ How pytest-xdist Works
With pytest -n 4, pytest starts a controller and 4 worker processes. Every worker collects the same tests, and the controller hands out tests to whichever worker is free. Each worker is a separate Python process with:
- its own Playwright instance and browser,
- its own copy of every session-scoped fixture,
- its own output, which the controller merges into one report.
Tests are therefore isolated by process. The risks come from things outside the process: the application’s data, files on disk and user accounts.
⌨️ Terminal
pip install pytest-xdist
📏 Measure the Speed-Up
A suite of twelve independent UI tests on the SQA Shop:
📄 pytest.ini
[pytest]
addopts = --base-url https://sqatools.in
markers =
xdist_group: keep tests on the same worker
📄 tests/test_catalog.py
import pytest
from playwright.sync_api import Page, expect
SHOP = "/dummy-ecommerce-website/"
TERMS = ["earbuds", "jeans", "course", "shirt", "watch", "laptop", "camera", "ebook", "hoodie", "speaker", "charger", "dress"]
@pytest.mark.parametrize("term", TERMS)
def test_search_returns_results(page: Page, term):
page.goto(SHOP + "#/search/" + term)
expect(page.get_by_test_id("product-card").first).to_be_visible()
⌨️ Terminal
pytest -q
🖥️ Output
............ [100%]
12 passed in 22.96s
⌨️ Terminal
pytest -q -n 4
🖥️ Output
bringing up nodes...
bringing up nodes...
............ [100%]
12 passed in 8.26s
⌨️ Terminal
pytest -q -n auto
🖥️ Output
bringing up nodes...
bringing up nodes...
............ [100%]
12 passed in 6.48s
Four workers cut the time noticeably, and -n auto (one worker per CPU core, 12 on this machine) cut it further, because these tests are independent and wait mostly on the network. That is not guaranteed: each worker pays a fixed start-up cost (a process and a browser), and on a 2-core CI agent or with CPU-heavy pages, too many workers make things slower. Measure on your own machines, and use --maxprocesses to cap auto.
| Option | Workers |
|---|---|
-n 4 |
Exactly 4 |
-n auto |
One per CPU core (physical cores if psutil is installed) |
-n logical |
One per logical CPU (hyper-threads included; needs psutil) |
-n auto --maxprocesses 6 |
auto, but at most 6 |
💡 Tip: Browser tests are limited more by CPU and memory than by Python. On CI agents with 2 to 4 cores, -n 2 to -n 4 is usually the sweet spot.
🔀 How Tests Are Distributed
--dist chooses how the controller hands out tests:
| Mode | Behaviour | Use when |
|---|---|---|
load (default with -n) |
Any free worker takes the next test | Independent tests (the normal case) |
loadscope |
All tests of a module (or class) go to one worker | Module/class fixtures are expensive |
loadfile |
All tests of a file go to one worker | Files share setup |
loadgroup |
Tests with the same xdist_group mark go to one worker |
Specific tests across files must not run in parallel (see the warning below) |
worksteal |
Like load, but idle workers steal queued tests | Test durations vary a lot |
Two tests that use the same shared account must not run at the same time. The most robust way to keep them together is to put them in one file and use --dist loadfile:
📄 tests/test_shared_cart.py
from playwright.sync_api import Page
def test_add_item(page: Page, worker_id):
print(f"[{worker_id}] add item with the shared account")
def test_remove_item(page: Page, worker_id):
print(f"[{worker_id}] remove item with the shared account")
📄 tests/test_other.py
from playwright.sync_api import Page
def test_independent_a(page: Page, worker_id):
print(f"[{worker_id}] independent a")
def test_independent_b(page: Page, worker_id):
print(f"[{worker_id}] independent b")
⌨️ Terminal
pytest tests/test_shared_cart.py tests/test_other.py -n 2 --dist loadfile -v
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
created: 2/2 workers
2 workers [4 items]
scheduling tests via LoadFileScheduling
tests/test_other.py::test_independent_a[chromium]
tests/test_shared_cart.py::test_add_item[chromium]
[gw0] [ 25%] PASSED tests/test_shared_cart.py::test_add_item[chromium]
tests/test_shared_cart.py::test_remove_item[chromium]
[gw1] [ 50%] PASSED tests/test_other.py::test_independent_a[chromium]
tests/test_other.py::test_independent_b[chromium]
[gw0] [ 75%] PASSED tests/test_shared_cart.py::test_remove_item[chromium]
[gw1] [100%] PASSED tests/test_other.py::test_independent_b[chromium]
============================== 4 passed in 1.78s ==============================
Each file went to a single worker, so the two shared-account tests ran one after the other on the same worker, while the other file ran in parallel on another worker.
pytest-xdist also offers @pytest.mark.xdist_group("name") with --dist loadgroup, which groups tests across files. Check it on your versions before relying on it:
⚠️ Watch out: With pytest 9.2 and pytest-xdist 3.8.0 (the latest releases when this lesson was written) xdist_group has no effect: xdist tags grouped tests by rewriting their node id, and pytest 9 no longer reads the attribute it rewrites, so grouped tests are spread over workers like any others. While this lasts, use --dist loadfile (or loadscope for classes) to keep tests together, and watch the pytest-xdist changelog for a fix.
You can verify grouping yourself: with a working loadgroup, the test ids in -v output end in @<group name>.
🔁 Session Fixtures Run Once per Worker
A session-scoped fixture runs once per worker, not once per run:
📄 tests/conftest.py
import os
from pathlib import Path
import pytest
@pytest.fixture(scope="session")
def expensive_setup(worker_id):
# xdist hides workers' print() output, so leave a file as evidence of each setup
Path("setup_log").mkdir(exist_ok=True)
Path("setup_log", f"{worker_id}-pid{os.getpid()}.txt").write_text("expensive setup ran")
return worker_id
📄 tests/test_session.py
import pytest
@pytest.mark.parametrize("n", range(6))
def test_uses_setup(expensive_setup, n):
assert expensive_setup
⌨️ Terminal
pytest tests/test_session.py -n 3 -q
python -c "import os; print(sorted(os.listdir('setup_log')))"
🖥️ Output
bringing up nodes...
bringing up nodes...
...... [100%]
6 passed in 1.34s
['gw0-pid29136.txt', 'gw1-pid27992.txt', 'gw2-pid25144.txt']
Six tests, three workers, three setups: one per worker process. (Note that pytest-xdist does not show print() output from workers, even with -s; that is why the fixture writes files.) That is fine for things like logging in (Lesson 51: one login per worker) but wrong for setup that must happen exactly once, such as creating a shared test account or seeding a database.
🔒 Exactly-Once Setup with a File Lock
The standard recipe from the pytest-xdist documentation: the first worker creates the data and writes it to a file; the others wait on a lock and read the file. tmp_path_factory.getbasetemp().parent is a folder shared by all workers of one run:
📄 tests/test_once.py
import json
import os
from pathlib import Path
import pytest
from filelock import FileLock
def create_shared_data() -> dict:
Path("once_log").mkdir(exist_ok=True)
Path("once_log", f"created-by-pid{os.getpid()}.txt").write_text("created")
return {"coupon": "SAVE10", "created_by": os.getpid()}
@pytest.fixture(scope="session")
def shared_data(tmp_path_factory, worker_id):
if worker_id == "master": # not running under xdist
return create_shared_data()
root = tmp_path_factory.getbasetemp().parent
data_file = root / "shared_data.json"
with FileLock(str(data_file) + ".lock"):
if data_file.is_file():
return json.loads(data_file.read_text())
data = create_shared_data()
data_file.write_text(json.dumps(data))
return data
@pytest.mark.parametrize("n", range(6))
def test_shared(shared_data, n):
assert shared_data["coupon"] == "SAVE10"
⌨️ Terminal
pip install filelock
⌨️ Terminal
pytest tests/test_once.py -n 3 -q
python -c "import os; print(sorted(os.listdir('once_log')))"
🖥️ Output
bringing up nodes...
bringing up nodes...
...... [100%]
6 passed in 1.41s
['created-by-pid4748.txt']
Three workers, but the data was created once; the other workers waited for the lock and read the file. worker_id == "master" covers normal, non-parallel runs.
🧪 Parallel-Safe Test Data
When tests create data on a shared server, two workers must never create or change the same record. Make every value unique per worker and per run:
📄 tests/test_unique.py
import uuid
import pytest
@pytest.fixture
def unique_name(worker_id, testrun_uid):
return f"pw-{testrun_uid[:6]}-{worker_id}-{uuid.uuid4().hex[:6]}"
@pytest.mark.parametrize("n", range(4))
def test_create_object(playwright, unique_name, n):
api = playwright.request.new_context(base_url="https://sqatools.in/wp-json/sqa-api/v1/")
created = api.post("objects", data={"name": unique_name, "data": {"n": n}}).json()
assert created["name"] == unique_name
api.delete(f"objects/{created['id']}")
api.dispose()
⌨️ Terminal
pytest tests/test_unique.py -n 2 -q
🖥️ Output
bringing up nodes...
bringing up nodes...
.... [100%]
4 passed in 3.32s
testrun_uid (same for every worker of one run) and worker_id (gw0, gw1 …) are provided by pytest-xdist; together with a random suffix they make collisions impossible, even when two CI pipelines run at the same moment.
⚠️ Common Parallel Pitfalls
| Pitfall | Symptom | Fix |
|---|---|---|
| One shared user account | Random logouts, wrong cart contents | One account per worker (testuser-{worker_id}) or per test |
| Tests that depend on order | Pass serially, fail with -n |
Make every test set up its own state |
| Writing the same file | Corrupt or missing files | Per-worker paths (tmp_path, worker_id in names) |
| Exactly-once setup in a session fixture | Setup runs N times | File lock recipe above |
base_url only in pytest.ini |
Invalid url on relative goto() |
Use --base-url in addopts (Lesson 49) |
| Global rate limits or small test servers | 429 and timeouts under load | Fewer workers, or mock third parties (Lesson 52) |
🧩 Combining with Other Options
- Several browsers:
pytest -n 4 --browser chromium --browser firefoxspreads all browser×test combinations across the workers. - Retries:
pytest -n 4 --reruns 2works; reruns happen on the same worker. - Reports: pytest-html and Allure merge results from all workers automatically.
- Turning it off:
-n 0runs serially with the plugin loaded;-p no:xdistdisables the plugin entirely (useful when debugging with--pdb, which does not work in workers).
🏋️ Practice Exercises
Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.
Exercise 1: Your CI agent has 4 cores. Write the command that runs the suite in parallel with as many workers as cores but never more than 4, distributing tests so idle workers can steal queued work.
Show answer
pytest -n auto --maxprocesses 4 --dist workstealExercise 2: Two tests both change the shipping address of the shared account testuser. How do you stop them from running at the same time without making the whole suite serial?
Show answer
Put both tests in the same file (for example tests/test_testuser_address.py) and run with pytest -n 4 --dist loadfile: each file runs on one worker, so the two tests run one after the other while other files run in parallel. (@pytest.mark.xdist_group with --dist loadgroup is meant for this too, but check that it works with your pytest and xdist versions, see the warning in the lesson.) Better still, give each test its own account so no grouping is needed.
Exercise 3: Write a fixture worker_account that returns testuser1 on worker gw0, testuser2 on gw1 and so on, and plain testuser without xdist.
Show answer
@pytest.fixture(scope="session")
def worker_account(worker_id):
if worker_id == "master":
return "testuser"
return f"testuser{int(worker_id.removeprefix('gw')) + 1}"Create those accounts in the test environment beforehand.
Exercise 4: Why does pytest -n 4 --pdb not stop at your failing test, and what do you run instead?
Show answer
The debugger needs an interactive terminal, but tests run inside worker processes without one. Rerun the failing test serially: pytest --lf -p no:xdist --pdb (or -n 0).
🧠 MCQ Quiz: Parallel Execution with pytest-xdist
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What does
pytest -n 4start?Answer: A controller and 4 worker processes, each with its own browser. xdist uses separate processes; each worker runs its own Playwright instance. - What does
-n autochoose?Answer: One worker per CPU core.autosizes the pool to the machine; cap it with--maxprocesses. - How often does a session-scoped fixture run with
-n 3?Answer: Three times, once per worker. Every worker is a separate pytest session. - Which
--distmode sends all tests of one file to the same worker?Answer: loadfile.loadfilegroups by test file;loadscopegroups by module or class,loadgroupbyxdist_groupmark. - What is
worker_idwhen tests run without xdist?Answer:master. The fixture returnsmasterin a normal, non-distributed run. - What is the purpose of the FileLock recipe?Answer: To run setup exactly once across all workers and share its result. The first worker creates the data under the lock; the others read the saved file.
- Which folder is shared by all workers of one run?Answer:
tmp_path_factory.getbasetemp().parent. Each worker has its own basetemp; their common parent is shared per run. - Why might
-n autobe slower than-n 4for a small suite?Answer: Each worker has a fixed start-up cost (process, browser), which outweighs the gain for few tests. Parallelism pays off when the work per worker is larger than its start-up cost. - A test passes alone but fails with
-n 4. What is the most likely cause?Answer: Shared state: another test changes the same account, data or file at the same time. Parallel failures almost always come from resources shared outside the process. - How do you disable xdist completely for one run?Answer:
-p no:xdist.-p no:xdiststops the plugin from loading;-n 0keeps it loaded but runs serially.
Want a longer, timed test? Take the Module 12 mock interview (20 MCQs in 20 minutes).
❓ Frequently Asked Questions
🤔 Is Playwright’s own parallelism different in Python?
Yes. Playwright Test (TypeScript) has built-in workers. In Python, parallelism comes from pytest-xdist; the idea (one browser per worker, isolated contexts per test) is the same.
🤔 Can I run tests in parallel inside one process with threads?
Not with the sync API: Playwright’s sync objects must be used from the thread that created them. Use processes (xdist) or the async API with asyncio (Lesson 69) for concurrency inside one process.
🤔 How do I see which worker ran a test?
Use -v: each line shows [gw0], [gw1] … Inside a test, the worker_id fixture gives the same value.
🤔 Do I need more memory for parallel browser tests?
Yes. Each worker runs a browser, roughly 150 to 400 MB each depending on the pages. Watch memory on CI agents when increasing -n.
🤔 How do I split a suite across several CI machines?
xdist parallelises on one machine. For several machines, run a subset per job (for example by folder or marker, or with a sharding plugin such as pytest-split) and merge the reports afterwards.
🏁 Summary
- pytest-xdist runs tests in separate worker processes:
-n 4,-n auto,--maxprocesses; measure before choosing. --distmodes control distribution;--dist loadfilekeeps a file’s tests on one worker (checkxdist_group+loadgroupon your versions first).- Session fixtures run once per worker; use the FileLock recipe for exactly-once setup.
- Make data unique with
worker_id,testrun_uidand random suffixes; avoid shared accounts, order dependencies and shared files. - xdist works with browsers, reruns and reports; disable it with
-p no:xdistfor debugging.
🎬 Watch the Playwright tutorial series on YouTube!
Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page