Skip to content

fix(db): attach an error handler to the pg pool#3172

Open
helder-mattos wants to merge 1 commit into
amruthpillai:mainfrom
helder-mattos:fix/pg-pool-error-handler
Open

fix(db): attach an error handler to the pg pool#3172
helder-mattos wants to merge 1 commit into
amruthpillai:mainfrom
helder-mattos:fix/pg-pool-error-handler

Conversation

@helder-mattos

@helder-mattos helder-mattos commented Jun 21, 2026

Copy link
Copy Markdown

What
Add an 'error' listener to the shared pg Pool in packages/db/src/client.ts.

Why
node-postgres emits an error event on the pool when an idle pooled client loses its connection. Per the node-postgres docs, if there is no listener, the error is re-emitted as an unhandled 'error' event on an EventEmitter, which crashes the Node process. The pool is currently created with no listener, so a single idle-connection drop takes down the whole server.

I hit this in a self-hosted setup backed by a serverless Postgres: the database terminated an idle connection (FATAL 57P01 admin_shutdown) and the API process exited with:

error: terminating connection due to administrator command
  severity: 'FATAL', code: '57P01', routine: 'ProcessInterrupts'
  at .../pg-protocol/src/index.ts

Fix
Log the pool error instead of letting it go unhandled. The pool then discards the dead client and opens a fresh one on the next query, so the server survives transient/idle disconnects.

pool.on("error", (error) ={
  console.error("[db] idle pool client error:", error);
});

Impact

  • No behavior change on the no error path; purely prevents a process crash from an idle-client error.
  • Improves resilience on any Postgres that recycles idle connections (serverless/managed Postgres, PgBouncer, failovers, network blips), not just one provider.

Testing

  • pnpm --filter @reactive-resume/db typecheck
  • pnpm --filter @reactive-resume/db test ✓ (34 passed)
  • pnpm exec biome check packages/db/src/client.ts

Summary by CodeRabbit

  • Bug Fixes
    • Improved database connection stability by adding robust error handling for PostgreSQL connection and pool failures.
    • Error events from both the pool and newly created connections are now captured and logged more reliably, helping prevent unexpected crashes in serverless PostgreSQL environments.

@coderabbitai

coderabbitai Bot commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: a97308f0-d886-49dd-b687-023ea6cc1569

📥 Commits

Reviewing files that changed from the base of the PR and between 1994b0e and 1244e6f.

📒 Files selected for processing (1)
  • packages/db/src/client.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/db/src/client.ts

📝 Walkthrough

Walkthrough

In packages/db/src/client.ts, getPool() now registers "error" event listeners on both the newly created pg Pool instance and on individual clients created by the pool. A shared logPgError handler logs errors from both pool and idle pooled clients before the pool reference is stored on globalThis.__pool.

Changes

Pool and Client Error Handling

Layer / File(s) Summary
Pool and client initialization with error listeners
packages/db/src/client.ts
Single-line Pool construction replaced with a multi-step setup: a shared logPgError handler is defined, attached to the pool's "error" events and to individual clients' "error" events via the pool "connect" event, then the pool is assigned to globalThis.__pool.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~2 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: adding an error handler to the PostgreSQL pool. It directly matches the primary objective of preventing unhandled pool errors.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
✨ Simplify code
  • Create PR with simplified code

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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 <noreply@anthropic.com>
@helder-mattos helder-mattos force-pushed the fix/pg-pool-error-handler branch from 1994b0e to 1244e6f Compare June 21, 2026 17:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant