From 8b73070b87b2ce9b6f47145b8f661859142cce9d Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Thu, 3 Dec 2026 08:40:41 -0500 Subject: [PATCH 1/3] fix(readyz): probe Postgres on a connection the readiness check owns The readiness ping took a connection from the master pool, whose max is 3. Three queries that never completed held every slot, so the ping waited for an acquire (up to 60s) behind a 3s race that neither cancelled nor released anything: /readyz answered database: {ok:false} against a database that answered a fresh client in milliseconds. The ping now opens its own client from the master connection config, bounded by ADMIN_DEPENDENCY_PING_TIMEOUT_MS for connect, query and statement, and destroys that connection when the timeout fires. Measured against the relay's Postgres with all three pool slots held by pg_sleep: the pooled raw('select 1') timed out at 3001ms, the new probe answered ok in 8ms. Closes #1356 --- .changeset/readyz-own-connection.md | 15 +++++ deploy/README.md | 10 +++- src/database/client.ts | 10 +++- src/utils/admin-health.ts | 85 ++++++++++++++++++++++++++-- test/unit/utils/admin-health.spec.ts | 69 +++++++++++++++++++++- 5 files changed, 181 insertions(+), 8 deletions(-) create mode 100644 .changeset/readyz-own-connection.md diff --git a/.changeset/readyz-own-connection.md b/.changeset/readyz-own-connection.md new file mode 100644 index 000000000..37026c239 --- /dev/null +++ b/.changeset/readyz-own-connection.md @@ -0,0 +1,15 @@ +--- +--- + +fix(readyz): probe Postgres on a connection the readiness check owns + +`pingDatabase()` took a connection from the master pool, whose `max` is 3. Three +queries that never completed held every slot, so the readiness ping waited for an +acquire (up to 60s) behind a 3s race that neither cancelled nor released anything: +`/readyz` answered `database: {ok:false}` against a database that answered a fresh +client in milliseconds, until the process was restarted. + +The ping now opens its own client from the master connection config, bounded by +`ADMIN_DEPENDENCY_PING_TIMEOUT_MS` for connect, query and statement, and destroys +that connection when the timeout fires instead of leaving it open. `/readyz` itself +is unchanged: same endpoint, same JSON, same 200/503. diff --git a/deploy/README.md b/deploy/README.md index 95005e09b..27f1d9de5 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -117,10 +117,16 @@ Postgres and Redis checks as `/admin/health` without requiring admin auth. When fan-out is enabled, the JSON body includes `relayBroadcast.ok` so a backend that lost Redis stream fan-out is drained by HAProxy instead of serving half of live subscribers. -Each dependency ping uses the default 3s timeout (`ADMIN_DEPENDENCY_PING_TIMEOUT_MS`). +Each dependency ping uses the default 3s timeout (`ADMIN_DEPENDENCY_PING_TIMEOUT_MS`), +which bounds the Postgres connect and query as well as the wait for the answer: a +probe that runs out of time destroys its connection instead of leaving it open. Set your load balancer check timeout above that (for example HAProxy `timeout check 5s`) so slow-but-healthy backends do not flap during probes. -Responses are cached in-process for 1s to absorb polling without hammering the DB pool. +Responses are cached in-process for 1s to absorb polling. The Postgres ping runs on +a connection it opens and closes itself rather than taking a slot from the +application pool, so a pool saturated by queries that never return still answers +readiness truthfully — the pool's `max` is small (3 by default) and an acquire can +wait up to `DB_ACQUIRE_CONNECTION_TIMEOUT` (60s). Use readiness before routing traffic to a new instance during deploys. On SIGTERM the relay sets `/readyz` to `503` with `"status":"draining"` while the HTTP listener remains up, rejects new WebSocket connections, drains diff --git a/src/database/client.ts b/src/database/client.ts index 86cbdd7ff..5d8540c9a 100644 --- a/src/database/client.ts +++ b/src/database/client.ts @@ -16,7 +16,9 @@ const poolLogger = createLogger('database-client:pool-monitor') lastUpdate[tag] = lastUpdate[tag] ?? now if (now - lastUpdate[tag] >= 60000) { lastUpdate[tag] = now - poolLogger.info(`${tag} connection pool: ${this.pool.numUsed()} used / ${this.pool.numFree()} free / ${this.pool.numPendingAcquires()} pending`) + poolLogger.info( + `${tag} connection pool: ${this.pool.numUsed()} used / ${this.pool.numFree()} free / ${this.pool.numPendingAcquires()} pending`, + ) } } @@ -51,6 +53,12 @@ const getMasterConfig = (): Knex.Config => : 60000, }) as any +/** + * The connection the master pool was built from, so a client the readiness probe owns + * dials the same server with the same credentials. + */ +export const getMasterConnectionConfig = (): Knex.Config['connection'] => getMasterConfig().connection + const getReadReplicaConfigByIndex = (index: number): Knex.Config => ({ tag: 'read-replica', diff --git a/src/utils/admin-health.ts b/src/utils/admin-health.ts index bdb87b475..801fe8dba 100644 --- a/src/utils/admin-health.ts +++ b/src/utils/admin-health.ts @@ -1,5 +1,7 @@ +import { Client, ClientConfig } from 'pg' + import { getCacheClient } from '../cache/client' -import { getMasterDbClient } from '../database/client' +import { getMasterConnectionConfig } from '../database/client' import { createLogger } from '../factories/logger-factory' import { delayMs } from './misc' @@ -66,17 +68,92 @@ const withTimeout = async (operation: Promise, timeoutMs: number): Promise ]) } -const pingDatabase = async (): Promise => { - const timeoutMs = getAdminDependencyPingTimeoutMs() +/** + * The parts of a `pg` client the readiness probe uses, so a test can stand one in. + */ +export interface ReadinessDbClient { + connect: () => Promise + query: (text: string) => Promise + end: () => Promise + connection?: { stream?: { destroy: () => void } } | null +} + +/** + * A client the probe owns, so a saturated application pool cannot answer readiness. + * + * `max` on the master pool is 3 by default: three queries that never complete hold + * every slot, and a ping that waits for one of them reports a healthy database as down. + * A client of its own always has a slot, and the connect and query timeouts bound it + * rather than leaving it queued behind an acquire that may take 60 s. + */ +const createReadinessDbClient = (timeoutMs: number): Client => { + const connection = getMasterConnectionConfig() + const config: ClientConfig = + typeof connection === 'string' ? { connectionString: connection } : (connection as ClientConfig) + + return new Client({ + ...config, + connectionTimeoutMillis: timeoutMs, + query_timeout: timeoutMs, + statement_timeout: timeoutMs, + application_name: 'nostream-readyz', + }) +} + +const destroyConnection = (client: ReadinessDbClient): void => { + client.connection?.stream?.destroy() +} + +/** + * Runs the readiness query on `client` and answers within `timeoutMs`. + * + * A timeout destroys the socket before the client is ended: a query that never returns + * would otherwise leave the connection open until the server notices, and the client + * ends a destroyed connection at once. + */ +export const pingDatabaseWith = async ( + client: ReadinessDbClient, + timeoutMs: number, +): Promise => { + let timer: NodeJS.Timeout | undefined + + const probe = (async () => { + await client.connect() + await client.query('SELECT 1') + })() + + const timedOut = new Promise((_, reject) => { + timer = setTimeout(() => { + destroyConnection(client) + reject(new Error(`dependency ping timed out after ${timeoutMs}ms`)) + }, timeoutMs) + }) try { - await withTimeout(getMasterDbClient().raw('SELECT 1'), timeoutMs) + await Promise.race([probe, timedOut]) return { ok: true } } catch { return { ok: false } + } finally { + if (timer) { + clearTimeout(timer) + } + // The loser of the race must not surface as an unhandled rejection. + probe.catch(() => undefined) + try { + await client.end() + } catch { + // The socket is already gone; there is nothing left to close. + } } } +const pingDatabase = async (): Promise => { + const timeoutMs = getAdminDependencyPingTimeoutMs() + + return pingDatabaseWith(createReadinessDbClient(timeoutMs), timeoutMs) +} + const pingRedis = async (): Promise => { const timeoutMs = getAdminDependencyPingTimeoutMs() diff --git a/test/unit/utils/admin-health.spec.ts b/test/unit/utils/admin-health.spec.ts index 992f77ae9..d4c9fa53f 100644 --- a/test/unit/utils/admin-health.spec.ts +++ b/test/unit/utils/admin-health.spec.ts @@ -1,6 +1,6 @@ import { expect } from 'chai' -import { getAdminDependencyPingTimeoutMs } from '../../../src/utils/admin-health' +import { getAdminDependencyPingTimeoutMs, ReadinessDbClient, pingDatabaseWith } from '../../../src/utils/admin-health' describe('admin-health', () => { const originalTimeout = process.env.ADMIN_DEPENDENCY_PING_TIMEOUT_MS @@ -36,4 +36,71 @@ describe('admin-health', () => { expect(getAdminDependencyPingTimeoutMs()).to.equal(3000) }) + + describe('pingDatabaseWith', () => { + const client = (overrides: Partial = {}): ReadinessDbClient => ({ + connect: async () => undefined, + query: async () => undefined, + end: async () => undefined, + ...overrides, + }) + + it('answers ok when the probe query answers', async () => { + let ended = false + const probe = client({ + end: async () => { + ended = true + }, + }) + + expect(await pingDatabaseWith(probe, 100)).to.deep.equal({ ok: true }) + expect(ended).to.equal(true) + }) + + it('answers not ok when the connection cannot be made', async () => { + const probe = client({ + connect: async () => { + throw new Error('connection refused') + }, + }) + + expect(await pingDatabaseWith(probe, 100)).to.deep.equal({ ok: false }) + }) + + it('destroys a hung probe at the timeout instead of waiting for it', async () => { + let destroyed = false + let ended = false + const probe = client({ + query: () => new Promise(() => undefined), + connection: { + stream: { + destroy: () => { + destroyed = true + }, + }, + }, + end: async () => { + ended = true + }, + }) + + const startedAt = Date.now() + const result = await pingDatabaseWith(probe, 50) + + expect(result).to.deep.equal({ ok: false }) + expect(destroyed).to.equal(true) + expect(ended).to.equal(true) + expect(Date.now() - startedAt).to.be.lessThan(1000) + }) + + it('still ends the client when ending it throws', async () => { + const probe = client({ + end: async () => { + throw new Error('already closed') + }, + }) + + expect(await pingDatabaseWith(probe, 100)).to.deep.equal({ ok: true }) + }) + }) }) From 676ed3331bcb951b587ca2f75de71dba40232faf Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Thu, 3 Dec 2026 08:46:22 -0500 Subject: [PATCH 2/3] test(readyz): pin the probe's own client and its bounded waits Greptile P2 on #1362: the fake-client tests never check the production probe, so reverting it to a pooled query would leave them green. The new test stubs pg.Client and the master pool and asserts the snapshot's database answer comes from a client built with connectionTimeoutMillis, query_timeout and statement_timeout at the ping timeout, never from getMasterDbClient(). --- test/unit/utils/admin-health.spec.ts | 86 +++++++++++++++++++++++++++- 1 file changed, 84 insertions(+), 2 deletions(-) diff --git a/test/unit/utils/admin-health.spec.ts b/test/unit/utils/admin-health.spec.ts index d4c9fa53f..f77cb6759 100644 --- a/test/unit/utils/admin-health.spec.ts +++ b/test/unit/utils/admin-health.spec.ts @@ -1,6 +1,15 @@ import { expect } from 'chai' - -import { getAdminDependencyPingTimeoutMs, ReadinessDbClient, pingDatabaseWith } from '../../../src/utils/admin-health' +import type * as PgModule from 'pg' +import sinon from 'sinon' + +import * as cacheClient from '../../../src/cache/client' +import * as databaseClient from '../../../src/database/client' +import { + collectAdminHealthSnapshot, + getAdminDependencyPingTimeoutMs, + pingDatabaseWith, + ReadinessDbClient, +} from '../../../src/utils/admin-health' describe('admin-health', () => { const originalTimeout = process.env.ADMIN_DEPENDENCY_PING_TIMEOUT_MS @@ -103,4 +112,77 @@ describe('admin-health', () => { expect(await pingDatabaseWith(probe, 100)).to.deep.equal({ ok: true }) }) }) + + describe('collectAdminHealthSnapshot database probe', () => { + const envNames = ['DB_URI', 'DB_HOST', 'DB_PORT', 'DB_USER', 'DB_PASSWORD', 'DB_NAME'] as const + const saved = new Map() + + beforeEach(() => { + for (const name of envNames) { + saved.set(name, process.env[name]) + delete process.env[name] + } + process.env.DB_HOST = 'db.example' + process.env.DB_PORT = '5432' + process.env.DB_USER = 'relay' + process.env.DB_PASSWORD = 'secret' + process.env.DB_NAME = 'nostream' + + sinon + .stub(cacheClient, 'getCacheClient') + .returns({ isOpen: true, ping: async () => 'PONG' } as ReturnType) + }) + + afterEach(() => { + sinon.restore() + for (const name of envNames) { + const value = saved.get(name) + if (value === undefined) { + delete process.env[name] + } else { + process.env[name] = value + } + } + saved.clear() + }) + + it('opens its own bounded client instead of taking a pool slot', async () => { + const constructed: unknown[] = [] + const probe = { + connect: sinon.stub().resolves(), + query: sinon.stub().resolves(), + end: sinon.stub().resolves(), + connection: {}, + } + // The namespace import is a frozen copy of the module, so the stub goes on the module + // object the source under test resolves `Client` from. + const pgModule = require('pg') as typeof PgModule + sinon.stub(pgModule, 'Client').callsFake((config: unknown) => { + constructed.push(config) + return probe as unknown as InstanceType + }) + const pooledClient = sinon.stub(databaseClient, 'getMasterDbClient') + + const snapshot = await collectAdminHealthSnapshot() + + expect(snapshot.database).to.deep.equal({ ok: true }) + expect(constructed).to.have.length(1) + // Every wait the probe can have is bounded by the ping timeout: a connect that + // hangs, a query that hangs, or a statement the server never finishes. + expect(constructed[0]).to.include({ + host: 'db.example', + port: 5432, + user: 'relay', + database: 'nostream', + connectionTimeoutMillis: 3000, + query_timeout: 3000, + statement_timeout: 3000, + application_name: 'nostream-readyz', + }) + expect(probe.query.calledWith('SELECT 1')).to.equal(true) + expect(probe.end.calledOnce).to.equal(true) + // The application pool is what made readiness lie; the probe must not take a slot from it. + expect(pooledClient.called).to.equal(false) + }) + }) }) From ea9ae36b643dc06a345276c089f2f515086e7b12 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Thu, 3 Dec 2026 08:56:53 -0500 Subject: [PATCH 3/3] fix(readyz): the probe's client must not outlive its budget CodeRabbit on #1362: - a reset socket emits 'error' on the client, and an unhandled event ends the process; the probe now installs a listener before it connects. - after a successful query the deadline was cleared before client.end(), so a silent drop could keep the probe waiting on an 'end' event that never arrives; closing now runs inside the same deadline and destroys the socket when it expires. - the snapshot fixture now saves and restores ADMIN_DEPENDENCY_PING_TIMEOUT_MS with the DB variables, so a suite that starts with 2500 does not fail the 3000 assertions. --- src/utils/admin-health.ts | 40 ++++++++++++++++++++----- test/unit/utils/admin-health.spec.ts | 44 +++++++++++++++++++++++++++- 2 files changed, 76 insertions(+), 8 deletions(-) diff --git a/src/utils/admin-health.ts b/src/utils/admin-health.ts index 801fe8dba..b6b537b2e 100644 --- a/src/utils/admin-health.ts +++ b/src/utils/admin-health.ts @@ -75,6 +75,7 @@ export interface ReadinessDbClient { connect: () => Promise query: (text: string) => Promise end: () => Promise + on?: (event: 'error', listener: (error: Error) => void) => unknown connection?: { stream?: { destroy: () => void } } | null } @@ -107,16 +108,22 @@ const destroyConnection = (client: ReadinessDbClient): void => { /** * Runs the readiness query on `client` and answers within `timeoutMs`. * - * A timeout destroys the socket before the client is ended: a query that never returns - * would otherwise leave the connection open until the server notices, and the client - * ends a destroyed connection at once. + * The client is discarded whatever happens, and nothing it does may outlive the + * deadline: a timeout destroys the socket rather than waiting for a query or a + * close that may never finish, and an `error` event gets a listener because an + * unhandled one would end the process — the query promise already reports the + * failure the probe cares about. */ export const pingDatabaseWith = async ( client: ReadinessDbClient, timeoutMs: number, ): Promise => { + const deadline = Date.now() + timeoutMs let timer: NodeJS.Timeout | undefined + // A reset socket emits `error` on the client as well as failing the query. + client.on?.('error', () => undefined) + const probe = (async () => { await client.connect() await client.query('SELECT 1') @@ -140,10 +147,29 @@ export const pingDatabaseWith = async ( } // The loser of the race must not surface as an unhandled rejection. probe.catch(() => undefined) - try { - await client.end() - } catch { - // The socket is already gone; there is nothing left to close. + await closeClient(client, Math.max(0, deadline - Date.now())) + } +} + +/** + * Ends `client` within `budgetMs`, destroying the socket if closing does not finish in + * time: a silent network drop can keep `end()` waiting on an event that never arrives. + */ +const closeClient = async (client: ReadinessDbClient, budgetMs: number): Promise => { + let timer: NodeJS.Timeout | undefined + const closing = client.end().catch(() => undefined) + const expired = new Promise((resolve) => { + timer = setTimeout(() => { + destroyConnection(client) + resolve() + }, budgetMs) + }) + + try { + await Promise.race([closing, expired]) + } finally { + if (timer) { + clearTimeout(timer) } } } diff --git a/test/unit/utils/admin-health.spec.ts b/test/unit/utils/admin-health.spec.ts index f77cb6759..eb41154b3 100644 --- a/test/unit/utils/admin-health.spec.ts +++ b/test/unit/utils/admin-health.spec.ts @@ -111,10 +111,52 @@ describe('admin-health', () => { expect(await pingDatabaseWith(probe, 100)).to.deep.equal({ ok: true }) }) + + it('listens for the error event a reset socket emits', async () => { + const listeners: string[] = [] + const probe = client({ + on: (event: 'error') => { + listeners.push(event) + }, + }) + + await pingDatabaseWith(probe, 100) + + expect(listeners).to.deep.equal(['error']) + }) + + it('does not outlive the deadline waiting for a close that never finishes', async () => { + let destroyed = false + const probe = client({ + end: () => new Promise(() => undefined), + connection: { + stream: { + destroy: () => { + destroyed = true + }, + }, + }, + }) + + const startedAt = Date.now() + const result = await pingDatabaseWith(probe, 50) + + expect(result).to.deep.equal({ ok: true }) + expect(destroyed).to.equal(true) + expect(Date.now() - startedAt).to.be.lessThan(1000) + }) }) describe('collectAdminHealthSnapshot database probe', () => { - const envNames = ['DB_URI', 'DB_HOST', 'DB_PORT', 'DB_USER', 'DB_PASSWORD', 'DB_NAME'] as const + const envNames = [ + 'ADMIN_DEPENDENCY_PING_TIMEOUT_MS', + 'DB_URI', + 'DB_HOST', + 'DB_PORT', + 'DB_USER', + 'DB_PASSWORD', + 'DB_NAME', + ] as const const saved = new Map() beforeEach(() => {