From 50885176e03326d7448a811cc68802641ce23b4e Mon Sep 17 00:00:00 2001 From: helder-mattos <30386292+helder-mattos@users.noreply.github.com> Date: Sat, 4 Jul 2026 09:28:18 +0200 Subject: [PATCH] fix(db): attach an error handler to the pg pool (#3172) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Postgres connection can drop at any time — e.g. a serverless Postgres such as Neon terminating the connection (error code 57P01). node-postgres surfaces this as an 'error' event; without a listener node re-throws it as an unhandled 'error' and crashes the process. Idle clients emit on the pool, but a client that is connecting or checked out emits on the client itself, so we listen on both the pool and each client. The pool then discards the dead client and opens a fresh one on the next query, so the server survives transient/idle disconnects. Co-authored-by: Claude Opus 4.8 --- packages/db/src/client.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index db39e0d46..607f5f7d6 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -11,7 +11,21 @@ declare global { export function getPool() { if (!globalThis.__pool) { - globalThis.__pool = new Pool({ connectionString: env.DATABASE_URL }); + const pool = new Pool({ connectionString: env.DATABASE_URL }); + const logPgError = (error: unknown) => { + console.error("[db] postgres connection error:", error); + }; + // A Postgres connection can drop at any time — e.g. a serverless Postgres such as Neon + // terminating the connection (code 57P01). `pg` surfaces this as an 'error' event, and + // without a listener node re-throws it as an unhandled 'error' that crashes the process. + // Idle clients emit on the pool; a client that is connecting or checked out emits on the + // client itself, so we must listen on both. The pool then discards the dead client and + // opens a fresh one on the next query. + pool.on("error", logPgError); + pool.on("connect", (client) => { + client.on("error", logPgError); + }); + globalThis.__pool = pool; } return globalThis.__pool; }