QA Interview Hub · Knowledge base · Quizzes · Українська

Patterns

Singleton and global state

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 globalSetup runs 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 inherit process.env from the runner) or storageState.

How many copies of a module

The runner: config, globalSetupits own process, its own copy of modulesWorker 1: pool #1, state #1the tests and files given to this workerWorker 2: pool #2, state #2does not see the state of worker 1
Figure 1. One module turns into an instance in every process.

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

Safe

Immutable config

Read from env once, then only read. How many copies does not matter.

Dangerous

Mutable state

Test A writes, test B reads: works only if they are in one worker and in the right order.

Figure 2. Immutability makes it safe, not the number of copies.

Common mistakes.

  • Expecting a variable from globalSetup to be available in a test: it is another process, an environment variable or a file is needed.
  • Keeping currentUser or 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 × max may exceed the database max_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.

In an interview. Junior: In Playwright each worker is a separate Node process, so a singleton in a module lives separately in every worker, and there is no shared state between them. Middle/Senior: So I do not keep mutable global state, and I make expensive resources worker fixtures. I pass data from globalSetup through environment variables, a file or storageState, because it runs in the runner process. I size the connection pool with the number of workers in mind, and if dependent tests are still needed I put them in a serial group.

The alternative: a worker fixture instead of a Singleton

Instead of a Singleton, Playwright uses a worker fixture with scope: 'worker': it gives one instance per worker but with a managed lifecycle. The code after await use(...) runs when the worker shuts down, so the resource is reliably closed and the dependency is visible in the test signature. Only an expensive resource is worth lifting to worker level, because its state becomes shared across that worker's tests.

Patterns · Singleton

A DB pool is created in every test or never closed. How to get one per worker?

Everything candidates write a Singleton for (a DB connection, an API client, a config) is better done in Playwright as a worker fixture. It gives the same “one instance per worker” but with a managed lifecycle: whoever created it closes it, and the dependency is visible in the test signature.

How it works and why. A fixture with scope: 'worker' is created once per worker, when the first test asks for it, and lives until the worker shuts down. Everything after await use(...) in the fixture code runs on shutdown, even if tests failed. So cleanup is guaranteed, while a module singleton has no shutdown hook.

There is a dependency rule: a test fixture may depend on a worker fixture, but a worker fixture cannot depend on a test fixture (the worker lives longer). In the base.extend<TestFixtures, WorkerFixtures> signature the second generic is exactly the worker fixtures.

The lifecycle of a worker fixture

The first test that asks for dbthe code before await use(pool) runsThe next tests of this workerget the same poolThe worker shuts downthe code after use() runs: pool.end()
Figure 1. Creation is lazy, closing is guaranteed.

Example: a pool as a worker fixture. Compare with the module getDb from the previous lesson. Four places:

1export const test = base.extend<{}, { db: Pool }>({
  db: [
    async ({}, use) => {
2      const pool = new Pool({ connectionString: process.env.DB_URL, max: 3 });
      await use(pool);
3      await pool.end();
    },
4    { scope: 'worker' },
  ],
});
  1. The second extend parameter describes worker fixtures; the first (empty) one is test fixtures.
  2. The pool is created once per worker, and max: 3 keeps the total number of connections under control.
  3. The code after use closes the pool when the worker shuts down.
  4. Without scope: 'worker' the fixture would be created for every test.

What this gives in practice: an explicit dependency (a test declares { db } and it is visible who goes to the DB), guaranteed closing, and the implementation can be replaced with a separate extend.

Data per worker. The workerInfo parameter (the third argument of a worker fixture) has two indexes. workerIndex is unique for every process, so it changes after a worker restart. parallelIndex lies between 0 and workers - 1 and is kept across a restart, so it is handy for numbering pre-created accounts. This way parallel workers do not touch each other's accounts:

type Account = { id: string; email: string };

export const test = base.extend<{}, { db: Pool; account: Account }>({
  db: [
    async ({}, use) => {
      const pool = new Pool({ connectionString: process.env.DB_URL, max: 3 });
      await use(pool);
      await pool.end();
    },
    { scope: 'worker' },
  ],
  account: [
    async ({ db }, use, workerInfo) => {
      // parallelIndex is stable across a worker restart
      const email = 'qa+w' + workerInfo.parallelIndex + '@example.com';
      const res = await db.query(
        'insert into accounts(email) values ($1) returning id',
        [email],
      );
      await use({ id: res.rows[0].id, email });
      await db.query('delete from accounts where email = $1', [email]);
    },
    { scope: 'worker' },
  ],
});

Limits and alternatives. A worker fixture lives across tests, so state they change becomes shared. If a test leaves junk in the account, the next test of this worker will see it. Keep cheap and isolated resources in a regular test fixture, and lift only what is expensive to create to the worker level.

A Singleton remains acceptable for an immutable config read from env once: there is no state that can be spoiled.

The browser: do not duplicate Playwright

Wrong

A custom singleton browser

Duplicates the worker's browser, bypasses the project settings (browserName, launchOptions) and risks breaking isolation if tests share a context.

Right

The built-in browser and context

One browser per worker, and isolation comes from a fresh context in every test.

Figure 2. A browser per worker already exists: your own singleton only gets in the way.

Common mistakes.

  • “I made a Singleton for the browser so it is not opened in every test”. Playwright already reuses the browser per worker, and isolation comes from a new context. A custom singleton browser duplicates this mechanism, bypasses the project settings (browserName, launchOptions) and risks breaking isolation if tests share one context or page.
  • A worker fixture depends on a test fixture (for example page): the worker lives longer, so Playwright rejects such a dependency.
  • Not closing the resource after use: connections hang, and the worker fixture only hides the leak.
  • One account for all workers without parallelIndex: parallel tests change the same data.
  • Lifting to the worker level what is created in milliseconds: the price of shared state is higher than the gain.

Check yourself

A worker fixture account wants to use page. Why will it not work and what to do?

Answer

page is a test fixture (it lives as long as a test), while a worker fixture lives longer and must exist before the first test. A dependency on a shorter-lived fixture is impossible. Prepare the account with the worker fixture db or an own API client from playwright.request.newContext() (the request fixture, like page, lives within a test), and leave page to the test.

How does parallelIndex differ from workerIndex and which fits a pool of pre-created accounts?

Answer

workerIndex is unique per process and changes when a worker restarts. parallelIndex is from 0 to workers - 1 and is kept across a restart. parallelIndex fits an account pool: the numbering does not grow without bound and the new worker gets the same account.

In an interview. Junior: Instead of a Singleton I make a worker fixture: the same one instance per worker but with an explicit dependency and guaranteed closing. I keep a Singleton only for an immutable config. Middle/Senior: I lift a worker fixture only for an expensive resource and treat state in it as shared between the worker's tests. I build unique data from parallelIndex because it is stable across a restart. I do not write a custom singleton browser: Playwright already keeps a browser per worker, and isolation comes from the context.