Budget realtime connections per API instance and Postgres superuser reserve
ci / rust (push) Successful in 11m46s
ci / typescript (push) Successful in 15m42s

dbConnectionBudget() only subtracted the API's Prisma pool and the worker's
own 1-connection remote broadcaster, so it never counted the 3 connections
each API process opens for realtime (attachRealtime: a 2-connection publish
pool plus a dedicated LISTEN client), nor the connections Postgres reserves
for superuser roles below max_connections -- exactly what "remaining
connection slots are reserved for roles with the SUPERUSER attribute" means.
With 2 API instances that gap was 9 connections, enough for the worker and
API together to run the cluster right up against the ceiling.

dbConnectionBudget() now takes realtimePerInstance and superuserReserved
(new DB_SUPERUSER_RESERVED_CONNECTIONS env var, default 3) and subtracts
both explicitly instead of leaving them to be absorbed by headroom.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31533
Paperclip-Run: fc6639aa-bf73-43f0-b3f6-85835a1f809b
This commit is contained in:
tiago-neves committed 2026-10-19 04:13:14 +01:00
1 parent 8020574415
commit d6a7edda38
5 files changed
+38 -11

No files matched your search

+1
View File
@@ -9,6 +9,7 @@ DATABASE_URL=postgresql://photoreport:CHANGE_ME@pr-db:5432/photoreport
# API_DB_POOL_SIZE=
# API_INSTANCES=
# DB_MAX_CONNECTIONS=
# DB_SUPERUSER_RESERVED_CONNECTIONS=
# At least 32 random characters, e.g. `openssl rand -base64 48`
JWT_SECRET=
ACCESS_TOKEN_TTL_SEC=900
+2
View File
@@ -19,6 +19,8 @@ const Env = z.object({
API_INSTANCES: z.coerce.number().int().positive().default(2),
/** Postgres' max_connections, so the worker leaves it enough room for the API and admin/migration connections. */
DB_MAX_CONNECTIONS: z.coerce.number().int().positive().default(100),
/** Postgres' superuser_reserved_connections: never available to the app, whatever max_connections says. */
DB_SUPERUSER_RESERVED_CONNECTIONS: z.coerce.number().int().nonnegative().default(3),
JWT_SECRET: z.string().min(32, "JWT_SECRET must have at least 32 characters"),
ACCESS_TOKEN_TTL_SEC: z.coerce.number().int().positive().default(900),
REFRESH_TOKEN_TTL_DAYS: z.coerce.number().int().positive().default(30),
+22 -4
View File
@@ -134,13 +134,31 @@ export class Pressure {
/**
* How many Postgres connections the worker's pool may open for `wanted`, leaving room under `max` (Postgres'
* `max_connections`) for the API's own pools (one per PM2 cluster instance), the realtime broadcaster's one
* connection, and headroom for ad hoc connections (migrations, scripts, psql) that aren't sized here.
* `max_connections`) for: the API's own Prisma pool, one per PM2 cluster instance; each of those instances'
* realtime connections (`attachRealtime` in `realtime.ts`: a 2-connection publish pool plus one dedicated
* `LISTEN` client, so 3 per instance — not just the worker's own 1-connection remote broadcaster); Postgres'
* `superuser_reserved_connections` (reserved below `max_connections`, never available to the app no matter
* how much headroom is left — this is what "reserved for roles with the SUPERUSER attribute" means); and
* extra headroom for ad hoc connections (migrations, scripts, psql, admin tools) that aren't sized here.
*/
export function dbConnectionBudget(
wanted: number,
{ max = 100, apiInstances = 2, apiPoolSize = 10, headroom = 10 }: { max?: number; apiInstances?: number; apiPoolSize?: number; headroom?: number } = {},
{
max = 100,
apiInstances = 2,
apiPoolSize = 10,
realtimePerInstance = 3,
superuserReserved = 3,
headroom = 10,
}: {
max?: number;
apiInstances?: number;
apiPoolSize?: number;
realtimePerInstance?: number;
superuserReserved?: number;
headroom?: number;
} = {},
): number {
const available = max - apiInstances * apiPoolSize - 1 - headroom;
const available = max - superuserReserved - apiInstances * (apiPoolSize + realtimePerInstance) - 1 - headroom;
return Math.max(1, Math.min(wanted, available));
}
+8 -2
View File
@@ -64,11 +64,17 @@ const capacity = planCapacity({
});
log.info(capacity, "capacity");
// Enough connections for everything running at once, within what's left of Postgres' max_connections once the
// API's cluster, the realtime broadcaster and ad hoc connections (migrations, scripts, psql) have theirs.
// API's cluster (Prisma pool and realtime connections), the superuser-reserved slots, the realtime broadcaster
// and ad hoc connections (migrations, scripts, psql) have theirs.
const wanted = 10 + Math.ceil((capacity.archiveDownloads + capacity.faces + capacity.ingest) / 2);
const db = createDb(
config.DATABASE_URL,
dbConnectionBudget(wanted, { max: config.DB_MAX_CONNECTIONS, apiInstances: config.API_INSTANCES, apiPoolSize: config.API_DB_POOL_SIZE }),
dbConnectionBudget(wanted, {
max: config.DB_MAX_CONNECTIONS,
apiInstances: config.API_INSTANCES,
apiPoolSize: config.API_DB_POOL_SIZE,
superuserReserved: config.DB_SUPERUSER_RESERVED_CONNECTIONS,
}),
);
const storage = new LocalStorage(config.STORAGE_ROOT);
const broadcaster = createRemoteBroadcaster(config.DATABASE_URL, (err) => log.error({ err }, "realtime publish failed"));
+5 -5
View File
@@ -40,15 +40,15 @@ describe("capacity", () => {
});
describe("dbConnectionBudget", () => {
it("stays under what the API's cluster, the broadcaster and headroom leave of max_connections", () => {
// 100 - (2 api instances * 10) - 1 broadcaster - 10 headroom = 69.
expect(dbConnectionBudget(500)).toBe(69);
it("stays under what the API's cluster, the superuser reserve, the broadcaster and headroom leave of max_connections", () => {
// 100 - 3 superuser reserved - (2 api instances * (10 pool + 3 realtime)) - 1 broadcaster - 10 headroom = 60.
expect(dbConnectionBudget(500)).toBe(60);
expect(dbConnectionBudget(10)).toBe(10);
});
it("follows a differently sized API cluster or Postgres limit", () => {
expect(dbConnectionBudget(500, { max: 200, apiInstances: 4, apiPoolSize: 15 })).toBe(129);
expect(dbConnectionBudget(500, { max: 40, apiInstances: 2, apiPoolSize: 10 })).toBe(9);
expect(dbConnectionBudget(500, { max: 200, apiInstances: 4, apiPoolSize: 15 })).toBe(114);
expect(dbConnectionBudget(500, { max: 40, apiInstances: 2, apiPoolSize: 10 })).toBe(1);
});
it("never goes below 1, even if the API and headroom already exceed max_connections", () => {