How-To Guide

How to Parallelize and Shard a Test Suite

Speed up CI by sharding tests across workers with stable distribution, isolated databases and deterministic ordering, without hiding failures.

On this page

  1. Introduction
  2. Sharding Versus Parallelism
  3. Distributing Tests Evenly
  4. Isolating Shared Resources
  5. Deterministic Order and Randomization
  6. Keeping Failure Reporting Clear
  7. Measuring the Improvement
  8. Common Pitfalls and Conclusion

Introduction

A test suite that takes thirty minutes serial is a suite engineers stop running locally and that slows every merge. Parallelism cuts wall-clock time by running tests across workers, but naive parallelism introduces its own failures: workers fighting over a shared database, tests that pass alone but fail together, and an uneven shard split that leaves one worker doing all the work. Effective sharding distributes tests evenly, isolates each worker’s resources, and keeps the suite deterministic, so the speed comes without new flakiness.

Sharding Versus Parallelism

Parallelism within one machine runs several test files in separate processes, using the cores available. Sharding splits the suite across separate machines or CI jobs, each running a subset. The two compose: several shards, each internally parallel across cores. Sharding is what scales beyond one machine and what makes a large suite finish in minutes.

The distribution problem is the same at both levels: if the work is uneven, some workers idle while one grinds. Splitting by file count assumes every file costs the same, which is false; a file with one slow integration test costs more than a file with twenty fast unit tests. Distribute by measured duration, not by count.

# sharding shapes
1 machine, N processes   -> run files in parallel on N cores
M machines, N processes  -> split suite into M shards, each parallel within
# distribute by duration, not file count:
# a 1-test slow file and a 20-test fast file are not equal units of work

Distributing Tests Evenly

Use historical durations to build shards of roughly equal total time. Assign the slowest tests first to whichever shard currently has the least total duration, a greedy bin-packing that keeps the maximum shard time low. Recompute the split periodically, since durations change as tests are added.

Testing frameworks and CI providers offer timing-based splits: Vitest, Jest, Playwright and pytest all support sharding by index or by duration file. Feed them a duration cache from previous runs, refreshed regularly, and the shards stay balanced without manual bookkeeping.

# Playwright: split across 4 shards using recorded timing.
npx playwright test --shard=1/4
npx playwright test --shard=2/4
# in CI, run the four shards as separate jobs in parallel:
#   matrix: shard: [1, 2, 3, 4]
#   command: npx playwright test --shard=${{ matrix.shard }}/4

# Vitest: similar sharding
npx vitest run --shard=1/4

Isolating Shared Resources

Parallel tests that share a database corrupt each other: one test’s writes appear in another’s reads, transactions conflict, and unique constraints fire unexpectedly. Give each worker its own database or schema, created before the worker starts and destroyed after. This is the single most important isolation for parallel test suites.

The same applies to files, ports, temp directories and any shared cache. Bind each worker to its own port range, its own temp directory, and its own cache namespace. A test that assumes a fixed port or a shared file path passes serially and fails under parallel execution, and the fix is to make the resource per-worker rather than global.

// Each worker gets its own schema, derived from the worker id.
import { test as base } from '@playwright/test';
import { Client } from 'pg';

export const test = base.extend<{ db: Client }>({
  db: async ({}, use, workerInfo) => {
    const schema = `test_w${workerInfo.workerIndex}`;
    const client = new Client({ connectionString: process.env.DATABASE_URL });
    await client.connect();
    await client.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);
    await client.query(`SET search_path TO ${schema}`);
    await client.query('BEGIN');                 // roll back per test
    await use(client);
    await client.query('ROLLBACK');
    await client.query(`DROP SCHEMA ${schema} CASCADE`);
    await client.end();
  },
});

Deterministic Order and Randomization

Parallel execution makes order non-deterministic by construction, so tests must not depend on order. Detect order dependence by running the suite in a randomized order (test-order randomization) on a schedule; a test that fails only in some orders is order-dependent and must be fixed, not merely re-run.

Randomization is also a defence against accidental coupling: if tests share state through a module-level variable or a database row, running them in a different order exposes it. Keep the random seed in the failure output so a failing order can be reproduced locally, and treat any order-dependent failure as a real bug in the test’s isolation.

# Randomize order to expose hidden coupling; seed is printed on failure.
npx vitest run --sequence.shuffle --sequence.seed=1700000000
npx jest --randomize --seed=1700000000
# a test that fails only under some orders is order-dependent: fix it

Keeping Failure Reporting Clear

Sharding splits the report, so a failure in shard three must be as easy to find as one in shard one. Collect results from all shards into one report, annotate each with its shard, and fail the overall pipeline if any shard fails. Do not let a “best effort” shard silently pass.

Retry only at the whole-suite level if at all, and track retries as a flakiness signal. A shard that only passes on the second attempt is hiding a flake. Reporting the first-attempt result and the retry result separately keeps the signal honest, so the speed of sharding does not cost you the accuracy of the result.

# CI sharding with honest reporting
[ ] run shards in parallel jobs (matrix)
[ ] upload each shard's results (junit/json)
[ ] merge into a single report, tagged by shard
[ ] fail the pipeline if ANY shard fails on the first attempt
[ ] record retry counts as a flakiness signal (don't hide them)

Measuring the Improvement

Track wall-clock time per shard and the total, and watch for the slowest shard. Total time is set by the slowest shard, so an uneven split wastes the other workers. Rebalance when the slowest shard is significantly slower than the average, which usually means the distribution is stale.

Also watch the queue time and setup overhead: if each worker spends two minutes provisioning a database, that overhead can dominate a five-minute suite. Cache dependencies, reuse containers, and provision schemas efficiently so the parallel gain is real and not eaten by per-worker setup.

# metrics to watch
wall-clock per shard        total time = max(shard times)
max/avg shard ratio         > ~1.3 => rebalance the split
per-worker setup time       high setup can eat the parallel gain
retry rate                  rising retries => hidden flakes from isolation
# rebalance using fresh duration data; stale splits drift uneven

Common Pitfalls and Conclusion

Do not split by file count instead of duration. Do not share a database across workers. Do not depend on execution order. Do not hide failures behind a shard that retries silently. And do not parallelize before isolating resources, or you will trade slow for flaky.

Sharding turns a long suite into a short one by running tests across workers with even, duration-based distribution and per-worker resource isolation. Distribute by measured time, give each worker its own database and ports, keep order irrelevant, report failures from every shard clearly, and measure the slowest shard. Done well, the suite gets faster without becoming less trustworthy.

Sources: Playwright: Sharding, Vitest: Sharding and parallelism, Google Testing Blog: Test sizes and speed.

FAQ

Should I split tests by file count?
No. Files are unequal units of work: a one-test slow integration file costs more than a twenty-test fast unit file. Split by recorded duration so the slowest shard is not much slower than the average, and refresh the durations periodically.
Why do my tests pass serially but fail in parallel?
Almost always shared state: a common database, a fixed port, a shared temp file or a module-level variable. Give each worker its own database schema, ports and directories, and run the suite in a randomized order to expose the remaining coupling.

Related Examples