Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/readyz-own-connection.md
Original file line number Diff line number Diff line change
@@ -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.
10 changes: 8 additions & 2 deletions deploy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 9 additions & 1 deletion src/database/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
)
}
}

Expand Down Expand Up @@ -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',
Expand Down
111 changes: 107 additions & 4 deletions src/utils/admin-health.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand Down Expand Up @@ -66,17 +68,118 @@ const withTimeout = async <T>(operation: Promise<T>, timeoutMs: number): Promise
])
}

const pingDatabase = async (): Promise<AdminDependencyHealth> => {
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<unknown>
query: (text: string) => Promise<unknown>
end: () => Promise<void>
on?: (event: 'error', listener: (error: Error) => void) => unknown
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({
Comment thread
chappie-daemon marked this conversation as resolved.
Resolved
...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`.
*
* 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<AdminDependencyHealth> => {
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')
})()

const timedOut = new Promise<never>((_, 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)
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<void> => {
let timer: NodeJS.Timeout | undefined
const closing = client.end().catch(() => undefined)
const expired = new Promise<void>((resolve) => {
timer = setTimeout(() => {
destroyConnection(client)
resolve()
}, budgetMs)
})

try {
await Promise.race([closing, expired])
} finally {
if (timer) {
clearTimeout(timer)
}
}
}

const pingDatabase = async (): Promise<AdminDependencyHealth> => {
const timeoutMs = getAdminDependencyPingTimeoutMs()

return pingDatabaseWith(createReadinessDbClient(timeoutMs), timeoutMs)
}

const pingRedis = async (): Promise<AdminDependencyHealth> => {
const timeoutMs = getAdminDependencyPingTimeoutMs()

Expand Down
193 changes: 192 additions & 1 deletion test/unit/utils/admin-health.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import { expect } from 'chai'
import type * as PgModule from 'pg'
import sinon from 'sinon'

import { getAdminDependencyPingTimeoutMs } from '../../../src/utils/admin-health'
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
Expand Down Expand Up @@ -36,4 +45,186 @@ describe('admin-health', () => {

expect(getAdminDependencyPingTimeoutMs()).to.equal(3000)
})

describe('pingDatabaseWith', () => {
const client = (overrides: Partial<ReadinessDbClient> = {}): ReadinessDbClient => ({
connect: async () => undefined,
query: async () => undefined,
end: async () => undefined,
...overrides,
})
Comment thread
chappie-daemon marked this conversation as resolved.
Resolved

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 })
})

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 = [
'ADMIN_DEPENDENCY_PING_TIMEOUT_MS',
'DB_URI',
'DB_HOST',
'DB_PORT',
'DB_USER',
'DB_PASSWORD',
'DB_NAME',
] as const
const saved = new Map<string, string | undefined>()

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<typeof cacheClient.getCacheClient>)
})

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<typeof pgModule.Client>
})
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)
})
})
})
Loading