Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(ingestion): survive a postgres client lost mid-transaction (#104020)

Zach Brownfa6a7befca20
diff --git a/nodejs/src/common/utils/db/metrics.ts b/nodejs/src/common/utils/db/metrics.ts
index 3d7605c85aac..80ab41a83816 100644
--- a/nodejs/src/common/utils/db/metrics.ts
+++ b/nodejs/src/common/utils/db/metrics.ts
@@ -1,4 +1,4 @@
-import { Counter, Histogram } from 'prom-client'
+import { Counter, Gauge, Histogram } from 'prom-client'
export const personUpdateVersionMismatchCounter = new Counter({
name: 'person_update_version_mismatch',
@@ -36,3 +36,22 @@ export const postgresErrorCounter = new Counter({
help: 'Count of Postgres errors by type',
labelNames: ['error_type', 'database_use'],
})
+
+export const postgresPoolAcquireDurationHistogram = new Histogram({
+ name: 'postgres_pool_acquire_duration_seconds',
+ help: 'Time a transaction waits for a pooled client, which rises when the pool is saturated',
+ labelNames: ['pool'],
+ buckets: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 30, 60],
+})
+
+export const postgresClientErrorCounter = new Counter({
+ name: 'postgres_client_errors',
+ help: 'Errors raised on a client while a transaction held it',
+ labelNames: ['pool'],
+})
+
+export const postgresOpenTransactionsGauge = new Gauge({
+ name: 'postgres_open_transactions',
+ help: 'Transactions currently holding a client',
+ labelNames: ['pool', 'tag'],
+})
diff --git a/nodejs/src/common/utils/db/postgres-transaction.test.ts b/nodejs/src/common/utils/db/postgres-transaction.test.ts
new file mode 100644
index 000000000000..1e13996c1de3
--- /dev/null
+++ b/nodejs/src/common/utils/db/postgres-transaction.test.ts
@@ -0,0 +1,79 @@
+import { EventEmitter } from 'events'
+
+import { postgresClientErrorCounter, postgresOpenTransactionsGauge } from './metrics'
+import { PostgresRouter, PostgresUse } from './postgres'
+
+async function metricValue(metric: { get: () => Promise<any> }, labels: Record<string, string>): Promise<number> {
+ const values = (await metric.get()).values as { labels: Record<string, string>; value: number }[]
+ const match = values.find((sample) => Object.entries(labels).every(([key, value]) => sample.labels[key] === value))
+ return match?.value ?? 0
+}
+
+type FakeClient = EventEmitter & { query: jest.Mock; release: jest.Mock }
+
+describe('postgres transaction client failures', () => {
+ let client: FakeClient
+ let router: PostgresRouter
+
+ beforeEach(() => {
+ client = Object.assign(new EventEmitter(), {
+ query: jest.fn().mockResolvedValue({ rows: [] }),
+ release: jest.fn(),
+ }) as FakeClient
+
+ router = new PostgresRouter({ DATABASE_URL: 'postgres://fake', POSTGRES_CONNECTION_POOL_SIZE: 1 })
+ // pg pools connect lazily, so the real ones built by the constructor never dial.
+ ;(router as any).pools = new Map([[PostgresUse.COMMON_WRITE, { connect: jest.fn().mockResolvedValue(client) }]])
+ })
+
+ it('counts a client lost mid-transaction and has the pool destroy it', async () => {
+ const lost = new Error('Connection terminated unexpectedly')
+ const errors = (): Promise<number> => metricValue(postgresClientErrorCounter, { pool: 'COMMON_WRITE' })
+ const before = await errors()
+
+ await expect(
+ router.transaction(PostgresUse.COMMON_WRITE, 'merge', () => {
+ client.emit('error', lost)
+ return Promise.reject(new Error('query failed'))
+ })
+ ).rejects.toThrow('query failed')
+
+ expect(client.release).toHaveBeenCalledWith(lost)
+ expect(await errors()).toBe(before + 1)
+ expect(client.listenerCount('error')).toBe(0)
+ })
+
+ it('keeps the original error when ROLLBACK fails, and has the pool destroy the client', async () => {
+ const rollbackFailure = new Error('Connection terminated unexpectedly')
+ client.query.mockImplementation((sql: string) =>
+ sql === 'ROLLBACK' ? Promise.reject(rollbackFailure) : Promise.resolve({ rows: [] })
+ )
+
+ await expect(
+ router.transaction(PostgresUse.COMMON_WRITE, 'merge', () =>
+ Promise.reject(new Error('fold target was deleted concurrently'))
+ )
+ ).rejects.toThrow('fold target was deleted concurrently')
+
+ expect(client.release).toHaveBeenCalledWith(rollbackFailure)
+ })
+
+ it.each([
+ ['commits', () => Promise.resolve()],
+ ['throws', () => Promise.reject(new Error('query failed'))],
+ ])('reports a transaction as open only until it %s', async (outcome, finish) => {
+ const tag = `gauge-${outcome}`
+ const open = (): Promise<number> => metricValue(postgresOpenTransactionsGauge, { tag })
+
+ let during = -1
+ await router
+ .transaction(PostgresUse.COMMON_WRITE, tag, async () => {
+ during = await open()
+ return finish()
+ })
+ .catch(() => undefined)
+
+ expect(during).toBe(1)
+ expect(await open()).toBe(0)
+ })
+})
diff --git a/nodejs/src/common/utils/db/postgres.ts b/nodejs/src/common/utils/db/postgres.ts
index 857e65cfa14f..8ea8df271bfb 100644
--- a/nodejs/src/common/utils/db/postgres.ts
+++ b/nodejs/src/common/utils/db/postgres.ts
@@ -7,7 +7,12 @@ import { withSpan } from '~/common/tracing/tracing-utils'
import { logger } from '../logger'
import { createPostgresPool } from '../utils'
import { DependencyUnavailableError } from './error'
-import { postgresErrorCounter } from './metrics'
+import {
+ postgresClientErrorCounter,
+ postgresErrorCounter,
+ postgresOpenTransactionsGauge,
+ postgresPoolAcquireDurationHistogram,
+} from './metrics'
import { timeoutGuard } from './utils'
/** Config that PostgresRouter needs to create its connection pools. */
@@ -196,25 +201,47 @@ export class PostgresRouter {
tag: string,
transaction: (client: TransactionClient) => Promise<ReturnType>
): Promise<ReturnType> {
- const wrappedTag = `${PostgresUse[usage]}:Tx<${tag}>`
+ const poolLabel = PostgresUse[usage]
+ const wrappedTag = `${poolLabel}:Tx<${tag}>`
return withSpan('postgres', 'query.postgres_transaction', { tag: wrappedTag }, async () => {
const timeout = timeoutGuard(`Postgres slow transaction warning after 30 sec!`)
+ const acquireStart = performance.now()
const client = await this.pools.get(usage)!.connect()
+ postgresPoolAcquireDurationHistogram.observe({ pool: poolLabel }, (performance.now() - acquireStart) / 1000)
+
+ // pg removes the pool's error listener from a checked-out client, so a lost
+ // connection would otherwise crash the process as an unhandled 'error' event.
+ let releaseError: Error | undefined
+ const onClientError = (error: Error): void => {
+ releaseError = error
+ postgresClientErrorCounter.inc({ pool: poolLabel })
+ logger.warn('🔌', 'Postgres client error during transaction', { tag: wrappedTag, error: String(error) })
+ }
+ client.on('error', onClientError)
+ postgresOpenTransactionsGauge.inc({ pool: poolLabel, tag })
try {
await client.query('BEGIN')
const response = await transaction(new TransactionClient(usage, client))
await client.query('COMMIT')
return response
} catch (e) {
- await client.query('ROLLBACK')
+ try {
+ await client.query('ROLLBACK')
+ } catch (rollbackError) {
+ // The connection's transaction state is unknown, so the pool must not reuse it.
+ releaseError ??= rollbackError as Error
+ logger.warn('🔌', 'Postgres ROLLBACK failed', { tag: wrappedTag, error: String(rollbackError) })
+ }
// if Postgres is down the ROLLBACK above won't work, but the transaction shouldn't be committed either
handlePostgresError(e, usage)
throw e
} finally {
- client.release()
+ postgresOpenTransactionsGauge.dec({ pool: poolLabel, tag })
+ client.removeListener('error', onClientError)
+ client.release(releaseError)
clearTimeout(timeout)
}
})