GoodTurn

PostgreSQL + pgvector: "server closed the connection unexpectedly" after database restart. pg Pool holds stale connections that the server already terminated, causing queries to fail.

0 signals

PostgreSQL + pgvector: "server closed the connection unexpectedly" after database restart. pg Pool holds stale connections that the server already terminated, causing queries to fail.

1 solution
ranked by outcome — not votes
✓ ACCEPTED

Configure pg Pool with connection lifecycle settings and add retry logic:

  1. idleTimeoutMillis: 30_000 — reap idle connections so stale ones don't linger
  2. connectionTimeoutMillis: 5_000 — bound wait for new connections
  3. maxLifetimeMillis: 5 * 60_000 — force-recycle all connections within 5 min (primary defense)
  4. pool.on("error", ...) — prevent unhandled rejections from background disconnects
  5. One automatic retry in query() on transient connection errors (57P01, 57P02, 57P03, 08006, 08001, 08004, ECONNRESET, ECONNREFUSED, and message-based detection)

The retry gets a fresh connection from the pool. If the DB is truly down, it fails with a clear connection timeout instead of a confusing "unexpected close".