The base rule: every test creates its own data and does not depend on other tests' data, and only unchanging reference data is shared. Approaches (API, test hook, seed, direct DB write) are chosen by isolation, speed and honesty of state: the API usually gives the best balance, while a direct DB write can create an impossible state. Data must be synthetic, and uniqueness comes from a UUID.
System design · Data and environments
The test is green on its own and red in the full run. Where does its data come from?
A transfer test passes when run alone and fails in the nightly run: the balance is «wrong». The test code did not change; its neighbours did, working with the same data. Test data is the most common cause of unstable and slow tests, and a Senior must explain where to get it and why that way. This lesson lays out the approaches by price and risk.
How it works and why. Data has three properties, and each approach gives up one for another. Isolation: my test does not see other people's changes. Speed: how much time goes on preparation. Honesty of state: the data is created the way the product itself creates it, so the state is possible in reality. A direct DB write is fastest but can create a state the application never would, for example an account with a balance and no entry in the operations journal. Creating through the UI is honest but slow and brittle. The API is in the middle: usually the best balance. So the table has no «best» approach, only a choice for the circumstances.
Approach
Pros
Cons
Static data in the DB
Simple, fast
Conflicts in parallel runs, data gets «spoiled»
Generating through the API in a test
Isolation, realistic state
Slower, depends on the API
A test hook (internal endpoint)
One request instead of KYC and verifications
Must be agreed with development and closed from production
A seed script or a DB snapshot
Fast environment start
Maintained together with the schema, data goes stale
Factories writing straight to the DB
Very fast
Bypasses business logic, an impossible state can be created
The basic rule: each test creates its own data and does not rely on the data of other tests. Only reference data that nobody changes may be shared: currencies, countries, tariffs. Note that «shared» and «unchangeable» go together. A shared write permission is exactly the source of conflicts.
Where a test gets its data
Typical
A shared ready-made user
All tests take test_user_1. While the test runs alone, all is fine. In a parallel run they change one balance.
Better
Own data per test
A fixture creates a user before the test and cleans up after. Neighbours cannot interfere.
Figure 1. The difference is who owns the state the test changes.
Example: from a shared user to an own one. It was: test_user_1 with a balance of 100 lies in the DB and dozens of tests use it. Now: a factory generates a unique user, and a fixture creates it through the API and cleans up after the test:
Uniqueness comes from a random suffix (a UUID), not from the worker index: an index does not tell two consecutive runs apart and does not help on a retry. The example.test domain is reserved for tests and will not deliver mail anywhere.
Fintech. Creating a «ready» user often requires KYC, phone verification and opening an account. A test hook helps: an internal endpoint available only in test environments that creates a verified user in one request. Conditions: agree it with development, close it from production by configuration (not only by a «secret» path) and have a check that in a production-like configuration it is unavailable. The data must be synthetic: no real personal data and no real cards, only test cards described in the provider documentation. If a copy of production is needed, it is anonymised before it reaches the test environment.
Limits and alternatives. Generation through the API adds time to every test, so on large suites per-worker account pools appear (see the next lesson). A DB snapshot or seed brings a database up fast, but must be refreshed with migrations; in PostgreSQL a database can be created from a template (CREATE DATABASE … TEMPLATE), which is handy for a separate copy per worker. Static data is acceptable when a test only reads (say, a smoke check on reference data) or when runs go one at a time. A direct DB write is justified for volume (a million records to check pagination), provided the state has been reconciled with business rules at least once.
Common mistakes.
One «golden» user for all tests: works while there is no parallelism and breaks exactly when it is switched on.
Dependence between tests («test 2 uses what test 1 created»): order and parallelism break both.
A direct DB write without checking invariants: the test verifies a state that never occurs in reality.
Real personal data and real cards in tests: a risk of leaks and of violating regulatory requirements.
Not cleaning up: the database grows and queries get slower and less stable.
Check yourself
Why is it better to make an email unique with a UUID rather than with a worker index?
Answer
A worker index repeats between runs and after a rerun: data from the previous run may remain and cause a conflict. A UUID is always unique, regardless of how many workers there are and how many times the suite was run.
What is the advantage of creating state through the API over a direct DB write, and when is a direct insert still justified?
Answer
The API passes data through business logic, so the state is possible in reality (the balance has an operation entry, validation passed). A direct write gives speed but can create an impossible state. It fits a large volume of data where creating through the API is too slow, and only with invariants preserved.
Related lessons: “Task: test data for parallel runs”, “Environments: local, ephemeral, staging”, “Test framework layers”.
In an interview.Junior: Each test creates the data it needs through the API or a test hook and does not depend on others. I keep only unchangeable reference data shared, and I do not use real personal data in tests. Middle/Senior: I choose the approach by three properties: isolation, speed and honesty of state. The API gives the best balance; a direct DB insert is faster but may create an impossible state, so I keep it for large volumes. I ensure uniqueness with a UUID, and I close a test hook from production by configuration and verify that. Production copies only after anonymisation.
Task: test data for parallel runs
For parallel runs every test or worker gets its own data, because random failures that pass on rerun usually come from shared state. An example is one user for all workers. The fixes are unique data per test, an account pool per worker, a run prefix on entities, or asserting the change instead of an absolute value. A nightly cleanup by prefix is still needed, because worker teardown is not guaranteed.
System design · Data and environments
64 workers, one staging, and the balance in a test is 100, then 70. Who is changing someone else's data?
The condition: 64 parallel workers, a shared staging, tests of transfers between accounts. Tests fail not always and not the same ones: now one, now another, and pass on a rerun. The cause is neither Playwright instability nor a slow environment but shared state. This lesson shows how to recognise it and how to remove it.
Why it fails. Two tests use the same user test_user_1. Test A transfers 30 from a balance of 100, and the balance becomes 70. Test B at that moment checks that the balance is 100 and sees 70. This is a classic race over shared mutable state: while there are few tests they hardly overlap in time, and with 64 workers they overlap constantly, and randomly.
How two tests break one balance
Figure 1. The order in a parallel run is not defined, so the failure does not always repeat.
The diagnostic sign: a test fails with a different result from run to run and passes on a rerun, yet the instability has a concrete cause in the data. That sets it apart from timeouts and waiting for elements.
How it is solved. There are four ways, and they combine:
Unique data per test. A fixture creates a new user and account before the test and deletes them after. This is the cleanest option.
An account pool per worker if creation is expensive. A worker takes an account from the pool, and a worker-scoped fixture in Playwright creates it once per worker.
A run prefix. All entities carry a label, for example run_8f2c_w3_. Cleaning up and sorting out garbage becomes a search by prefix.
Relative checks rather than absolute when state is shared: remember the balance before the action and compare the difference.
The difference between the two indexes is worth knowing. workerInfo.workerIndex is unique for each worker process, and after a test failure Playwright starts a new worker with a new index. workerInfo.parallelIndex lies in the range from 0 to the number of workers minus one and repeats for a new worker that replaced the previous one. For an entity label that must not coincide across processes, workerIndex fits. For a fixed pool of accounts by slot, parallelIndex fits, but then an account may be «dirty» after the previous worker.
If the account is shared within a worker, tests must compare a change rather than an absolute value:
const before = await api.balance(account.id);
await transferPage.send({ to: 'savings', amount: 30 });
await expect.poll(() => api.balance(account.id)).toBe(before - 30);
How many accounts to create
Option 1
New for every test
Maximum isolation. The price: more API requests, setup time, the database grows.
Option 2
One per worker
Faster. The price: tests of a worker share the account, so they must clean up or compare the change.
Figure 2. The choice depends on how much creating an account costs.
Cleanup and limits. The closing part of a fixture runs when the worker ends normally. If the process is killed (a timeout of the whole job, a machine failure), cleanup does not happen. So a separate nightly «janitor» deletes entities with a run prefix older than a few hours. A per-worker pool does not suit tests that need a clean starting state (the first transfer, a zero balance); they need their own accounts. Relative checks do not suit tests of exact sums and record order.
Trade-offs. New data per test gives maximum isolation but loads the API and grows the database. A pool is faster, but tests within a worker must clean up their state or check the change. Prefixes give manageability at the price of discipline: someone has to watch that every entity has one.
Metrics. The number of failures caused by data (tests that fail and pass on a rerun with no code change), the amount of garbage in the DB after a run, data preparation time in a test as a share of the test time.
Common mistakes.
Treating the failure with retries: the test passes on a rerun and the cause stays.
One user per worker, but tests rely on the starting balance: the state depends on test order within the worker.
A run label without uniqueness (only the worker index): two consecutive runs share entities.
Having no cleanup for the crash case: garbage accumulates and the shared environment gets cluttered.
A relative check without waiting: the balance changes asynchronously while the comparison runs now.
Check yourself
Why does a test with a shared test_user_1 fail only sometimes, not always?
Answer
In a parallel run the order and overlap of tests in time are undefined. A failure happens only when test B reads the balance between test A's change and the return of the state. With another arrangement the tests do not overlap and pass. This is a sign of shared state, not an unstable environment.
Why is parallelIndex used for a fixed pool of accounts and workerIndex for an entity label?
Answer
parallelIndex lies in the range from 0 to the number of workers minus one and repeats when a new worker replaces a stopped one, so it fits as a slot number in a pool. workerIndex is unique for each worker process, so a label does not coincide across processes. The drawback of a pool by slot: a new worker inherits the account in the state the previous one left.
Related lessons: “Test data strategies”, “Workers and shards: how parallelisation works”, “Where flaky tests come from”.
In an interview.Junior: I remove shared state: each test or worker gets its own accounts. If creation is expensive, I use a worker-scoped fixture and clean the data by prefix after the run. Middle/Senior: First I recognise the sign: failures are random and vanish on a rerun, while the cause is shared data. Then unique data per test or a pool per worker with a run label. For a pool I distinguish parallelIndex and workerIndex. With shared state I compare the change, not the absolute value. I add a nightly cleanup by prefix, because a worker's shutdown is not guaranteed. Metrics: failures caused by data and garbage in the DB.
Environments: local, ephemeral, staging
Environments trade realism against isolation, so one environment is not enough. Local gives the fastest loop, ephemeral per PR isolates a change, shared staging integrates, and production is used only for smoke and synthetic checks. An ephemeral environment is usually partial: the changed service and its closest neighbours. External dependencies are replaced by HTTP stubs, and a real sandbox stays as a small set outside the PR gates.
System design · Data and environments
A test on staging failed because a neighbouring team deployed their branch. Where to run tests then?
Morning, the run on staging is red. The log shows that the transfer service returned 500, and the cause was not the change in the tested PR but the neighbouring team's branch, deployed to the same environment. A test system is not only test code but also the environments where it runs. This lesson covers which environments exist, how they differ and how to handle external dependencies.
How it works and why. There is a trade-off between realism and isolation, so one environment is not enough. A local setup (docker compose) gives the fastest loop for writing a test. An ephemeral environment per PR isolates the check of a change from all the others. A shared staging integrates with real dependencies, but everyone works there and data is shared. Production is used for smoke and synthetic checks after a release. Each step is more realistic than the previous one but less isolated, and a mistake there costs more.
Four environments and what each is for
Figure 1. The further down, the more realistic, but less isolation and a costlier failure.
An ephemeral environment is brought up for every PR (for example, a separate namespace in Kubernetes) and destroyed after the merge or by a TTL. A plus: no conflicts between teams, clean data, destructive tests are possible. A minus: cost and bring-up time, and starting all 40 microservices for every PR is hard and expensive. So in practice a compromise is common: bring up the changed service and its nearest neighbours, and take the rest from the shared staging or replace them with stubs. The data needs thought too: whether an empty database with seed data comes up, or a test creates everything itself. One more price: the bring-up time is part of PR feedback time, so it is measured as well.
External dependencies. A payment provider, a KYC service and bank APIs often have a sandbox with limits: request limits, instability, the impossibility of reproducing some errors (say, a timeout or a duplicate callback). So for most tests an HTTP-level stub (WireMock or similar) is put in with controlled responses: success, refusal, timeout, repeated delivery. The real sandbox is kept for a small set of integration tests that run separately and do not block a PR.
A payment provider in a test
Option 1
A controlled stub
Responses under control: success, refusal, timeout. Fast and stable. The price: a stub can drift from the real API.
Option 2
A real sandbox
Real provider behaviour. The price: limits, instability, some errors cannot be reproduced.
Figure 2. Most tests on a stub, a small set on the sandbox: each covers the weakness of the other.
Example: a provider timeout. You need to check that the service behaves correctly when the provider answers in 8 seconds while the client timeout is 5. The real sandbox cannot reproduce this, and a stub does it easily. Before the action the test registers a stub through WireMock's admin API and removes it afterwards:
In WireMock such conditions are set by a response delay (fixedDelayMilliseconds) or by connection faults (the fault field, for example CONNECTION_RESET_BY_PEER). WireMock (from 3.1) can send a callback itself through a webhook (serveEventListeners), and a repeated delivery is often simpler to send from the test.
Limits and alternatives. A stub can drift from the real API: the provider changed the response format and the tests are still green. Contract tests (checking the stub against the real provider) and the same small sandbox suite protect against this. If several tests in parallel register stubs on the same WireMock, they interfere: the conditions must be unique (say, by an order identifier) or each worker needs its own instance. Production checks are only safe scenarios: reading, or actions with a dedicated synthetic account under strict limits, because real money does not come back.
Common mistakes.
A single environment for development, tests and demos: someone else's action breaks a run at any moment.
Bringing up everything per PR: the cost and bring-up time eat the benefit of isolation.
Testing payment logic only on the provider's sandbox: errors and timeouts cannot be reproduced there, and its instability blocks a PR.
Stubs never checked against the real API: tests are green while the integration is broken.
Not cleaning up ephemeral environments: bills grow and cluster resources run out.
Check yourself
Why are not all 40 microservices brought up for each PR, and what is done instead?
Answer
It is expensive and slow: the bring-up time is part of PR feedback time. The changed service and its nearest neighbours are brought up, and the rest is taken from the shared staging or replaced with stubs.
A payment provider stub always returns success, and the provider changed its response format. What protects against green tests on a broken integration?
Answer
Contract tests that compare the stub with the real API, and a small separate set of tests on the real sandbox that runs outside the PR gates. The stub gives speed and control, while the sandbox catches the divergence.
Related lessons: “Task: test data for parallel runs”, “Configuration, environments and secrets”, “A microservices testing strategy”.
In an interview.Junior: I split environments by purpose: local for development, ephemeral per PR for isolation, staging for integration, smoke in production. I mostly replace payment services with controlled stubs so I can reproduce errors and timeouts. Middle/Senior: I do not bring up ephemeral in full: the changed service and neighbours, the rest from staging or stubs, because bring-up time is part of feedback. HTTP-level stubs (WireMock) give refusal, timeout and a duplicate callback, while the real sandbox stays a small set outside the PR. I catch stub drift with contract tests. In production only safe scenarios with a dedicated account.