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.

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 and kept parallel workers out of each other's data. 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.
@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 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 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. One running and one pending job per group, default replacement of pending jobs,
queue: maxwith its 100-job cap and FIFO order, the ban on combining it withcancel-in-progress: true, case-insensitive group names, and thehead_ref || run_idfallback. - Workflow syntax for GitHub Actions. Contexts allowed in workflow-level versus job-level
concurrency,max-paralleldefaulting to runner availability, andfail-fastdefaulting to true. - Running variations of jobs in a workflow.
max-parallellimiting jobs from one matrix even when runners are free. - Actions limits. Concurrent job ceilings per plan and the 100-run concurrency group queue.
- Playwright parallelism guide. 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.
--shard=x/yand test-level versus file-level shard balancing withfullyParallel. - Playwright TestConfig reference.
workersdefaulting to half the logical CPU cores. - Running Playwright on CI. The recommendation of one worker in CI and sharding for wider parallelism.
- Playwright release notes. Test locks in 1.63,
describe.configurelocks in 1.64, and the-exclusive-lock in 1.65. - PostgreSQL connection settings.
max_connectionsset only at server start and sizing shared memory,superuser_reserved_connectionsdefaulting to three, andreserved_connectionswithpg_use_reserved_connections. - PostgreSQL CREATE ROLE.
CONNECTION LIMITsemantics and which connections it counts. - PostgreSQL error codes appendix. SQLSTATE 53300 as
too_many_connections. - node-postgres pool API. A pool's default of 10 clients and
connectionTimeoutMillisdefaulting to no timeout. - RFC 6585, section 4. 429 Too Many Requests, and the server choosing how it identifies the user and counts requests.
- RFC 9110, section 10.2.3.
Retry-Afteras an HTTP-date or a delay in seconds. - PostgreSQL 18 connection startup source. The PostgreSQL 18 wording of the reserved-slots refusal, which differs from version 14's.
- PostgreSQL 16.0 release notes.
reserved_connectionsand thepg_use_reserved_connectionsrole arriving in version 16. - actionlint v1.7.12 release. The latest release on the check date, which reports
queueas an unexpected key.
CI and Test Infrastructure
CI and Test Infrastructure
Get part 6: Retain CI Artifacts That Explain a Failure on Their Own
It is live now: read part 6. The form below subscribes you to The Automation Brief, the site newsletter.
No spam, no sending cadence promised. Unsubscribe any time.