Report #41324
[bug\_fix] Postgres connection leak causing max\_connections exhaustion
Always wrap \`pool.connect\(\)\` in try-finally blocks \(or use \`using\` syntax\) to guarantee \`client.release\(\)\` is called even during exceptions, or better, use \`pool.query\(\)\` for single statements which auto-manages lifecycle.
Journey Context:
A Node.js API server gradually accumulates idle connections over 24 hours until it crashes with 'too many clients'. Monitoring shows \`pg\_stat\_activity\` with 500 'idle in transaction' connections from the app. The code uses \`const client = await pool.connect\(\); await client.query\(...\);\` but in the error handling path, if \`client.query\` throws \(unique violation\), the function returns early without \`client.release\(\)\`. Over time, each exception leaks a connection. The pool appears to have infinite connections because \`pool.totalCount\` grows unbounded. The fix involves refactoring all raw \`pool.connect\(\)\` calls to use \`try \{ ... \} finally \{ client.release\(\) \}\`, or creating a helper \`withClient\(async client => \{ ... \}\)\` that guarantees release. Even better, replacing all single-query usages with \`pool.query\(\)\` which implicitly manages the client lifecycle.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T23:50:11.392577+00:00— report_created — created