Test data management in Playwright is where a suite quietly stops being reliable. The selectors can be sharp and the fixtures tidy, and the build still fails. Two tests in different workers created the same user, and one of them got a conflict that had nothing to do with the feature under test. Nothing in the trace points at the data, so the fix lands on the assertion.
Setup and reuse are covered in a separate post. If you’re still working out where a factory belongs, which scope it takes, or why teardown runs in one order and not another, Playwright fixtures explained covers that ground. Everything below assumes a factory can already reach a test. It stays on the payload: how a record gets built, how it stays distinct from every other test’s record, and how it gets removed.
The same record in two workers
A spec file like this fails in more than one configuration, and each one looks like a different bug.
import { test, expect } from '@playwright/test';
test('owner sees the billing tab', async ({ request }) => {
const res = await request.post('/users', { data: { email: 'shared@example.test' } });
expect(res.status()).toBe(201);
});
test('owner cannot delete the last admin', async ({ request }) => {
const res = await request.post('/users', { data: { email: 'shared@example.test' } });
expect(res.status()).toBe(201);
});Both tests create a user with one email address. With fullyParallel on, Playwright can run the two tests in different workers at the same moment. An API that enforces unique emails accepts the first and answers the second with 409. Turn fullyParallel off and they run one after another in the same worker. The second still gets 409, because the first test never deleted its user. Two configurations, one root cause: a name written into the source file is a name every test in the file shares. Parallelism only decides whether you lose to a race or to a leftover row.

Why a leaked record fails every run after it
The second configuration is the one that spreads. Because no test deleted its user, shared@example.test outlived the run, and running the same file again failed both tests. That included the one that had passed, which now walked into the row its own previous run left behind. A collision fails a test once. A leaked record fails every run after it, on every branch, until someone works out that the data rather than the code is dirty.
Nothing here was a bug in the feature. The suite rests on an assumption: a record named in the source belongs to the test that names it. Nothing in the file makes that true. Worker count only changes which mechanism breaks it first: a request arriving at the same moment, or a row left behind by the last run. A module-level counter inherits the flaw in a subtler form. Each worker is a separate process, the counter restarts at one in every one of them, and two workers hand out user-1@example.test at the same instant. Identical code then gets a 201 in worker 0 and a 409 in worker 1.
Playwright test data factories built on the attempt, not the file
A factory returns a valid record on every call, with anything unusual overridden there. The default carries the weight: an email no other attempt will produce.
import { test, expect } from '@playwright/test';
import type { APIRequestContext, TestInfo } from '@playwright/test';
type NewUser = { email: string; name: string };
// One attempt's key: stable within a retry, different on the next one.
const attemptKey = (testInfo: TestInfo) =>
`t-${testInfo.testId}-r${testInfo.retry}-e${testInfo.repeatEachIndex}`;
async function createUser(request: APIRequestContext, testInfo: TestInfo, overrides: Partial<NewUser> = {}) {
const email = `${attemptKey(testInfo)}-${crypto.randomUUID().slice(0, 8)}@example.test`;
const res = await request.post('/users', { data: { email, name: 'Test User', ...overrides } });
expect(res.status(), `create ${email}`).toBe(201);
return res.json() as Promise<NewUser & { id: string }>;
}
test('signs in as a returning user', async ({ request }, testInfo) => {
const user = await createUser(request, testInfo, { name: 'Ada' });
expect(user.name).toBe('Ada');
});The key is built from three values Playwright passes to every test. testId identifies the test itself, retry counts attempts on that test, and repeatEachIndex separates repeated runs under --repeat-each. Including all three means a retried test starts from an empty namespace rather than inheriting whatever its failed attempt left half-finished.

One detail here is easy to get backwards. testId doesn’t change between attempts of the same test. Only retry moves, from 0 on the first run to 1 on the first retry. A key made from testId alone therefore hands the retry the exact email the first attempt already registered. The retry then fails on a duplicate instead of re-testing the bug. Add retry to the key and the second attempt creates cleanly, which turns a hard failure into a flaky pass. A flaky pass is information you can act on. The crypto.randomUUID() suffix is a backstop for the case where one test calls the factory twice.
Two rules keep factories from becoming the problem. Return what the API returned, not the payload you sent, because the server assigns the id and may normalize fields. Asserting against your own request object only tests your own literal. And assert on the create response, so a 400 from a broken payload fails at the line that built the data instead of three steps later.
Builders: valid by default, explicit at the call site
A factory that takes an object of optional fields gets unreadable once the record has more than a handful of them. A builder keeps the valid defaults in one place and makes each deviation a named call. The unusual part of a test is then visible in the test.
import { test, expect } from '@playwright/test';
type NewUser = { email: string; name: string; role: 'viewer' | 'editor' | 'admin'; verified: boolean };
class UserBuilder {
private data: NewUser = {
email: `user-${crypto.randomUUID()}@example.test`,
name: 'Test User',
role: 'viewer',
verified: false,
};
withName(name: string) { this.data.name = name; return this; }
withRole(role: NewUser['role']) { this.data.role = role; return this; }
verified() { this.data.verified = true; return this; }
build(): NewUser { return { ...this.data }; }
}
test('an admin override is visible at the call site', async ({ request }) => {
const payload = new UserBuilder().withName('Grace').withRole('admin').verified().build();
const res = await request.post('/users', { data: payload });
const body = await res.json();
expect(body.role).toBe('admin');
expect(body.verified).toBe(true);
});The defaults being valid is what makes this pay off. A test that only needs the record to exist passes nothing and reads as such. A test that needs an admin says withRole('admin') at the line where the admin matters. Reviewers stop diffing a fixture file against the test to work out which fields matter.
Builders need to hand back a copy. build() returns a copy, so calling withRole() after build() can’t change a payload you already sent.
Why test data management starts with database isolation
Unique emails stop two tests colliding on one row. They don’t stop one test reading rows another test left behind. That class of failure is much harder to see, because the test that reads the stale row usually passes.
Truncating the tables and reloading seed data between tests is the obvious answer and the one I’d push back on hardest. It makes the database a resource every test must hold. Under parallel workers it’s worse than a lock. Worker A truncates while worker B is mid-assertion, and B fails on data it created a moment earlier. The suite gets slower and less reliable in the same move.
Scoping the data works better. Every record a test creates carries a marker that ties it to that attempt. The marker can be the key above, a run id from the environment, or a tenant the API already isolates on. Every query in the test then filters by that marker. A test never sees another test’s rows because it never asks for them, and no test has to wait for another. The Playwright docs cover the worker-level version of this in isolating test data between parallel workers.

The shared login account is test data too
The login account is the record teams forget is data. A suite that signs every test in as one seeded qa@example.test has created a shared row that no test owns. It breaks in a specific way. A test that changes the account’s display name, role or notification settings changes what the next test sees, in whatever order the workers happen to finish. Either the account is read-only and no test mutates it, or each worker gets its own account built the same way as any other record. Signing in faster isn’t worth a test whose result depends on which worker got there first.
Two things make scoping work in practice. The app has to support the marker with a real tenant or namespace field, not a naming convention the tests maintain by hand. A convention is only as good as the next person’s memory. And the seed rows every test depends on, such as reference lists, plan catalogs and country tables, have to be read-only. Seed data any test is allowed to edit is shared mutable state with a friendlier name.
Not every check needs data at all. If the question is whether a response has the right shape, the payload can be a literal and no record has to exist. Contract testing versus E2E testing covers how to decide which checks deserve a seeded database and which are cheaper without one.
Seeding Playwright test data through the API, or around it
Seeding through the API is the default I’d pick. It goes through the same validation a user would and produces records the whole application agrees are valid. It also needs no database credentials in the test config. Playwright ships an HTTP client as a fixture, so the seeding code stays inside the runner. Playwright vs Selenium covers what each runner ships with.
API seeding has one trap that shows up as flakiness rather than an obvious error. A create that returns 201 doesn’t promise the record is readable yet. Replication lag, a write queue or a cached read path can each delay it. Reading it straight away is a race that passes on a fast machine.
import { test, expect } from '@playwright/test';
test('waits for the new user to become readable', async ({ request }) => {
const created = await request.post('/users', { data: { email: `lag-${crypto.randomUUID()}@example.test` } });
const { id } = await created.json();
await request.get(`/users/${id}`); // on a lagging backend this can still be 404
await expect.poll(async () => {
const res = await request.get(`/users/${id}`);
return res.status();
}, { timeout: 5000, intervals: [50, 100, 250] }).toBe(200);
});Against a backend with read lag, the immediate read can come back 404 while the polled read reaches 200. expect.poll re-runs the callback until the assertion holds or the timeout expires. The test waits exactly as long as the backend needs and no longer. Setting the intervals keeps a slow backend from costing a second per attempt while still backing off once the fast attempts have failed.
API seeding vs direct inserts
| Strategy | What it gives you | What it costs |
|---|---|---|
request fixture | Same validation as a real client; no DB credentials in tests | Slower; needs the API to be reachable |
| Direct database insert | Fast; can build states the API forbids | Bypasses validation; couples tests to schema |
| Snapshot and restore | Exact known state per test | Needs privileges; blocks parallel writes |
Direct inserts earn their place for states the API won’t produce, such as a locked account or a subscription mid-dunning. There the coupling to schema is a fair trade. As the default they’re a liability. A row written straight into a table can exist in a combination the application never creates, and the test then asserts against fiction. A restored snapshot has the same problem in another shape, needing restore privileges in CI and refusing to coexist with workers writing at once.
Test data cleanup that survives a failing test
Cleanup written at the end of a test body only runs if the test reaches the end. The failures worth cleaning up after are exactly the ones that throw first.
import { test as base, expect } from '@playwright/test';
import type { TestInfo } from '@playwright/test';
type Tracker = { createTrackedUser: (name?: string) => Promise<{ id: string; email: string }> };
export const test = base.extend<{ tracker: Tracker }>({
tracker: async ({ request }, use, testInfo: TestInfo) => {
const created: string[] = [];
const createTrackedUser = async (name = 'Test User') => {
const email = `t-${testInfo.testId}-r${testInfo.retry}-e${testInfo.repeatEachIndex}-${created.length}@example.test`;
const res = await request.post('/users', { data: { email, name } });
expect(res.status(), `create ${email}`).toBe(201);
const user = await res.json();
created.push(user.id);
return user;
};
await use({ createTrackedUser });
// runs even when the test body throws
for (const id of created) {
const res = await request.delete(`/users/${id}`);
if (res.status() !== 204 && res.status() !== 404) {
console.warn(`cleanup failed for ${id}: ${res.status()}`);
}
}
},
});
test('creates two users and fails on purpose', async ({ tracker }) => {
await tracker.createTrackedUser('Ada');
await tracker.createTrackedUser('Grace');
expect('this assertion').toBe('deliberately wrong');
});A fixture teardown is the right home for this because Playwright runs it whether the test body passed or threw. Even when the test body throws, the teardown still deletes both records. The status check is defensive. Not every API answers a repeat delete with success, and cleanup that throws on an already-deleted row buries the real failure under a cleanup error.

Cleanup has an edge a fixture can’t cover. A worker killed mid-test, by a canceled CI job or a job timeout, never reaches teardown at all. That’s why a cleanup strategy needs a second layer outside the run, rather than trusting every teardown to have executed. That layer is a sweep that deletes records carrying an old run marker, or a disposable database per pipeline run. The in-test cleanup keeps the common case tidy; the sweep handles the runs that died.
Two habits make cleanup trustworthy. Delete by id collected at creation time, not by re-running the query that found the records, because the query may match more than the test created. And decide deliberately what happens when a delete fails. A warning that names the id keeps a leaked record visible in the log. A thrown error turns a data problem into a confusing test failure. Neither hides the leak, but one of them tells you where to look.
Test data management mistakes to catch in review
- A literal email, id or slug in a spec file. If two tests can name the same record, some worker count will eventually make them collide.
- A counter or an incrementing generator at module scope. Each worker restarts it, so the values repeat across processes.
- A key built from
testIdwithoutretry. The retry inherits the failed attempt’s namespace and fails on a duplicate. - Seed data any test may edit. Reference rows are for reading; a test that writes to them is editing everyone else’s fixture.
- Cleanup only at the end of the test body. The interesting failures never reach it.
- Assertions that compare against the payload the test sent, rather than the record the API returned.
Keep reading
Fixtures decide where the setup lives and how it gets torn down, and Playwright fixtures explained is the post for that half of the problem. Sometimes test data keeps leaking between runs and the suite goes run-dependent. For that case, how to handle flaky tests in Playwright is the triage process for finding which input moved.
