Playwright locks stop at the shard. One server per shard.

Published: · 9 min read

A Playwright test lock only sees its own run. See two shards break one shared server, then two fixes that passed in a demo on 1.65.1.

Playwright test locks stop at the shard. Give each shard its own server. Two shards call one server: shard 1's restart test passes, while shard 2's three note tests each fail with Received: 503.

Playwright test locks stop at the shard. Give each shard its own server.

Two readers on DEV added a good point to the -exclusive- lock article. Playwright 1.63 added test locks. Version 1.65 added the built-in -exclusive- lock. It makes one test run alone, such as a server restart. But a lock only sees its own Playwright run. What happens when a suite is split into shards?

Their advice was to give each shard its own server and port. One reader also suggested keeping each shard's test data under its own name prefix.

The results below come from real runs on Playwright 1.65.1. You'll see the failure, two fixes, and one small trap in the config.

Shards are separate runs

Sharding splits one test suite into parts, called shards. You pick a part with a flag like --shard=1/2. CI is the system that runs your tests on each push. There, each shard is usually its own job.

The test-locks docs say locks work across files, worker processes and projects. Shards aren't on that list. Each shard is a separate run, and it only knows its own tests.

Two shards, one server: three tests fail

The demo reuses the notes server from the last article. Its data lives in memory, so a restart wipes it. For 1.5 seconds after a restart, it answers 503. That status means "busy, try again later."

One thing changed. The server now takes its port as an argument. A port is the number a server listens on.

// A tiny notes server. Data lives in memory, so a restart wipes it.
// Usage: node server.mjs [port]
import http from 'node:http';

const port = Number(process.argv[2] ?? 3123);
let notes = new Map();
let restartingUntil = 0;

http.createServer((req, res) => {
  const url = new URL(req.url, 'http://localhost');
  if (Date.now() < restartingUntil) {
    res.writeHead(503).end('restarting');
    return;
  }
  if (req.method === 'POST' && url.pathname === '/restart') {
    notes = new Map();
    restartingUntil = Date.now() + 1500;
    res.writeHead(202).end('restarting');
    return;
  }
  const id = url.pathname.slice('/notes/'.length);
  if (req.method === 'PUT' && url.pathname.startsWith('/notes/')) {
    notes.set(id, 'saved');
    res.writeHead(201).end('saved');
    return;
  }
  if (req.method === 'GET' && url.pathname.startsWith('/notes/')) {
    res.writeHead(notes.has(id) ? 200 : 404).end(notes.get(id) ?? 'missing');
    return;
  }
  res.writeHead(url.pathname === '/health' ? 200 : 404).end();
}).listen(port);

Save it as server.mjs. The tests are the same seven as last time. Six tests save a note, wait one second, then read it back. The seventh restarts the server and waits until it answers again.

The restart test now has a tag, @restart. A tag is a label you can filter on.

import { test, expect } from '@playwright/test';

function noteTest(name) {
  test(`save note ${name}`, async ({ request }) => {
    expect((await request.put(`/notes/${name}`)).status()).toBe(201);
    await new Promise((resolve) => setTimeout(resolve, 1000));
    expect((await request.get(`/notes/${name}`)).status()).toBe(200);
  });
}

test('restart the server', { tag: '@restart', lock: '-exclusive-' }, async ({ request }) => {
  expect((await request.post('/restart')).status()).toBe(202);
  await expect.poll(async () => (await request.get('/health')).status(), {
    timeout: 5000,
  }).toBe(200);
});

noteTest('a');
noteTest('b');
noteTest('c');
noteTest('d');
noteTest('e');
noteTest('f');

Save it as tests/notes.spec.mjs. This time the restart comes first in the file. That makes the overlap happen on every run, as you'll see below.

The first config sends every shard to one server that is already running. Think of a shared test server in CI, often called staging.

import { defineConfig } from '@playwright/test';

// All shards call one server that is already running.
export default defineConfig({
  testDir: './tests',
  fullyParallel: true,
  workers: 3,
  retries: 0,
  use: { baseURL: process.env.BASE_URL ?? 'http://localhost:3123' },
});

Save it as playwright.shared.config.mjs. fullyParallel: true lets Playwright split single tests between shards, not just whole files. Start the server in one terminal:

node server.mjs

Then run both shards at once from a second terminal:

npx playwright test --config playwright.shared.config.mjs --shard=1/2 &
npx playwright test --config playwright.shared.config.mjs --shard=2/2 &
wait

The & starts each command in the background, so both shards run together. These commands are for macOS and Linux.

Three runs ended the same way. Shard 1 ran 4 tests, and all passed. Shard 2 ran notes d, e and f, and all 3 failed. Every failure received 503, sometimes on the save and sometimes on the read-back.

Here is the first run. Times are seconds from the first test's start, across both shards.

Shard Test Start End Result
2 save note f 0.00 1.05 Failed
2 save note d 0.00 1.06 Failed
1 restart the server 0.01 1.92 Passed
2 save note e 0.01 1.06 Failed
1 save note a 1.94 2.95 Passed
1 save note b 2.18 3.21 Passed
1 save note c 2.18 3.21 Passed

Inside shard 1, the lock worked. The restart ran alone, and notes a, b and c waited for it. Shard 2 never saw that lock. Its three tests ran during the restart and got 503.

A pass can be luck

In another version of the test file, the restart came fourth instead of first. Shard 1 then ran notes a, b and c before the restart. Shard 2 passed in all three runs.

But its last test ended only 0.03 to 0.07 seconds before the restart began. Nothing kept the two shards apart. Shard 2 just happened to finish first.

When do shards share a server?

GitHub-hosted runners give every job a fresh, separate runner. GitHub's workflow docs say "each job runs in a fresh instance of a runner image". Say your config starts the app with webServer. That option starts a server before the tests run. Then each CI shard already gets its own copy.

Shards share a server in two common cases:

  • The shards run on one machine. Your laptop is one example. One big CI machine is another.
  • The shards call a shared server or database. One example is a staging server that every job uses.

The first case has a simple fix. The second needs a different plan.

Fix 1: each shard starts its own server

Give each shard its own port, and let each shard start its own server. Read the shard number from one place. Here it comes from an environment variable, a named value set before a command. I called it SHARD.

import { defineConfig } from '@playwright/test';

// One source for the shard: SHARD=1/2, SHARD=2/2, or nothing.
const [current, total] = (process.env.SHARD ?? '').split('/').map(Number);
const port = 3123 + (current || 0);

export default defineConfig({
  testDir: './tests',
  fullyParallel: true,
  workers: 3,
  retries: 0,
  shard: current ? { current, total } : null,
  use: { baseURL: `http://localhost:${port}` },
  webServer: {
    command: `node server.mjs ${port}`,
    url: `http://localhost:${port}/health`,
    reuseExistingServer: false,
  },
});

Save it as playwright.config.mjs. SHARD=1/2 now sets two things. The config's shard option picks the tests. Port 3124 goes to the server and to baseURL, the address the tests call. Without SHARD, the whole suite runs on port 3123, so stop the first server before you try that.

Run both shards at once:

SHARD=1/2 npx playwright test &
SHARD=2/2 npx playwright test &
wait

All three runs passed: 4 tests in shard 1 and 3 in shard 2. In the demo's JSON reports, the two server commands were node server.mjs 3124 and node server.mjs 3125.

The restart still overlapped notes d, e and f in time. But it restarted a different server, so nothing failed.

Keep the shard number in one place

Why not pass --shard on the command line, like the sharding guide does? You can, but then the port won't follow it.

One run set SHARD=1/2 and also passed --shard=2/2. The command-line flag won, so Playwright ran shard 2's tests. The server still used port 3124, the port for shard 1. With one value in one place, the two can't disagree.

Two servers on one port

On one machine, two servers need two ports. In one more test, both shards started a server on port 3123. In all three runs, one shard stopped before running any test:

[WebServer] Error: listen EADDRINUSE: address already in use :::3123
Error: Process from config.webServer was not able to start. Exit code: 1

EADDRINUSE means the port is already taken. The other shard passed. Which shard lost changed from run to run.

In GitHub Actions

Here is how I'd pass SHARD from a GitHub Actions matrix. A matrix runs one job per value, here one job per shard. The shape follows the Playwright sharding guide.

This file passed actionlint, a checker for workflow files. It was not run in CI.

name: Playwright tests
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        shard: [1, 2]
    steps:
      - uses: actions/checkout@v6
      - uses: actions/setup-node@v6
        with:
          node-version: 24
      - run: npm ci
      - run: npx playwright test
        env:
          SHARD: ${{ matrix.shard }}/2

If your tests open a browser, add npx playwright install --with-deps after npm ci. The demo skips it, because it only uses the request fixture, a built-in HTTP client.

Fix 2: when there is only one server

Sometimes you can't copy the server. It might be a shared staging server, or a database every job uses.

Then keep the restart out of the shards. Run it once, alone, after they finish. The @restart tag makes that easy:

npx playwright test --config playwright.shared.config.mjs --shard=1/2 --grep-invert @restart &
npx playwright test --config playwright.shared.config.mjs --shard=2/2 --grep-invert @restart &
wait
npx playwright test --config playwright.shared.config.mjs --grep @restart

--grep-invert @restart skips the tagged test. --grep @restart runs only that test. All three runs passed: 3 notes in each shard, then the restart alone. The restart never overlapped another test.

In GitHub Actions, the restart becomes its own job. needs: shards makes it wait for both shards. This file also passed actionlint and was not run in CI.

name: Playwright tests
on: [push, pull_request]

jobs:
  shards:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        shard: [1, 2]
    steps:
      - uses: actions/checkout@v6
      - uses: actions/setup-node@v6
        with:
          node-version: 24
      - run: npm ci
      - run: >-
          npx playwright test --config playwright.shared.config.mjs
          --shard=${{ matrix.shard }}/2 --grep-invert @restart
        env:
          BASE_URL: https://staging.example.com

  restart:
    needs: shards
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - uses: actions/setup-node@v6
        with:
          node-version: 24
      - run: npm ci
      - run: npx playwright test --config playwright.shared.config.mjs --grep @restart
        env:
          BASE_URL: https://staging.example.com

Two limits apply. If a shard fails, GitHub skips the restart job by default. The needs docs explain this. Also, this only orders jobs inside one workflow run. Another workflow or team can still call the same staging server.

Shared data: name it by shard, too

The first reader also suggested a data namespace per shard. A namespace is a prefix that keeps one shard's data apart. That matters when shards share a database.

Watch for one trap. Playwright runs tests in several workers at once. A worker is one test process. A common way to name test data uses its number, parallelIndex. In the demo, both shards had workers 0, 1 and 2. So a name like user-0 would repeat in both shards.

Add the shard number. Inside a test, testInfo.config.shard holds it:

function dataName(testInfo) {
  const shard = testInfo.config.shard?.current ?? 0;
  return `s${shard}-w${testInfo.parallelIndex}`;
}

In a small test file, six tests printed this name in two shards. In three runs, the names went from s1-w0 to s2-w2, with no repeats. That held with --shard on the command line and with SHARD in the config.

The name belongs to a worker, not a test. Tests that run one after another in a worker share it. Two workers running at once get different names, even in different shards.

Two workflows might use the same database at once. Then I'd add the CI run ID too. GitHub sets it as GITHUB_RUN_ID. A re-run keeps that ID, so I'd add GITHUB_RUN_ATTEMPT as well. The reader also suggested cleaning up only your own namespace at the end. Then a failed job can't delete another shard's data. I agree, but this demo has no database, so neither idea was run here.

A namespace doesn't help with a restart, though. Notes d, e and f already had their own names. They still failed, because the restart took down the whole server.

Which one I'd pick

  • You can start the app inside each shard: I'd give each shard its own server and data, from one SHARD value.
  • There is one shared server: I'd tag the tests that restart or reset it. Then I'd run them alone after the shards.
  • Inside each shard: I'd keep the -exclusive- lock. It still keeps the restart away from that shard's own tests.

Try it

The demo ran on macOS with Node.js 24 and Playwright 1.65.1. Make a folder with the four files from this article:

server.mjs
playwright.config.mjs
playwright.shared.config.mjs
tests/notes.spec.mjs

Then install Playwright:

npm init -y
npm install --save-exact @playwright/test@1.65.1

Run the commands from each section. You should see these results:

  • Two shards on one server: 4 passed in one shard, 3 failed in the other.
  • Fix 1: 4 passed and 3 passed.
  • Fix 2: 3 passed, 3 passed, then 1 passed.

Exact seconds will differ on your machine. The demo's waits are set by hand, so the overlap happens every time. It shows what a shared restart does to another shard. It doesn't measure how often that happens in a real suite.

Thanks to the two readers on DEV who spotted this. Their per-shard server advice held up in every run here.

Anton Gulin is the AI QA Architect, the first person to claim this title on LinkedIn. He builds AI-powered test automation systems where AI agents and human engineers collaborate on quality. Former Apple SDET (Apple.com / Apple Card pre-release testing). Find him at anton.qa or on LinkedIn.

playwright · testing · ci

Subscribe

Get notified when I publish something new, and unsubscribe at any time.

Related articles

Read all my blog posts