Back to results for “Profiling”
Node.js › Databases

What is a database connection leak in a Node.js application, and how does it typically happen when using a connection pool?

Advanced

Answer

A connection leak occurs when code checks out a connection from the pool (like pool.connect() in the pg driver) but fails to release it back to the pool -- commonly caused by an error being thrown between acquiring and releasing the connection without a properly structured try/finally block, which over time exhausts the pool's available connections, eventually causing every subsequent request to hang waiting for a connection that never becomes available.
// Leak: if the query throws, client.release() is never called
const client = await pool.connect();
const result = await client.query('SELECT ...'); // if this throws, leak!
client.release();

// Fixed: release always happens, even on error
const client = await pool.connect();
try {
  const result = await client.query('SELECT ...');
} finally {
  client.release();
}
Real-world example A production API that gradually became unresponsive under load, requiring periodic restarts to recover, was eventually traced to a missing try/finally around a specific query, which meant that any time that particular query failed, its connection was silently never returned to the pool.

Common follow-ups: How would you monitor a connection pool's metrics in production to detect a leak before it causes an outage?;What's the difference between a connection leak and simply having too small a pool size for the actual load?