Singleton in Node and the Playwright worker model
In Node, one instance means one per process, and Playwright runs tests in several workers, so a module singleton lives separately in each. State written in one worker is invisible to another, and after a failed test the worker restarts with an empty module cache. So mutable global state causes flakes, and a connection pool size is multiplied by the number of workers.
Patterns · Singleton
A counter in a module shows 1 in one test and 0 in the neighbouring one. Where does it live?
A module state.ts holds an object with a counter. Test A increments it, and with --workers=1 test B sees one. With four workers B sees zero, and sometimes one, depending on where the scheduler put it. Such a test passes locally and fails on CI. The reason is that “one instance” in Node means “one per process”, and Playwright has several processes.
How it works and why. A Singleton guarantees one instance and a global access point. In TypeScript it is rarely written as a class with static getInstance(): exporting an object from a module is enough, because a module runs once and is cached. But the module cache belongs to a Node process. Playwright runs tests in several worker processes (by default half of the logical cores, controlled by the workers option). Each worker loads the modules anew.
- A Singleton is “one instance per worker”, not per run.
- State written in one worker is not visible in another.
- A worker in which a test failed is discarded, and the next tests go to a new process with an empty module cache. A retry also runs in a new worker.
- Modules loaded by a worker live as long as it does: state can outlive several tests and even several files of the same worker. That is a temptation, and it is where order dependencies come from.
- Code in
globalSetupruns in the runner process before the workers. Module variables it filled are not visible to tests. Pass data through a file, an environment variable (workers inheritprocess.envfrom the runner) or storageState.
How many copies of a module
Example 1: a “singleton” for the DB.
// db.ts
import { Pool } from 'pg';
let pool: Pool | undefined;
export function getDb() {
pool ??= new Pool({ connectionString: process.env.DB_URL });
return pool;
}
With workers: 4 there are four pools, and that is fine. There are two problems. First, someone has to close the pool, and a plain module has no shutdown hook, so connections hang until the process dies. Second, the number of connections becomes workers × the pool max: four workers with a default pool of ten connections is up to forty, and the DB limit may be lower.
Example 2: mutable state between tests.
// session.ts
export const session: { user?: User } = {};
// users.spec.ts
test('creates a user', async () => {
session.user = await createUser();
});
test('opens the profile', async ({ page }) => {
await page.goto('/users/' + session.user!.id); // TypeError if the worker is another one
});
The second test depends on the first through a module. While both run one after another in one worker, everything works. But if the first test fails (the worker restarts) or fullyParallel is on, the second lands in another process where session.user is empty and fails with a TypeError that has nothing to do with the function under test. This is how instability looks like “we did not change the code and the test started failing”.
Limits and alternatives. Dependent tests can be bound on purpose: test.describe.configure({ mode: 'serial' }) runs them one after another in one worker: if one test fails the rest are skipped, and with retries enabled the whole group is retried from the start. It works, but such a group is cut off from parallelism, so it is better for each test to create its own data (a factory, a fixture). For expensive resources (a pool, a client, an account) there are worker fixtures: the next lesson.
When a singleton is safe
Immutable config
Read from env once, then only read. How many copies does not matter.
Mutable state
Test A writes, test B reads: works only if they are in one worker and in the right order.
Common mistakes.
- Expecting a variable from
globalSetupto be available in a test: it is another process, an environment variable or a file is needed. - Keeping
currentUseror a counter in a module that tests change: the order and the distribution over workers become a hidden dependency. - Creating a pool lazily in every worker and never closing it: connections pile up and on CI the DB limit runs out.
- Ignoring the workers multiplier in the pool size:
workers × maxmay exceed the databasemax_connections. - Assuming the module cache is reset between files: within a worker it lives, so state leaks between files.
Check yourself
Test A writes session.user, test B in the same file reads it. Locally all is green, on CI B fails with a TypeError. What changed?
Answer
On CI fullyParallel is on (or a test failed before B and the worker restarted), and B ended up in a process where the session module is still empty: by default the tests of one file run in order in one worker. A singleton lives separately in every worker, so the dependency on order and shared state does not hold.
workers: 4, getDb has a pool with max 10. How many DB connections can be expected at the peak?
Answer
Up to forty: one pool in each of the four workers, each with up to ten connections. Plus connections opened by globalSetup or other clients. The pool size should be the DB limit divided by the number of workers.