# Size CI Parallelism From Dependency Capacity, Not Runners

> Four shards against a 24-connection PostgreSQL failed 43 of 48 tests in 0.4 seconds, the fastest run of the day. This guide sizes fan-out from the dependency's budget, shows why max-parallel bounds only one run, turns concurrency groups into queued slots, fences the database role, and tests where Playwright locks stop.

- Author: [Shashank Rawlani](https://shashank.rawlani.com)

- Published: 2026-11-17T13:30:00.000Z

- Updated: 2026-11-17T13:30:00.000Z

- Category: Automation Tutorials

- Canonical source: https://automationtester.in/blog/automation-tutorials/control-ci-parallelism-dependency-capacity

- Tags: ci-cd, github-actions, test-parallelism, playwright, postgresql, test-infrastructure

**Quick answer:** Count the total concurrent workers your pipeline can put on each shared dependency, not the runners you can rent. Measure what one worker consumes (connections, requests per minute), divide each dependency's usable budget by it after keeping 20% headroom, and take the smallest result. Then enforce it in three places: concurrency groups that act as named slots so the limit holds across workflow runs, a hard limit on the dependency side such as a PostgreSQL role `CONNECTION LIMIT`, and Playwright test locks for the few tests that cannot overlap inside one run. `max-parallel` alone bounds one matrix in one run, which is rarely the thing that runs out.

An end-to-end suite runs on two shards, and someone doubles the matrix to four to cut the wait. The next run finishes faster than any before it, and 43 of its 48 database-backed tests fail with `remaining connection slots are reserved for non-replication superuser connections`. Re-running only the failed jobs puts less load on the database than the original run did, so a rerun can pass and make the failure look like flakiness. It is arithmetic: four shards of two workers, each worker holding four connections, ask for 32 connections from a server that admits 21 ordinary ones.

Earlier parts of this series decided [which tests run at which stage](/blog/automation-tutorials/ci-test-pyramid-feedback-cost) and [kept parallel workers out of each other's data](/blog/automation-tutorials/eliminate-ci-test-data-collisions). Isolated data does not help when the dependency refuses the connection before any data is read. This part sizes fan-out from the thing that runs out, and enforces that size where GitHub Actions, PostgreSQL and Playwright each can.

**Versions checked on 2026-11-09:** `@playwright/test` 1.65.0 and `pg` (node-postgres) 8.23.1 are the current npm releases, and actionlint v1.7.12 (published 2026-03-30) is its latest release. The runs below used those versions with Node.js 26.12.1 on an Apple silicon Mac, against a throwaway PostgreSQL 14.21 cluster listening only on 127.0.0.1. PostgreSQL behaviour was checked against the version 18 documentation; PostgreSQL 14 reaches end of life on 2026-11-12, and its error wording differs from newer releases. GitHub Actions behaviour comes from GitHub's documentation on the same date and was not exercised on hosted runners.

## Two shards pass, four shards fail in under a second

The reproduction needs no browser. A throwaway cluster is started with `max_connections=24` and a non-superuser login role, `ci_tests`, standing in for the test suite. A launcher spawns one Node.js process per shard, because shards are separate CI jobs on separate machines, and each shard runs a number of workers. Every worker owns a pool, and every test holds four connections at once for 200 ms, the way a test does when the app under test, a seeding fixture and an assertion query all reach the same database:

```
// shards.mjs (excerpt): one process per shard, WORKERS pools per process
const DB = { host: '127.0.0.1', port: 56517, database: 'postgres' };
const SHARDS = Number(process.env.SHARDS ?? 4);
const WORKERS = Number(process.env.WORKERS ?? 2);
const CONNS = Number(process.env.CONNS ?? 4);
const TESTS = Number(process.env.TESTS ?? 6); // tests per worker

async function worker(id) {
  const pool = new pg.Pool({ ...DB, user: 'ci_tests', max: CONNS });
  pool.on('error', () => {});
  const out = { passed: 0, failed: 0, errors: {} };
  for (let t = 0; t < TESTS; t++) {
    const held = [];
    try {
      for (let c = 0; c < CONNS; c++) held.push(await pool.connect());
      await Promise.all(held.map((cl) => cl.query('SELECT pg_sleep(0.2)')));
      out.passed++;
    } catch (e) {
      out.failed++;
      const key = `${e.code} ${e.message}`;
      out.errors[key] = (out.errors[key] ?? 0) + 1;
    } finally {
      held.forEach((cl) => cl.release());
    }
  }
  await pool.end();
  return out;
}
```

The parent process samples `pg_stat_activity` every 10 ms through a separate superuser connection and reports the peak. Three runs, changing only the shape of the fan-out:

```
$ SHARDS=4 node shards.mjs
shards=4 workers/shard=2 conns/worker=4 demand=32
tests passed=5 failed=43
peak ci_tests connections=20 wall=0.4s
  43 x 53300 remaining connection slots are reserved for non-replication superuser connections

$ SHARDS=2 node shards.mjs
shards=2 workers/shard=2 conns/worker=4 demand=16
tests passed=24 failed=0
peak ci_tests connections=16 wall=1.4s

$ SHARDS=4 WORKERS=1 node shards.mjs
shards=4 workers/shard=1 conns/worker=4 demand=16
tests passed=24 failed=0
peak ci_tests connections=16 wall=1.4s
```

The failing run was the fastest. Refused connections fail in milliseconds, so a pipeline dashboard that tracks duration shows the over-sharded configuration as an improvement until someone reads the failure count.

The peak stopped at 20, not 21. PostgreSQL documents that once active connections reach `max_connections` minus `superuser_reserved_connections` (default three), only superusers may connect. That gives 21 ordinary slots here, and the sampler's own connection occupied one of them. Monitoring sessions, migration jobs and a developer's `psql` all spend the same budget as the tests.

Two shards of two workers and four shards of one worker produced identical results. The database cannot see shards. It sees concurrent connections, so the quantity to control is total workers multiplied by connections per worker, wherever those workers happen to run.

Match the failure by SQLSTATE `53300` (`too_many_connections`), not by message text. The wording above is PostgreSQL 14's. The PostgreSQL 18 source says `remaining connection slots are reserved for roles with the SUPERUSER attribute` instead, so a log filter written for one version misses the other.

## Write the budget down before choosing a shard count

Every shared dependency on the test path has a capacity and a per-worker cost. The smallest quotient wins, and runner availability is only one row in the table:

```
// size-parallelism.mjs: the smallest budget wins. Inputs are measured, not guessed.
const headroom = 0.2; // keep 20% of every dependency free for retries, the app, and humans

const budgets = {
  'runner slots': { capacity: 16, perWorker: 1 },                 // concurrent jobs x workers you can actually get
  'staging db connections': { capacity: 40, perWorker: 4 },       // role CONNECTION LIMIT, not max_connections
  'payments sandbox req/min': { capacity: 600, perWorker: 90 },   // vendor limit; perWorker from one shard's logs
};

const workersPerShard = 2;
let binding = null;
for (const [name, { capacity, perWorker }] of Object.entries(budgets)) {
  const usable = name === 'runner slots' ? capacity : Math.floor(capacity * (1 - headroom));
  const maxWorkers = Math.floor(usable / perWorker);
  console.log(`${name.padEnd(26)} usable=${String(usable).padStart(4)} perWorker=${String(perWorker).padStart(3)} -> max workers ${maxWorkers}`);
  if (!binding || maxWorkers < binding.maxWorkers) binding = { name, maxWorkers };
}
const shards = Math.max(1, Math.floor(binding.maxWorkers / workersPerShard));
console.log(`binding constraint: ${binding.name}`);
console.log(`total workers <= ${binding.maxWorkers}; at ${workersPerShard} workers per shard: max-parallel ${shards}`);
```

```
$ node size-parallelism.mjs
runner slots               usable=  16 perWorker=  1 -> max workers 16
staging db connections     usable=  32 perWorker=  4 -> max workers 8
payments sandbox req/min   usable= 480 perWorker= 90 -> max workers 5
binding constraint: payments sandbox req/min
total workers <= 5; at 2 workers per shard: max-parallel 2
```

Each input has a trap.

**Per-worker cost** comes from a measured run, not from the pool's `max` setting. Run one shard with one worker, take the peak of `pg_stat_activity` for the test role, and read the sandbox's request count from that shard's logs. node-postgres defaults a pool to 10 clients and opens them lazily, so the configured maximum overstates some suites and the measurement shows the truth.

**Workers per shard** must be pinned. Playwright's `workers` option defaults to half the logical CPU cores, so moving a job to a larger runner silently multiplies database demand with no change to the workflow file. Set it explicitly (`--workers=2` or a fixed number in the config) so that a runner upgrade cannot change the connection count. Playwright's own CI guide goes further and recommends one worker in CI, with sharding for wider parallelism.

**Rate-limited APIs** have a floor on wall time that no shard count moves. RFC 6585 defines 429 Too Many Requests and states that it does not define how the server identifies the user or counts requests; a sandbox keyed on one API key counts every shard together. If the suite makes 4,800 sandbox calls and the usable budget is 480 a minute, the run cannot finish in under ten minutes. Shards past the budget turn into 429 responses and retries rather than speed.

**Runner slots** are the least likely binding constraint, which is why sizing from them goes wrong. GitHub documents a ceiling of 20 concurrent jobs for standard hosted runners on the Free plan, 40 on Pro, 60 on Team and 500 on Enterprise, with macOS capped at 5 below Enterprise.

## What each GitHub Actions control actually limits

The controls look interchangeable and are not. Their scopes differ:

| Control | Scope | Bounds | Does not bound |
| --- | --- | --- | --- |
| `strategy.max-parallel` | One matrix in one workflow run | Jobs from that matrix running at once | The same matrix in a second run, triggered by another PR |
| Workflow-level `concurrency` | Repository, per group name | One running and, by default, one pending run per group | Anything per shard; it may only use the `github`, `inputs` and `vars` contexts, so `matrix` is unavailable |
| Job-level `concurrency` | Repository, per group name | One running job per group, and its group may use `matrix` and `strategy` | Workflows in other repositories that hit the same dependency |
| `cancel-in-progress` | The same group | Time a superseded run keeps holding capacity | Load from runs in other groups |

A matrix with `max-parallel: 2` keeps one run at two shards. Three open pull requests pushing at once put six shards on staging, and nothing in the matrix definition counts the other runs.

### Concurrency groups as numbered slots

Job-level concurrency allows the `matrix` context in the group name. Naming the group after the shard turns each shard index into a slot that at most one job in the repository can hold:

```
name: e2e
on:
  pull_request:
  push:
    branches: [main]

concurrency:
  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}

jobs:
  e2e:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    concurrency:
      group: staging-db-slot-${{ matrix.slot }}
      queue: max
    strategy:
      fail-fast: false
      max-parallel: 2
      matrix:
        slot: [1, 2]
    steps:
      - uses: actions/checkout@v5
      - run: npx playwright test --shard=${{ matrix.slot }}/2 --workers=2
```

Two slot groups, each admitting one running job, cap staging at two shards of two workers across every run in the repository: the five-worker budget computed above, rounded down to whole shards.

`queue: max` is not optional here. By default a concurrency group holds at most one pending job, and a newly queued job cancels the existing pending one. With three runs competing, the second run's slot-1 job is cancelled the moment the third run queues, and the second run ends with a cancelled shard and an incomplete result. `queue: max` lets up to 100 jobs wait per group, processed first-in-first-out by the time each started waiting, and cancels any beyond that.

The documentation forbids combining `queue: max` with `cancel-in-progress: true` and calls it a workflow validation error. The file above keeps the two in separate `concurrency` blocks with separate groups: cancellation of superseded pull request runs at the workflow level, queuing at the slot level. Because that pairing was not exercised on hosted runners here, push it to a throwaway branch with two overlapping runs and watch the slot jobs queue before relying on it.

The workflow-level group uses `github.head_ref || github.run_id`, the fallback GitHub documents, so pushes to `main` get a unique group and are never cancelled, and the expression on `cancel-in-progress` cancels only pull request runs. `fail-fast: false` matters for diagnosis: `fail-fast` defaults to `true` and cancels every in-progress and queued matrix job when one fails, so a capacity failure in one shard would leave its siblings marked cancelled instead of showing whether they hit the same limit.

One tooling snag: actionlint v1.7.12 rejects the documented key.

```
$ actionlint .github/workflows/e2e.yml
.github/workflows/e2e.yml:17:7: unexpected key "queue" for "concurrency" section. expected one of "cancel-in-progress", "group" [syntax-check]

$ actionlint -ignore 'unexpected key "queue" for "concurrency" section' .github/workflows/e2e.yml
$ echo $?
0
```

Ignore that exact message rather than the whole syntax-check rule, so a misspelt `cancel-in-progres` is still caught. For more on how matrix values expand into job names and slot values, the [matrix include and exclude preview](/blog/tools-reviews/preview-github-actions-matrix-include-exclude) shows the generated jobs before a run does.

## Put the hard limit on the dependency

Concurrency groups are scoped to one repository; GitHub's documentation describes pending and cancellation only for runs "in the repository". A nightly job in another repository, a load test, or a second team's pipeline sharing staging is invisible to them. The limit that holds regardless of who connects belongs in the dependency:

```
$ psql -h 127.0.0.1 -p 56517 -U labadmin -d postgres -c 'ALTER ROLE ci_tests CONNECTION LIMIT 12'
ALTER ROLE

$ SHARDS=2 node shards.mjs
shards=2 workers/shard=2 conns/worker=4 demand=16
tests passed=3 failed=21
peak ci_tests connections=12 wall=0.3s
  21 x 53300 too many connections for role "ci_tests"

$ SHARDS=3 WORKERS=1 node shards.mjs
shards=3 workers/shard=1 conns/worker=4 demand=12
tests passed=18 failed=0
peak ci_tests connections=12 wall=1.3s
```

Same SQLSTATE, different message, very different meaning. The role fence refused the suite while the other nine ordinary slots stayed free for the application and its operators. Without the fence, the same overload took slots from everything else connected to that server. The `CREATE ROLE` documentation notes that only normal connections count toward the limit; prepared transactions and background worker connections do not.

PostgreSQL 16 added a second lever, absent from the 14.21 cluster used here and therefore not demonstrated: `reserved_connections` keeps slots for roles granted `pg_use_reserved_connections`, admitted after ordinary roles are refused and before the superuser reserve. Granting it to the application's role means a runaway suite exhausts its own share first.

Do not raise `max_connections` to make the error go away. The documentation states it can only be set at server start and that PostgreSQL sizes shared memory and other resources directly from it. The fence plus a measured budget fixes the cause; a larger ceiling postpones the same failure to a bigger matrix.

For a rate-limited API you do not control, the vendor's limit is the fence. Give CI its own sandbox key where the vendor allows it, so a pipeline that exceeds its budget gets the 429 and production-like manual testing does not.

## Serialise a few tests inside one run with Playwright locks

Some contention is narrower than a whole dependency: three tests that change one global sandbox setting, or a test that restarts a shared service. Playwright 1.63 added test locks, and 1.65 added the built-in `-exclusive-` lock that runs a test only when nothing else is running. Tests that share a lock name never overlap, while every other test keeps running in parallel:

```
// tests/payments.spec.mjs
import { test } from '@playwright/test';
import { appendFileSync } from 'node:fs';

const log = (name, edge) => appendFileSync('timeline.log', `${Date.now()} ${edge} ${name}\n`);
const work = async (name) => {
  log(name, 'start');
  await new Promise((r) => setTimeout(r, 500));
  log(name, 'end');
};

test('sandbox refund', { lock: 'payments-sandbox' }, () => work('refund'));
test('local search', () => work('search'));
test('sandbox capture', { lock: 'payments-sandbox' }, () => work('capture'));
test('sandbox void', { lock: 'payments-sandbox' }, () => work('void'));
test('local profile', () => work('profile'));
test('local cart', () => work('cart'));
```

With `fullyParallel: true` and four workers, a small script replays the timeline and reports the most sandbox tests running at one instant. The same suite was then run as two shards started at the same moment, the way two matrix jobs start:

```
$ npx playwright test
  6 passed (1.9s)
$ node overlap.mjs
peak concurrent sandbox tests: 1

$ npx playwright test --shard=1/2 & npx playwright test --shard=2/2 & wait
  3 passed (1.4s)
  3 passed (909ms)
$ node overlap.mjs
peak concurrent sandbox tests: 2
```

Playwright documents that locks work across files, worker processes and projects. The second run shows the boundary that sentence implies: each shard is its own test run, and a lock in one cannot see the other. Locks handle contention inside a job; slot groups and the dependency fence handle it across jobs. The docs add one cost: in the default and serial modes all tests in a file run together, so a lock on any test is held for the whole file.

## Telling capacity failures apart

Each of these looks like a flaky test in a run summary, and each has a different check.

### 53300 with the reserved-slots message

The whole server ran out of ordinary slots, so CI took capacity from everything else. While a failing run is in progress, group the connections by role:

```
SELECT usename, state, count(*)
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY 1, 2 ORDER BY 3 DESC;
```

```
 usename  | state  | count
----------+--------+-------
 ci_tests | active |    16
 labadmin | active |     1
 labadmin | idle   |     1
```

If the test role dominates, lower total workers and add the role fence. If another role dominates, the tests are victims, and the fix belongs to whoever owns that role.

### 53300 naming your role

The fence did its job. The suite exceeded its own budget, and nothing else was harmed. Lower workers per shard or the slot count until one run's peak, measured as above, sits below the limit with headroom.

### Shard jobs marked cancelled, with no test failure

Either a concurrency group with the default single pending slot replaced a waiting job, or `fail-fast` cancelled siblings after one shard failed. Open the run and check which job failed first; if none did, the queue replaced it, and `queue: max` on the slot group is the fix.

### 429 from a third-party sandbox

Every shard shares the key's budget. Read `Retry-After`, which RFC 9110 allows as either a date or a number of seconds, and honour it in the client; then recompute the budget, because retries spend the same allowance that caused the 429.

Tests that time out with no database error at all usually mean the client pool is queueing: node-postgres waits for a free client indefinitely unless `connectionTimeoutMillis` is set. [Finding which pool or queue saturates first](/blog/automation-tutorials/capacity-testing-bottlenecks-queues-pools) covers that wait in depth.

## Apply this now

Pick the job that fans out widest against staging. Run it once as a single shard with one worker and record two numbers: peak `pg_stat_activity` rows for the test role, and the count of calls to each rate-limited API. Fill in the sizing script with those and with each dependency's real limit, and set `max-parallel`, the slot list and `--workers` to its output. Then create a dedicated test role with a `CONNECTION LIMIT` at that budget, and keep the evidence for the change: the sizing output, a passing run at the new shard count, and one deliberate run one shard above it that fails with `53300` naming the test role and nothing else.

## Questions about CI fan-out and shared dependencies

### Should a test retry when it gets 53300?

Not as the fix. The retry arrives while the budget is still exhausted, and every retried attempt is another connection request. A retry can cover a rare spike once the budget is right; if 53300 shows up in most runs, the shard count is wrong.

### Should `cancel-in-progress` apply to `main`?

Usually not. Cancelling a superseded pull request run frees capacity at no cost, because nobody needs that result. Cancelling runs on `main` loses the per-commit result that tells you which merge broke it. GitHub's documented pattern is an expression, such as cancelling everywhere except `release/` branches; the workflow above cancels only `pull_request` runs.

### What caps the total when two repositories use one staging database?

Only the dependency. Concurrency groups never see another repository's runs, so give each repository its own role with its own `CONNECTION LIMIT`, and make the limits add up to less than the ordinary slots the server admits.

## References for parallelism and capacity limits

- [Control the concurrency of workflows and jobs](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency). One running and one pending job per group, default replacement of pending jobs, `queue: max` with its 100-job cap and FIFO order, the ban on combining it with `cancel-in-progress: true`, case-insensitive group names, and the `head_ref || run_id` fallback.

- [Workflow syntax for GitHub Actions](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax). Contexts allowed in workflow-level versus job-level `concurrency`, `max-parallel` defaulting to runner availability, and `fail-fast` defaulting to true.

- [Running variations of jobs in a workflow](https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/run-job-variations). `max-parallel` limiting jobs from one matrix even when runners are free.

- [Actions limits](https://docs.github.com/en/actions/reference/limits). Concurrent job ceilings per plan and the 100-run concurrency group queue.

- [Playwright parallelism guide](https://playwright.dev/docs/test-parallel). Worker processes, test locks across files, workers and projects, the `-exclusive-` lock, and locks held for a whole file in default and serial modes.

- [Playwright sharding guide](https://playwright.dev/docs/test-sharding). `--shard=x/y` and test-level versus file-level shard balancing with `fullyParallel`.

- [Playwright TestConfig reference](https://playwright.dev/docs/api/class-testconfig). `workers` defaulting to half the logical CPU cores.

- [Running Playwright on CI](https://playwright.dev/docs/ci). The recommendation of one worker in CI and sharding for wider parallelism.

- [Playwright release notes](https://playwright.dev/docs/release-notes). Test locks in 1.63, `describe.configure` locks in 1.64, and the `-exclusive-` lock in 1.65.

- [PostgreSQL connection settings](https://www.postgresql.org/docs/current/runtime-config-connection.html). `max_connections` set only at server start and sizing shared memory, `superuser_reserved_connections` defaulting to three, and `reserved_connections` with `pg_use_reserved_connections`.

- [PostgreSQL CREATE ROLE](https://www.postgresql.org/docs/current/sql-createrole.html). `CONNECTION LIMIT` semantics and which connections it counts.

- [PostgreSQL error codes appendix](https://www.postgresql.org/docs/current/errcodes-appendix.html). SQLSTATE 53300 as `too_many_connections`.

- [node-postgres pool API](https://node-postgres.com/apis/pool). A pool's default of 10 clients and `connectionTimeoutMillis` defaulting to no timeout.

- [RFC 6585, section 4](https://www.rfc-editor.org/rfc/rfc6585#section-4). 429 Too Many Requests, and the server choosing how it identifies the user and counts requests.

- [RFC 9110, section 10.2.3](https://www.rfc-editor.org/rfc/rfc9110#section-10.2.3). `Retry-After` as an HTTP-date or a delay in seconds.

- [PostgreSQL 18 connection startup source](https://github.com/postgres/postgres/blob/REL_18_STABLE/src/backend/utils/init/postinit.c). The PostgreSQL 18 wording of the reserved-slots refusal, which differs from version 14's.

- [PostgreSQL 16.0 release notes](https://www.postgresql.org/docs/release/16.0/). `reserved_connections` and the `pg_use_reserved_connections` role arriving in version 16.

- [actionlint v1.7.12 release](https://github.com/rhysd/actionlint/releases/tag/v1.7.12). The latest release on the check date, which reports `queue` as an unexpected key.

## Continue reading on AutomationTester.in

- [Preview a GitHub Actions Matrix Before include Adds the Wrong Jobs](https://automationtester.in/blog/tools-reviews/preview-github-actions-matrix-include-exclude)
- [Gate an MCP Server and Client on the Official Conformance Suite](https://automationtester.in/blog/ai-in-testing/mcp-conformance-framework-ci)
- [Build Trustworthy Database Tests with Testcontainers](https://automationtester.in/blog/automation-tutorials/testcontainers-database-integration-tests-trustworthy)
- [Write k6 Thresholds That Fail CI for the Right Reasons](https://automationtester.in/blog/automation-tutorials/k6-thresholds-fail-ci-right-reasons)
- [Understand Appium 3 Drivers, Plugins, and Boundaries](https://automationtester.in/blog/automation-tutorials/appium-drivers-plugins-test-boundaries)

Source: [Size CI Parallelism From Dependency Capacity, Not Runners](https://automationtester.in/blog/automation-tutorials/control-ci-parallelism-dependency-capacity) by Shashank Rawlani.
