Ömer Faruk YILDIRIM
tutorials

Node.js Production Failure Lab · part 7

No Errors, No CPU, No Response: How One Database Connection Leaking on an Error Path Freezes an API

A minute after every restart the API freezes: no errors, no logs, CPU idle, requests simply never get an answer. We walk step by step through the anatomy of a connection pool, a connection that leaks on an error path, the idle in transaction session in pg_stat_activity, and the timeout that turns a silent hang into a visible error.

31 min read75 min hands-oncode(opens in a new tab)

Node.js Production Failure Lab · Part 7 · Difficulty ★★☆ · Reading time ~25 min · Lab ~45–75 min

In a postmortem published in the last days of 2024, Val Town describes how one of its servers stayed half-dead for almost seven hours. Concurrent edits to a Val drove a few database queries into a deadlock; those queries never released their connections, and because the pool had no query timeout, that server’s connection pool ran dry. Most incoming requests waited indefinitely. Because the health checks didn’t look at the database side, the server kept looking “healthy”, and the problem only ended when a user reported it and the server was shut down by hand. The team first blamed the network and only later realized that hypothesis was wrong. The postmortem’s own summary: with no timeouts, the server reached its capacity without showing any sign of backpressure (Val Town, Post-mortem: Exhausted Host Connection Pool).

In this part we’ll live through the same pattern: no errors, no CPU, no logs; requests simply never get an answer, and a restart fixes everything for about a minute. This time the culprit isn’t a deadlock but a single client.release() that a new coupon-code checkout flow forgets on its error path.

In Part 6 the API and the database were relaxed; the problem was one request firing dozens of cheap queries back to back. This time the API and the database are relaxed again, idle even. But no request can reach the database.

What you’ll learn

  • The anatomy of a connection pool: open, idle and waiting connections, and why a leaked connection never comes back
  • Reading the “no errors” symptom: the difference between 499 (the client gave up) and 5xx, and p95 = client timeout
  • The “not working, not failing, waiting” diagnosis: where the latency goes when CPU and the event loop are idle
  • Looking through PostgreSQL’s eyes: idle in transaction, wait_event_type = Lock and the blocking chain from pg_blocking_pids() in pg_stat_activity
  • Why a row lock taken with SELECT … FOR UPDATE isn’t released until the transaction ends
  • The fix: a single helper that ends the transaction with finally on every path, plus connectionTimeoutMillis on the pool
  • Why a timeout alone isn’t enough, and neither is finally alone

Prerequisites

You can read this article without running the lab. These will help:

TopicWhyResource
The node-postgres connection poolpool.connect(), release(), and why you must “always” releasenode-postgres, Pooling
Transactions and try/catch/finallyBEGIN, COMMIT, ROLLBACK, and releasing the connection in finallynode-postgres, Transactions; MDN, try…catch
Row locksWhat SELECT … FOR UPDATE blocks, and for how longPostgreSQL, Explicit Locking
Edge vs. in-service latency, the pool panelTo read the dashboardPart 1, Steps 1–2; Part 5

1. The concept: the pool is a library, a connection is a book

A PostgreSQL connection is expensive: a TCP handshake, authentication, a separate server process for every connection. That’s why Node.js applications keep connections in a pool. node-postgres’s pg.Pool opens at most 10 connections by default (Pool API) and tracks three numbers:

CounterMeaning
totalCountTotal connections in the pool (open)
idleCountConnections not lent out, sitting idle
waitingCountRequests queued while every connection is lent out

There are two ways to use it:

  • pool.query(sql): the pool lends out a connection, runs the query and takes the connection back itself. There’s no way to forget.
  • pool.connect(): you take the connection. This is what transactions need, because BEGIN, the queries and COMMIT must run on the same connection. But giving it back is your job too: client.release().

The node-postgres documentation is clear about this: if you check out a connection, you must always return it, whether or not the queries failed; if you don’t, your application leaks connections and every later connect call waits forever (Pooling).

The library analogy: a library with 10 books. Every reader takes a book, reads it, returns it. If a reader walks out the door without returning the book, it never comes back to the shelf. If ten readers do that, the shelf is empty and everyone who arrives queues at the door. How long the queue waits is set by the library’s rule: connectionTimeoutMillis. Its default is 0, meaning no timeout (Pool API).

Where is the easiest place to forget a connection? On the error path. The happy path runs a hundred times in tests, and release() is always there. A throw, on the other hand, exits the function and skips every line after it.

const client = await pool.connect();
await client.query('BEGIN');
if (!couponValid) throw badRequest('coupon is not valid'); // ← COMMIT and release() are skipped
await client.query('COMMIT');
client.release();                                           // only on the happy path

Three things leak at once in this code: the connection never goes back to the pool, the transaction stays open (the database sees it as idle in transaction), and the locks the transaction took are never released.

See for yourself: a 60-line experiment

No database needed. A small pool that mimics pg.Pool’s behavior (at most 10 connections, then a wait queue) and ~100 orders per second; one in every 10 orders uses an expired coupon:

// leak.mjs: node leak.mjs leak | finally | timeout
class Pool {
  constructor({ max, connectionTimeoutMillis = 0 }) {
    Object.assign(this, { max, connectionTimeoutMillis, inUse: 0, waiting: [] });
  }
  connect() {
    if (this.inUse < this.max) { this.inUse++; return Promise.resolve(this.#client()); }
    return new Promise((resolve, reject) => {
      const waiter = (client) => { clearTimeout(timer); resolve(client); };
      const timer = this.connectionTimeoutMillis && setTimeout(() => {
        this.waiting.splice(this.waiting.indexOf(waiter), 1);
        reject(new Error('timeout exceeded when trying to connect'));
      }, this.connectionTimeoutMillis);
      this.waiting.push(waiter); // with no timeout: waits forever
    });
  }
  #client() {
    return {
      query: () => new Promise((r) => setTimeout(r, 2)), // a 2 ms "query"
      release: () => {
        const next = this.waiting.shift();
        if (next) next(this.#client()); else this.inUse--;
      },
    };
  }
}

const mode = process.argv[2] ?? 'leak';
const pool = new Pool({ max: 10, connectionTimeoutMillis: mode === 'timeout' ? 500 : 0 });

async function placeOrder(couponValid) {
  const client = await pool.connect();
  if (mode === 'finally') {
    try {
      await client.query('BEGIN');
      if (!couponValid) throw new Error('400 coupon is not valid');
      await client.query('COMMIT');
    } finally {
      client.release(); // on every path
    }
    return;
  }
  await client.query('BEGIN');
  if (!couponValid) throw new Error('400 coupon is not valid'); // leaves with the connection
  await client.query('COMMIT');
  client.release(); // only on the happy path
}

let sent = 0, ok = 0, failed = 0;
const start = Date.now();
const load = setInterval(() => {
  sent++;
  placeOrder(sent % 10 !== 0).then(() => ok++, () => failed++); // every 10th order: expired coupon
}, 10);

const report = setInterval(() => {
  const t = ((Date.now() - start) / 1000).toFixed(1);
  console.log(`t=${t}s sent=${sent} ok=${ok} failed=${failed} inUse=${pool.inUse} waiting=${pool.waiting.length}`);
}, 500);

setTimeout(() => { clearInterval(load); clearInterval(report); }, 3100);

The three modes on my machine (Node.js 22.18):

$ node leak.mjs leak
t=0.5s sent=44 ok=40 failed=4 inUse=4 waiting=0
t=1.0s sent=89 ok=81 failed=8 inUse=8 waiting=0
t=1.5s sent=133 ok=90 failed=10 inUse=10 waiting=33
t=2.0s sent=176 ok=90 failed=10 inUse=10 waiting=76
t=2.5s sent=219 ok=90 failed=10 inUse=10 waiting=119
t=3.0s sent=263 ok=90 failed=10 inUse=10 waiting=163

$ node leak.mjs finally
t=3.0s sent=269 ok=243 failed=26 inUse=0 waiting=0

$ node leak.mjs timeout
t=1.5s sent=132 ok=90 failed=10 inUse=10 waiting=32
t=2.0s sent=175 ok=90 failed=42 inUse=10 waiting=43
t=3.0s sent=265 ok=90 failed=130 inUse=10 waiting=45

Notice three things:

  1. In leak mode, after exactly 10 invalid coupons (failed=10) the number of successful orders freezes at 90. Every later request joins the queue, and the queue grows by ~85 per second. No request gets an error; failed stays at 10. A silent freeze.
  2. In finally mode the pool is always empty (inUse is 0 or 1). Invalid coupons are still rejected (26 of them), but nobody loses anything.
  3. In timeout mode the leak carries on exactly as before: ok still stops at 90. The difference: waiters get an error after 500 ms (failed goes from 10 to 130). The outage continues, but now it’s visible: there’s an error that lands in the logs, the metrics and the alerts.

These three runs sum up the whole lesson of this article: the fix is finally; the timeout is there so the next bug doesn’t stay silent.


2. The incident: a restart heals it for a minute

🔥 [FIRING] ApiHighLatencyP95: shopflow-api p95 latency at the edge is above 500 ms (currently ~10 s)

It’s mid-October and you’re on call at ShopFlow. Since yesterday the API keeps freezing: requests get no answer, browsers spin and then give up. A restart fixes everything for about a minute, then it freezes again. The night shift has restarted it 11 times. What you know:

  • No errors: no 5xx from the API, no stack traces, no error logs.
  • No load: while frozen, the API’s CPU is near zero; so is the database’s.
  • The health check (/health) keeps responding; nothing restarts the API on its own.
  • Recent deploys:
VersionWhenChange
2.22.0yesterdayfeat(checkout): coupon codes
2.21.24 days agofix(db): wait for a connection instead of failing checkouts after 5 s when the pool is busy
2.21.02 weeks agofeat(account): itemized order history for the mobile app

A note from the marketing team: an old BACK2SCHOOL code (25% off) that expired on September 30 is circulating on TikTok again.

If you’ve set up the lab, start the incident:

git clone https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab.git
cd nodejs-production-failure-lab
./lab start 007

💡 Want to try it yourself first? Stop here, open Grafana (http://localhost:3000), and investigate on your own for 30 minutes. The results of each step below are tucked into collapsible sections; open them when you get stuck. For the lab’s built-in hints: ./lab hint 007. If you want to watch the freeze form, ./lab deploy restarts the API; look at the dashboards right after.


3. Investigation, step by step

Step 1: What’s happening at the edge?

Look at the Requests per second by status and Latency at the edge panels in the first row of the dashboard. The error rate says everything is normal; so what’s happening to the requests?

What do we see?
  • About 40 seconds after the lab starts, successful requests (green 200, yellow 201) drop fast and reach zero within a minute. Orange 499 takes their place: ~50 per second.
  • The p50, p95 and p99 of edge latency draw a dead-flat ceiling at 10 seconds.
  • After the restart (the first orange dashed line, 01:50:40), everything returns to normal for ~1 minute: ~65 req/s, p95 a few hundred milliseconds. Then the same movie starts again.

Grafana: on the left, requests per second by status; during the freeze the 200s drop to zero and are replaced by ~50 499s per second, then after the restart things recover for a minute and collapse again. On the right, edge latency; p50, p95 and p99 draw a flat ceiling at 10 seconds

On the left, the orange area is 499s: the client waited 10 seconds and gave up. 5xx (red) appears only at the moment of the restart: 502s while the API was down. On the right, all three latency percentiles are stuck at 10 seconds.

There are two clues:

  1. 499 is not a 5xx. 499 means “the client gave up waiting for a response and closed the connection” (Traefik and nginx use this code). No error happened on the server side, because the server never answered. That’s why the “error rate is normal” alert stays quiet.
  2. p95 = client timeout. A latency graph that’s a flat line at exactly 10 s tells you the real duration couldn’t be measured: requests take longer than 10 s and the client cuts them off there. The real question isn’t “why is it slow?” but “why does it never finish?”.

Lesson: “No errors” isn’t good news. A request that never gets an answer doesn’t produce an error either; look at the number of requests completed at the edge, and at the 499s.

Step 2: Is the API working, or waiting?

Could the event loop be blocked, as in Part 1? Go to the dashboard’s Node.js runtime row: CPU and event loop delay.

What is the API doing?
  • CPU during the freeze is ~0.08–0.1 cores: practically idle. Even in the healthy minute after the restart it only reaches ~0.23.
  • Event loop delay max is mostly under 50 ms, p99 ~15 ms. The event loop is free; nothing is blocking it.
  • No errors in the logs.

Grafana: on the left, API CPU at ~0.1 cores during the freeze, ~0.23 only in the minute after the restart; on the right, event loop delay max mostly under 50 ms, p99 ~15 ms

The API is neither working (CPU idle) nor blocked (event loop free). Compare with the multi-second event loop pauses in Part 1: there’s nothing like that here.

Diagnosis: the API isn’t working, it isn’t failing either; it’s waiting. In Node.js there are only a few places where a request can wait for seconds while the event loop is free: a response from an external service, a timer, a queue. In this API, the biggest queue on the request path is the one in front of the database connection pool.

Lesson: If there’s latency while CPU and the event loop are idle, the code is waiting for something. Next question: for what?

Step 3: Look at the pool

The dashboard’s Database connection pool panel draws three lines: open, idle and waiting. Next to it, Database sessions, by state: the sessions as PostgreSQL itself sees them.

What does the pool say?
  • The number of waiting requests starts rising ~1 minute after the lab starts and climbs like a dead-straight line: ~8,200 before the restart, 6,844 at 01:54 in the second freeze, ~10,700 at 01:55 (after which the process restarts; see the note below). The queue never drains; it only grows.
  • Idle connections: 0. Open connections are fixed at 10 (the pool’s limit; on the thousands scale of the waiting line it looks glued to the axis).
  • On the database side: during the freeze, 9 sessions active and 1 session idle in transaction. It resets briefly at the restart, then the same picture comes back.

Grafana: on the left, requests waiting in the pool climb linearly twice (~8,200 before the restart, then past 10,000); on the right, database sessions: during the freeze 9 active and 1 idle in transaction

The linear climb on the left shows that every incoming request joins the queue and never leaves: the queue never empties. On the right, the blue line: a single idle in transaction session, there for the whole freeze.

There’s a contradiction here: 9 sessions are active, which makes them look like they’re running in the database. But the database’s CPU is idle and the pool isn’t getting any connection back. What does an “active but doing nothing” session wait for?

The easy trap at this point: “The pool is small, let’s raise it from 10 to 30.” In the lab scenario’s postmortem, the team does exactly that, and the freeze arrives after three minutes instead of one. Pool size determines how long it takes you to enter the queue; as long as leaked connections never come back, it does nothing for getting out of it.

Lesson: If the pool panel shows “idle 0, waiting keeps rising”, the connections are either busy or lost. The database will tell you which.

Step 4: Look at the database side of the connections

Connect to PostgreSQL with ./lab psql and list the application’s sessions. pg_stat_activity shows, for each connection, its state, what it’s waiting for, when its transaction started and its last query. pg_blocking_pids(pid) tells you which sessions are blocking a given session with a lock (PostgreSQL, System Information Functions):

SELECT pid, state, wait_event_type AS wait_type, wait_event,
       date_trunc('second', now() - xact_start) AS in_xact_for,
       pg_blocking_pids(pid) AS blocked_by,
       left(regexp_replace(regexp_replace(query, '\s+', ' ', 'g'), '^SELECT .*? FROM ', 'SELECT … FROM '), 52) AS last_query
  FROM pg_stat_activity
 WHERE datname = 'shop' AND backend_type = 'client backend' AND pid <> pg_backend_pid()
 ORDER BY xact_start;
What does the database say?

./lab psql output: session 869 has been idle in transaction for 3 minutes 25 seconds and nobody blocks it; 876 waits for its transaction (transactionid); the remaining eight sessions wait on a tuple lock and the chain leads through 876 to 869; every one of them has SELECT … FROM coupons WHERE code = $1 FOR UPDATE as its last query

The yellow row is the culprit: it has been sitting in an open transaction for 3 minutes 25 seconds, doing nothing. The red row is the first victim behind it. All the rest are queued for the lock on the same coupon row.

The table reads itself:

  • pid 869: idle in transaction, ClientRead, 3 min 25 s. As far as PostgreSQL is concerned, this session is inside an open transaction, waiting for the client’s next command. That command never comes. Nobody is blocking it (blocked_by = {}).
  • pid 876: active, Lock / transactionid, blocked_by = {869}. It’s waiting for 869’s transaction to finish.
  • The remaining 8 sessions: active, Lock / tuple. They’re queued for the lock on the same row; the chain leads through 876 to 869.
  • They all have the same last query: SELECT … FROM coupons WHERE code = $1 FOR UPDATE.

10 sessions in total: the entire pool. The contradiction from Step 3 is resolved too: the 9 “active” sessions aren’t running, they’re waiting for a lock. In pg_stat_activity, state and wait_event are independent of each other; a session can be active and waiting on a lock at the same time (PostgreSQL, The Cumulative Statistics System). Look at the wait times: from 3:25 down to 2:14. The nine waiting sessions piled up over ~70 seconds; that’s the length of the “good minute” after the restart.

SELECT … FOR UPDATE locks a row, and other transactions that want to lock the same row wait until the first transaction ends; row locks are released only at the end of the transaction (COMMIT or ROLLBACK) (PostgreSQL, Explicit Locking). Since 869’s transaction will never end, the queue will never move either.

Lesson: If the application’s pool says it’s “full”, look at the other end of the connections: the database’s sessions. idle in transaction with an xact_start more than a few seconds old is the signature of an abandoned transaction.

Step 5: Find the trace of the abandoned transaction

Which request locks the coupon row and then sits there quietly? Look at the POST /api/orders traces in Jaeger. This lab samples 20% of traces; to make sure you don’t miss the one you’re looking for, you can send an order with the expired coupon yourself right after a restart (the trailing 01 in the W3C traceparent header means “sample this trace”):

./lab deploy   # restart: the pool and the lock are reset
curl -s -H 'content-type: application/json' \
     -H "traceparent: 00-$(openssl rand -hex 16)-$(openssl rand -hex 8)-01" \
     -d '{"customerId":77,"items":[{"productId":1,"quantity":1}],"couponCode":"BACK2SCHOOL"}' \
     http://localhost:8080/api/orders
# {"error":{"code":"bad_request","message":"coupon BACK2SCHOOL is not valid"}}
What does the trace show?

From the customer’s side everything is flawless: a clean 400 in a few tens of milliseconds. But look at the trace:

Jaeger: POST /api/orders 400; inside the API there is the customer SELECT, the price SELECT, BEGIN and the coupon SELECT, then the trace ends; there is no ROLLBACK span. The detail of the last span shows db.query.text = SELECT code, percent_off … (the coupon query)

The sequence: the customer and price queries, BEGIN, the coupon SELECT … FOR UPDATE (the detail at the bottom), then the 400. No COMMIT, no ROLLBACK. The request finished, but its transaction and its connection were left behind.

This trace’s start time (01:50:46.9) matches the transaction start of session 869 from Step 4: 3 min 25 s before 01:54, so 01:50:47. This request is the frozen pool’s “patient zero”. Every later BACK2SCHOOL attempt holds one more connection while it waits for the lock on the coupon row; after nine attempts the pool has no connections left.

What about requests that arrive after the pool is exhausted, a product page for example? Their trace is even stranger:

Jaeger: a GET /api/products/:id trace, 10 s in total; Traefik 499, the API span lasts 10 s but contains no database spans at all, and the request handler span is empty from start to finish

The product page request lasts 10 s and the client gives up (499). There isn’t a single query inside the API: the request is queued waiting to get a connection from the pool. Because the wait never ends, not even the pg-pool.connect span is closed and recorded. Don’t be fooled by the API’s own span saying “200”; the request was never answered.

Lesson: A span that isn’t in a trace is evidence too. If you don’t see a COMMIT or ROLLBACK after BEGIN, the code that ends the transaction never ran on that path.

Step 6: The latest code

Now you know where to look. The coupon checkout in 2.22.0:

// orders/orders.service.ts (2.22.0)
const client = await pool.connect();
await client.query('BEGIN');

let discountCents = 0;
if (input.couponCode) {
  const coupon = await lockCoupon(input.couponCode, client);                                     // SELECT … FOR UPDATE
  if (!coupon || !isRedeemable(coupon)) throw badRequest(`coupon ${input.couponCode} is not valid`); // ← leaves with the connection
  discountCents = Math.round((subtotalCents * coupon.percentOff) / 100);
  await redeemCoupon(coupon.code, client);
}
const { taxCents } = await quoteTax(/* ... */);
const orderId = await insertOrder(/* ... */, client);
await client.query('COMMIT');
client.release();                                                                                 // only on the happy path

And the pool settings from 2.21.2:

// platform/db.ts (2.21.2)
export const pool = new pg.Pool({
  connectionString: config.databaseUrl,
  max: config.dbPoolSize,
  idleTimeoutMillis: 30_000,
  // connectionTimeoutMillis: 5_000  ← removed so that "checkouts don't fail when the pool is busy"
});

The full chain:

  1. An order with BACK2SCHOOL locks the coupon row with FOR UPDATE and throws a 400 because the coupon has expired. The customer gets a clean error. The connection doesn’t go back to the pool; the transaction in PostgreSQL stays open and keeps the lock.
  2. The next BACK2SCHOOL order takes a new connection, tries to lock the same row and starts waiting. Forever: the first transaction will never end.
  3. With today’s traffic, a new BACK2SCHOOL attempt arrives every few seconds; each one holds one more connection. In our measurement the 10 connections were gone in ~70 seconds.
  4. Once the pool is empty, every request that needs the database queues in pool.connect(): product pages, order history, orders with valid coupons. Since there’s no connectionTimeoutMillis, none of them gets an error; and since there’s no error, there are no logs either.
  5. Clients give up after 10 s (499 at the edge). Because /health doesn’t touch the database, everything looks fine to the orchestrator.

A restart closes the connections, PostgreSQL rolls back the half-finished transactions and the lock goes away; until the first invalid coupon.

Once again, the trigger and the root cause are different: the root cause is a manually managed transaction that only ends on the happy path, plus a pool that waits forever. The trigger is an expired coupon circulating on TikTok. The problem isn’t the volume of traffic: it’s a handful of requests per minute. The problem is what each of them leaves behind.

The silent freeze has one more side effect. If you leave the lab frozen for long enough, the API eventually restarts on its own. In our run it happened at 01:55:23, with ~10,700 requests piled up in the queue: because every pending request’s objects stay in memory, the heap hit ~250 MB in the 512 MB container and the process crashed with JavaScript heap out of memory (a relative of the memory leak from Part 2). Docker restarted it, and a minute later it froze again. Unbounded waiting means unbounded memory.

Submitting your diagnosis: the lab’s questions and answers (./lab submit 007)
QuestionAnswer
What are most of the hanging requests waiting for?A free connection from the API’s database pool
Why don’t connections go back to the pool?A code path takes a connection and never gives it back, leaving its transaction open
Which requests start this?Orders with a coupon that isn’t valid (expired, used up or unknown)

4. Mitigation: stop the bleeding first

A proper fix needs a code change and a review. In the meantime:

  • Remove the trigger: delete the BACK2SCHOOL row, or return a 400 for this code directly at the edge. Other invalid codes (mistyped, used up) keep leaking, but far less often.
  • Then restart: the leaked connections and their locks are only freed when the process exits.
  • A safety net on the database side: idle_in_transaction_session_timeout (say, 30 s) exists so that PostgreSQL itself terminates the session of an abandoned transaction; its default is 0, meaning off (PostgreSQL, Client Connection Defaults). That releases the lock. But as long as the code never calls release(), the pool still counts that connection as checked out: on its own, this doesn’t stop the pool from draining.
  • Don’t: grow the pool (the freeze just arrives later), scale up the database (it’s idle), or go hunting through the infrastructure because “something’s wrong with the network”.

5. The fix: every path ends the transaction, every path returns the connection

The codebase already has the right helper. transaction() in platform/db.ts:

export async function transaction<T>(work: (client: pg.PoolClient) => Promise<T>): Promise<T> {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    const result = await work(client);
    await client.query('COMMIT');
    return result;
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}

node-postgres’s own transaction example follows the same pattern: ROLLBACK in catch, release() in finally (Transactions). A finally block always runs, even when the try block is exited with throw or return (MDN).

Move the coupon checkout onto this helper:

// orders/orders.service.ts
const orderId = await transaction(async (client) => {
  let discountCents = 0;
  if (input.couponCode) {
    const coupon = await lockCoupon(input.couponCode, client);
    if (!coupon || !isRedeemable(coupon)) throw badRequest(`coupon ${input.couponCode} is not valid`); // now ROLLBACK + release
    discountCents = Math.round((subtotalCents * coupon.percentOff) / 100);
    await redeemCoupon(coupon.code, client);
  }
  const { taxCents } = await quoteTax({ country: customer.country, amountCents: subtotalCents - discountCents });
  return insertOrder({ /* ... */ }, client);
});

Bring the timeout back to the pool:

// platform/db.ts
export const pool = new pg.Pool({
  connectionString: config.databaseUrl,
  max: config.dbPoolSize,
  idleTimeoutMillis: 30_000,
  // Never wait for a connection forever: a timeout turns a silent hang into an error.
  connectionTimeoutMillis: 5_000,
});

Valid coupons keep getting their discount and invalid ones keep being rejected with a 400; the lab’s functional checks verify this.

Right after the deploy, send the same BACK2SCHOOL request again. The response is the same 400, ~42 ms. But now the trace ends properly:

Jaeger: after the fix, POST /api/orders 400; after BEGIN and the coupon SELECT there is an 8.2 ms ROLLBACK span, 41 ms in total

Same request, same 400. The difference is in the bottom row: ROLLBACK. The coupon lock is released and the connection goes back to the pool.

Why both?

Only…What happens
…the timeoutThe leak and the lock continue, and the pool still drains. Instead of hanging for 10 s, requests get an error after 5 s. Visible, alertable, but still an outage. That’s exactly the demo’s timeout mode.
…finallyCorrect today. But the next bug that holds a connection (a slow query, a lock, an external call stuck inside a transaction) freezes the API silently again. The timeout makes sure you see the next incident in the logs and metrics.

6. Verification

./lab deploy
./lab verify 007

verify runs today’s traffic (~66 req/s, one in every 10 orders tries BACK2SCHOOL) for 60 seconds; clients give up after 10 s:

MetricTargetBeforeAfter
Checkout p95< 400 ms10.0 s (client timeout)130 ms
Catalog p95< 250 ms10.0 s (client timeout)26 ms
Error rate< 0.5%57.3%0%
Waiting in the pool (p90 over the run)< 201,9120
CPU0.12 cores0.22 cores
Event loop utilization16%29%
Waiting in the pool (max)1,9500

Look at the CPU in the “Before” column: 0.12 cores. The broken version uses less CPU than the fixed one, because it never answers two thirds of the requests. Low resource usage isn’t always a sign of health.

The graphs say the same thing. The last orange dashed line is the moment the fix was deployed (01:59):

Before and after the fix: on the left the 499s disappear and 200s and 201s hold steady at ~65 req/s; on the right edge latency falls from the 10 s ceiling to the floor and stays there

One minute passes after the last deploy, then two, then five: no freeze. The collapse that started a minute after each of the two previous restarts doesn’t come this time.

Before and after the fix: on the left, requests waiting in the pool climb to 8,000–10,700 three times, then stay flat at zero after the deploy; on the right, after the deploy most sessions are idle, with active and idle in transaction showing only momentary spikes

Three freezes, three sawteeth; after the fix, the waiting line sits flat at zero. On the right, most sessions are now idle (idle in the pool, ready to use). idle in transaction still pops up to 1 now and then, but that’s normal: the milliseconds between a transaction’s two queries. The difference is that it no longer lasts even a few seconds. We didn’t touch the pool size.

Before and after the fix: CPU rises from ~0.1 cores during the freeze to ~0.2 cores; event loop delay max rises a little, but p99 stays around 20 ms

CPU rises after the fix (from ~0.1 to ~0.2 cores): the API is actually doing work now. Event loop max goes up a little too, for the same reason; p99 is around 20 ms. The problem was never in the event loop.


7. Fixes that look right but aren’t

AttemptWhy it’s not enough
Growing the pool (10 → 30)Delays the freeze: it arrives after 30 leaks instead of 10. Leaked connections don’t come back. You also burn through PostgreSQL’s max_connections faster.
Restarting (via cron, or “every hour on the hour”)One minute of relief. The night shift tried it 11 times.
Only connectionTimeoutMillisTurns a silent freeze into a visible outage. A good step, but the outage continues.
Only idle_in_transaction_session_timeoutPostgreSQL closes the session and the lock is released. But the application’s pool still counts that connection as checked out; the pool drains anyway. Valuable as a safety net, incomplete as a fix.
Deleting BACK2SCHOOLA good first response. Every mistyped or used-up code triggers the same path.
Treating /health as “good enough”A health check that doesn’t touch the database never sees this incident. One of Val Town’s first action items was also adding pool health to the health check.

8. In production: alternatives and prevention

Shorten the coupon lock. The transaction’s first job is locking the coupon row. Alternatives:

  • Validate the coupon before the transaction without a lock, and if it’s invalid, never open the transaction at all; inside the transaction, lock it and check again. Invalid codes never take a lock, but finally is still mandatory.
  • Redeem it with a single conditional UPDATE, no explicit lock: UPDATE coupons SET redemptions = redemptions + 1 WHERE code = $1 AND expires_at > now() AND (max_redemptions IS NULL OR redemptions < max_redemptions) RETURNING percent_off. If no row comes back, the coupon is invalid. The lock lasts as long as one statement.

Ban manual pool.connect(). Block pool.connect() with a lint rule or a review rule everywhere except a single, well-tested helper like transaction(). If the query is a single statement, pool.query() is enough; the pool takes the connection back itself.

Timeouts everywhere. Waiting forever is never the right default:

  • connectionTimeoutMillis on the pool (say, 5 s)
  • statement_timeout and idle_in_transaction_session_timeout on the application’s database role (both default to 0, meaning off; the PostgreSQL documentation recommends setting them per role or session rather than server-wide in postgresql.conf: Client Connection Defaults)
  • Request timeouts in external service clients
ALTER ROLE shop SET idle_in_transaction_session_timeout = '30s';
ALTER ROLE shop SET statement_timeout = '10s';

Alert on the cause, not the symptom:

- alert: DbPoolStarved
  expr: max_over_time(db_pool_connections{job="api", state="waiting"}[1m]) > 20
  for: 2m
  labels:
    severity: page
- alert: IdleInTransactionTooLong
  # from a postgres-exporter query or your own exporter query:
  # SELECT max(extract(epoch FROM now() - xact_start)) FROM pg_stat_activity WHERE state = 'idle in transaction'
  expr: pg_idle_in_transaction_max_seconds > 10
  for: 1m
- alert: EdgeClientsGivingUp
  expr: sum(rate(traefik_service_requests_total{code="499"}[5m])) > 1
  for: 5m

The first rule would have caught this incident in its first minute: the waiting count is normally zero.

Make the health check honest. /health (is the process up?) and /ready (can it serve requests?) are different questions. A readiness check that borrows a connection from the pool with a short timeout and runs SELECT 1 would have taken the instance out of traffic in this incident. Careful: if every instance loses readiness at the same time, traffic has nowhere to go; the point of this check is alerting and isolation, not an automatic restart loop.

Test error paths more times than the pool size. This bug doesn’t show up in a single test: one order with an invalid coupon is a clean 400. It shows up on the eleventh attempt. An integration test:

for (let i = 0; i < 25; i++) {
  await expect(placeOrder({ ...order, couponCode: 'EXPIRED' })).rejects.toThrow(/not valid/);
}
expect(pool.totalCount - pool.idleCount).toBe(0); // no connection left checked out
expect(pool.waitingCount).toBe(0);

Code review checklist:

  • Is there a pool.connect()? If so, is release() inside a finally?
  • Does every throw and return path after BEGIN go through COMMIT or ROLLBACK?
  • Is there an external service call (tax, payment, email) inside the transaction? If so, when that call hangs, the locks and the connection hang with it.
  • Does a “wait, don’t fail” change (like 2.21.2) remove a timeout? If so, what replaces it?

Key takeaways

  • No errors, no CPU, no logs: the code is waiting for something. “For what?” is the whole investigation.
  • 499s and p95 = client timeout mean the response never came; error rate alerts don’t see this.
  • “Idle 0, waiting keeps rising” on the pool panel is the signature of a leak or an endless wait. Growing the pool only buys time.
  • Look through the database’s eyes: an idle in transaction whose age is measured in minutes, plus the pg_blocking_pids() chain in pg_stat_activity, names the culprit.
  • Resource leaks (connections, locks, file handles) hide on error paths. The code that acquires a resource must release it in finally; ideally in a single helper.
  • A timeout isn’t a fix, it’s insurance: it turns a silent hang into a visible error. Waiting forever is never the right default.
  • Once again, the trigger (a viral coupon) and the root cause (a transaction that only ends on the happy path, plus a pool with no timeout) are different.

Test yourself

1. What happens if you raise the pool from 10 to 30?

The freeze arrives later: every attempt with an invalid coupon holds one more connection, so 30 connections run out in about three times as long (three minutes instead of one in the lab scenario’s postmortem). Because leaked connections never come back, the outcome doesn’t change. On top of that, you open more connections to PostgreSQL and get closer to the max_connections limit.

2. In pg_stat_activity, 9 sessions are active, but the database’s CPU is idle. How?

state and wait_event are independent. These sessions are running a query (active), but the query is waiting for a row lock (wait_event_type = Lock, tuple or transactionid). A session waiting on a lock burns no CPU. The session holding the lock is idle in transaction: the transaction is open, and the client never sends the next command.

3. Why isn’t adding only connectionTimeoutMillis: 5000 enough, and why should you add it anyway?

The leak and the coupon lock continue; the pool still drains, and requests that need the database now get an error after 5 s. The outage continues. But now there’s an error: it lands in the logs, the 5xx rate alert fires, and the error message (“timeout exceeded when trying to connect”) points straight at the pool. The next bug that holds a connection won’t stay silent.

4. What would this incident have looked like with idle_in_transaction_session_timeout = 30s?

PostgreSQL closes the abandoned transaction’s session after 30 s, the coupon lock is released, and the orders waiting on it move on. But on the application side, the leaked client object is still counted as checked out of the pool; every request with an invalid coupon permanently takes a pool slot with it. The freeze arrives later, and this time not because of the lock but because the pool itself runs out. Valuable as a safety net, not a fix.

Further reading

Basics

  • node-postgres, Pooling: if you check out a connection, you must always return it, error or not; if you don’t, later requests wait forever.
  • node-postgres, Pool API: max, connectionTimeoutMillis (default 0 = no timeout), totalCount, idleCount, waitingCount.
  • node-postgres, Transactions: ROLLBACK in catch, release() in finally; and why you don’t use pool.query for transactions.
  • MDN, try…catch: how finally runs even on throw and return.

Deep dives

Real-world incidents


Next up: Flash sale timeouts. On Black Friday night, checkout for the three discounted products takes seconds; product pages and order history slow down too, yet neither the API’s nor the database’s CPU is busy. This time nothing leaks: locks are always released, they’re just held too long. We’ll follow row lock waits, why pg_stat_statements counts lock waiting as execution time, and short-lock patterns.

The full lab: https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab. If you’ve solved the lab, run ./lab report 007 to generate a postmortem template and compare it with your own write-up.