How to keep shared‑resource tests safe while still exploiting Playwright’s parallelism


1. Why “parallel” is not always “safe”

Playwright’s default test runner executes files in parallel workers and, inside each file, runs tests concurrently when fullyParallel is enabled. This gives dramatic speed‑ups on CI, but it also assumes that every test is isolated – i.e., it does not depend on a mutable external state that another test might touch at the same time.

Typical non‑isolated scenarios include:

Shared resourceTypical conflict
A single test account on an external SaaS serviceSimultaneous password changes, data wipes
A rate‑limited sandbox environmentExceeding request quotas
Global configuration files written by testsOverwrites that corrupt later runs
Test data that lives in a shared databaseConcurrent inserts/updates causing flaky reads

When such resources are accessed without coordination, tests become flaky, and CI pipelines lose their reliability. Historically the workaround was to mark the whole suite (or an entire file) as serial, which guarantees that no two tests run at the same time. The downside is that the whole suite loses parallelism, inflating execution time.

Playwright 1.63 introduces named test locks to address this gap. Locks let you declare a named resource that must be exclusive, while all other tests continue to run in parallel. The feature works across files, worker processes, and projects – exactly the boundaries where concurrency previously caused trouble.

> Official behavior – Playwright acquires all the locks of a test before the test starts and releases them when it finishes. In default and serial modes, a lock declared on any test is held for the duration of the whole file; with fully parallel execution, the lock is scoped to the individual test. (Playwright test locks documentation)

The rest of this article explains how to use locks correctly, how they interact with workers and projects, and how to design a pragmatic QA strategy that avoids deadlocks while preserving most of the parallel speed‑up.


2. Three baseline approaches

ApproachParallelismIsolation guaranteeTypical use‑case
Isolated tests (no shared state)Full parallel across workers, files, and projectsEach test runs independently; no coordination neededPure unit‑style UI tests
Fully serial suite (test.describe.configure({ mode: 'serial' }))No parallelism inside the file; files still run in parallel workersGuarantees that any two tests in the file never overlapLegacy suites that rely on a global browser or shared DB
Narrowly scoped locks (new in 1.63)Parallelism is retained for all tests that do not share a lock nameOnly tests that declare the same lock name are serialized; others run concurrentlyTests that need a single test account, a rate‑limited sandbox, or a global config file

The lock approach is the sweet spot for most teams: you keep the fast default parallelism and only serialize the minimal set of tests that truly conflict.


3. Declaring locks – syntax and scope

3.1 At the test level

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

test('create user in shared sandbox', { lock: 'sandbox-A' }, async ({ page }) => {
  // The lock name "sandbox‑A" is acquired before the test starts.
  // No other test that also asks for "sandbox‑A" will run concurrently.
  await page.goto('https://example.com/signup');
  // …
});

The lock name is declared in the test options object:

test('update shared account', { lock: 'shared-account' }, async ({ page }) => {
  // The test starts only when the named lock is available.
  // …
});

When fullyParallel is off (the default), the lock is held for the whole file because the test runner treats the file as a single unit. When fullyParallel is on, the lock is held only for the duration of the individual test.

3.2 At the test.describe level

If a whole group of tests needs the same exclusive resource, you can declare the lock once:

test.describe('Operations on shared sandbox A', () => {
  test.describe.configure({ lock: 'sandbox‑A' });

  test('reset sandbox', async ({ page }) => {
    // lock already acquired
    // …
  });

  test('run migration script', async ({ page }) => {
    // same lock, same exclusivity guarantee
    // …
  });
});

All tests inside the describe inherit the lock name, simplifying maintenance.

3.3 Multiple locks

A test can request more than one lock by passing an array:

test('reset the database', { lock: ['sandbox-A', 'shared-account'] }, async () => {
  // …
});

Playwright acquires all requested locks before the test starts and releases them when it finishes. The documentation does not define lock-acquisition order or fairness, so tests and QA policy must not depend on either.


4. Naming conventions – keeping the lock space manageable

Because lock names are global across the whole test run, a disciplined naming scheme prevents accidental collisions:

RecommendationExample
Prefix with the resource typeaccount‑admin, sandbox‑us‑east
Use kebab‑case (Playwright treats names as strings)sandbox‑a
Keep names short but descriptiverate‑limit‑api
Document the lock map in a shared README(see migration plan)

A clear map makes it easy for new contributors to understand which tests must not run together.


5. Interaction with workers, projects, and CI sharding

5.1 Workers

Playwright runs tests in configurable worker processes. Locks are enforced across workers: if Worker 1 holds lock sandbox‑A, Worker 2 waits before starting another test that requests sandbox‑A. This is the core guarantee that enables safe parallelism.

5.2 Projects

Projects are separate configurations (e.g., Chrome vs. Firefox). Locks are also global across projects. A test in the chromium project that locks shared‑account will block the same‑named test in the firefox project until the lock is released. This prevents two browsers from simultaneously mutating the same external account.

5.3 CI sharding

CI systems often split the test suite into shards that run on different agents. Playwright’s lock implementation is process‑local; it does not coordinate across separate CI machines. Therefore, a lock only guarantees exclusivity within a single CI job. If a shared resource truly cannot be accessed concurrently across agents, you must either:

The article does not claim distributed locking across CI machines because the official documentation does not guarantee it.


6. Practical concerns

6.1 Timeouts

Playwright does not expose a lock‑specific timeout. If a test cannot acquire its lock because another test is stuck, the waiting test will simply stay in the queue until the lock is released. In practice this can cause the overall suite to exceed the CI timeout. Mitigation strategies:

6.2 Failure recovery

Playwright releases a test’s locks when the test finishes, and Playwright shuts down a worker after a test failure. External state can nevertheless remain corrupted (for example, a partially updated account), so subsequent tests may still fail. Recommended practice:

6.3 Observability

The official documentation defines lock behavior but does not expose lock-acquisition telemetry. Treat timing evidence as team-owned instrumentation:

This evidence helps reveal unexpected contention without claiming undocumented runner internals.

6.4 Preventing deadlocks

Playwright waits until all requested locks are available before running a test. The following team policy is therefore about limiting contention and keeping lock usage reviewable:

These rules keep the lock registry small and easy to reason about.


7. Architecture & data‑flow view

Test files → named lock options → runner coordination → worker process → test result

This diagram is a conceptual view of the documented contract: Playwright coordinates named locks across worker processes and projects before a test is allowed to start.


8. Test design checklist

CategoryWhat to verify
PositiveA test that declares lock sandbox‑A runs successfully when no other test holds that lock.
NegativeTwo tests that both request sandbox‑A never overlap; the second test starts only after the first finishes.
ConcurrencyTests with different lock names (sandbox‑A vs sandbox‑B) run in parallel, even when executed on the same worker pool.
Timeout handlingA deliberately slow test uses an explicit test timeout; cleanup and external-state recovery are verified separately.
CI shardingWhen the suite is split into two shards, each shard uses a distinct lock name (or external isolation) to avoid cross‑agent conflicts.

Automated verification can be added to a “lock sanity” test suite that runs in a dedicated CI job.


9. Migration plan – from fully serial to lock‑based parallelism

  1. Identify shared resources – List external accounts, sandboxes, config files, databases that are mutated by tests.
  2. Add lock names – Add { lock: 'resource-name' } as the test options argument for each test that touches a shared resource.
  3. Run a baseline – Execute the suite with fullyParallel: true and confirm that the lock‑sanity tests (section 8) pass.
  4. Gradually expand – If a new test needs the same resource, add the same lock name.
  5. Measure – Compare total suite duration before and after lock adoption. Unrelated tests should still run in parallel; the reduction in wall‑clock time is the primary KPI.
  6. Human‑owned release gate – Before merging a PR that introduces a new lock, require a reviewer to verify that the lock name is documented and that no existing test already uses it unintentionally. This gate prevents accidental lock proliferation.

The migration can be performed incrementally; you do not need to switch the whole suite to serial mode.


10. Measurable evidence that unrelated tests stay parallel

Use explicit test start and finish timestamps from CI logs or a custom reporter to verify concurrency. After migration, evidence should show:

From those timestamps, calculate an observed concurrency factor:

concurrency factor = (sum of individual test durations) / (suite wall-clock duration)

A ratio close to the number of workers indicates that locks are not throttling the suite.


11. Where automation helps

AreaAutomation opportunity
Lock map validationA lint rule that scans test files for lock: usage and flags duplicate or missing documentation.
Deadlock detectionA script that builds a lock‑dependency graph from the test suite and warns if any node has degree > 2 (per policy).
Performance regressionCI job that records suite duration and fails if the parallelism ratio drops below a threshold.
Resource health checksPre‑test hook that verifies the external sandbox is reachable; if not, the suite aborts early.
Release gate enforcementPull‑request check that ensures any new lock name is added to the shared lock‑registry file.

These automated guards keep the lock strategy maintainable as the test base grows.


12. Recommended QA strategy (our take)

  1. Prefer isolation – Write tests that do not need any lock whenever possible.
  2. Introduce locks only for truly shared resources – Use the naming conventions and policy rules above.
  3. Keep critical sections tiny – Move all non‑essential work outside the locked region (e.g., page navigation can happen before acquiring the lock if it does not affect the shared state).
  4. Monitor lock contention – Review the recorded timing evidence or a custom lock log to ensure contention remains low.
  5. Document and review – Treat lock names as a shared contract; any change must go through the human‑owned release gate.

By following this approach you retain most of Playwright’s parallel speed while eliminating the flakiness caused by concurrent access to external resources.


13. Review questions

  1. What is the difference between a lock’s behavior in the default mode versus fullyParallel mode?
  2. How does Playwright enforce lock exclusivity across workers and projects?
  3. List two practical policies that reduce the risk of deadlocks when using multiple locks.
  4. Why must a team treat lock names as a shared contract and enforce a release‑gate review?
  5. Which part of the test suite should you still keep fully serial, if any, after adopting test locks?

14. Conclusion

Playwright 1.63’s named test locks give QA teams a precise tool to serialize only the tests that truly need exclusive access to an external resource. By understanding the scope of locks, naming them consistently, and applying a lightweight policy to avoid deadlocks, you can keep the majority of your suite running in parallel while eliminating flaky failures caused by shared‑state contention. Combine the built‑in lock mechanism with automated linting, performance monitoring, and a human‑owned release gate, and you’ll have a robust, scalable testing pipeline that respects both speed and reliability.


Sources