Node.js Production Failure Lab · part 8
Why Checkout Locks Up on Black Friday: Waiting for Payment Inside a Transaction, and Hot Rows
On Black Friday night checkout takes seconds and product pages slow down too, yet neither the API's nor the database's CPU is busy. We follow row lock waits step by step: a transaction that waits on the payment service while holding a lock, why pg_stat_statements counts lock waiting as execution time, and the fix that cuts lock time from half a second to tens of milliseconds.
Node.js Production Failure Lab · Part 8 · Difficulty ★★★ · Reading time ~25 min · Lab ~60–90 min
In an engineering post published in May 2026, Shopify describes how it redesigned inventory reservations in checkout (Shopify Engineering, We replaced Redis with MySQL for inventory reservations—and it scaled). The problem is a familiar one: hold the stock while payment is in progress (reservation), decrement it permanently once payment succeeds (claim), and do it during flash sales where everyone is trying to buy the same few products. Two of the post’s findings read like a summary of this part: in an extreme flash sale a hot product’s pool can temporarily run dry, and the real bottleneck isn’t CPU or query speed but database connections. Knowing that connections are exhausted doesn’t tell you who’s holding them; the team starts measuring connection hold time per business process. The pieces of their solution will show up in this part too: always taking locks in the same order, skipping locked rows instead of waiting (SKIP LOCKED), one lock per row.
In this part we’ll live through an incident of the same class at small scale. On Black Friday night, checkout for three discounted products takes seconds; product pages and “My orders” slow down too. Yet neither the API’s nor the database’s CPU is busy, and the payment provider is as fast as ever.
In Part 7 a transaction was abandoned on an error path, and its lock and connection never came back. This time nothing leaks: every transaction ends, every lock is released. They’re just held too long, and everyone wants the same three rows.
What you’ll learn
- Why a row lock lasts as long as the slowest thing inside the transaction, and the cost of making a network call inside a transaction
- “Hot rows”: how contention grows not with volume but with concentration on the same rows, and why queues explode at 85% utilization
- Why a database waiting on locks has an idle CPU, and why
pg_stat_statementsshows a primary key query taking 0.7 s - Using
pg_stat_activity,pg_blocking_pids()andpg_locksto find the lock chain and name the locked rows - How lock waits spread to unrelated pages through the connection pool
- The fix: payment first, then a transaction of tens of milliseconds; a conditional
UPDATE … WHERE stock >= $2, and a compensating step that voids the authorization on failure
Prerequisites
You can read this article without running the lab. These will help:
| Topic | Why | Resource |
|---|---|---|
Row locks and FOR UPDATE | What a lock blocks, and when it’s released | PostgreSQL, Explicit Locking |
Concurrent UPDATE under Read Committed | Why the fix doesn’t allow overselling | PostgreSQL, Transaction Isolation |
Connection pool, idle in transaction, pg_blocking_pids() | Reading the pool panel and pg_stat_activity | Part 7, Steps 3–4 |
| Edge vs. in-service latency | To read the dashboard | Part 1, Step 1 |
1. The concept: a lock lasts as long as the transaction’s slowest step
When you lock a row with SELECT … FOR UPDATE, other transactions that want to lock or modify that row wait until your transaction ends. Row locks are released only at the end of the transaction (COMMIT or ROLLBACK) (PostgreSQL, Explicit Locking).
The consequence is simple but often forgotten: the lock’s duration is the sum of everything you do inside the transaction after taking it. If that work is database queries, it’s milliseconds. But if there’s a network call in between (a tax service, a payment provider, email), the lock is held for as long as that call takes, i.e. hundreds of milliseconds. And during that time PostgreSQL sees your session as idle in transaction: running nothing, just waiting for the application’s next command, with the lock in hand.
time ──────────────────────────────────────────────────────────────►
order A: [BEGIN][FOR UPDATE product 1][tax 50 ms][PayFlow ~400 ms ·········][UPDATE][INSERT][COMMIT]
order B: [BEGIN][FOR UPDATE product 1 ··· waiting for A's COMMIT ·························][tax][PayFlow ···]…
order C: [BEGIN][FOR UPDATE product 1 ··· waiting for B ··················································]…On a normal day this is harmless: orders spread across 20,000 products, and two orders wanting the same row in the same half second is rare. The locks never meet. But when everyone buys the same three products, that product’s orders go through in single file: at ~0.5 s per lock, at most ~2 orders per second per product.
A rough calculation: 6 orders per second, 85% of them containing one of the three sale products. That’s ~1.7 orders per second per product, each holding the row for ~0.5 s. The row is locked ~85% of the time. This is where queueing theory intuition kicks in: as a server’s utilization approaches 100%, the average wait grows not linearly but explosively. At 50% utilization nobody notices they’re waiting; at 85% the queue is measured in seconds.
There’s a second effect too: every order waiting on a lock also holds a pool connection while it waits. If the pool has 10 connections and most of them are in the lock queue, a product page that has nothing to do with the lock queues for a connection too.
See for yourself: a 50-line experiment
No database needed. A 10-connection pool, one “row lock” per product (a mutex with a FIFO queue), 6 orders per second and 40 product page requests per second. An order takes a connection from the pool, locks the product, calls the tax (50 ms) and payment (250–550 ms) services, “writes” for 5 ms and releases:
// hotrow.mjs: node hotrow.mjs <normal|sale> <inside|outside>
const [products = 'sale', payment = 'inside'] = process.argv.slice(2);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
class Mutex { // a lock with a FIFO queue: like SELECT … FOR UPDATE
#busy = false; #queue = [];
async lock() { if (this.#busy) await new Promise((r) => this.#queue.push(r)); this.#busy = true; }
unlock() { const next = this.#queue.shift(); if (next) next(); else this.#busy = false; }
}
const pool = { free: 10, queue: [], maxWaiting: 0,
async acquire() {
if (this.free > 0) { this.free--; return; }
await new Promise((r) => { this.queue.push(r); this.maxWaiting = Math.max(this.maxWaiting, this.queue.length); });
},
release() { const next = this.queue.shift(); if (next) next(); else this.free++; },
};
const rows = new Map();
const row = (id) => rows.get(id) ?? rows.set(id, new Mutex()).get(id);
const pickProduct = () =>
products === 'sale' && Math.random() < 0.85 ? 1 + Math.floor(Math.random() * 3) : 1 + Math.floor(Math.random() * 20000);
const payflow = () => sleep(250 + Math.random() * 300); // card authorization: 250–550 ms
const taxrate = () => sleep(50);
async function checkout() {
const product = pickProduct();
if (payment === 'outside') { await taxrate(); await payflow(); } // external calls first, no lock
await pool.acquire(); // BEGIN
await row(product).lock(); // SELECT … FOR UPDATE
if (payment === 'inside') { await taxrate(); await payflow(); } // external calls while holding the lock
await sleep(5); // UPDATE stock, INSERT order
row(product).unlock(); pool.release(); // COMMIT
}
async function productPage() { await pool.acquire(); await sleep(5); pool.release(); }
const timings = { checkout: [], page: [] };
const run = (kind, fn) => { const t = performance.now(); fn().then(() => timings[kind].push(performance.now() - t)); };
function arrivals(perSecond, kind, fn, until) { // Poisson arrivals
(function next() {
if (performance.now() > until) return;
run(kind, fn);
setTimeout(next, -Math.log(1 - Math.random()) * (1000 / perSecond));
})();
}
const until = performance.now() + 45_000;
arrivals(6, 'checkout', checkout, until);
arrivals(40, 'page', productPage, until);
await sleep(47_000);
const pct = (xs, p) => { const s = [...xs].sort((a, b) => a - b); return s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))] ?? NaN; };
const fmt = (ms) => (ms >= 1000 ? `${(ms / 1000).toFixed(1)} s` : `${Math.round(ms)} ms`);
console.log(`${products}/${payment}: checkout p50 ${fmt(pct(timings.checkout, 50))} p95 ${fmt(pct(timings.checkout, 95))}` +
` | product page p50 ${fmt(pct(timings.page, 50))} p95 ${fmt(pct(timings.page, 95))}` +
` | waiting in pool (max) ${pool.maxWaiting} | orders completed ${timings.checkout.length}`);node hotrow.mjs normal inside # normal day: orders spread across 20,000 products, payment inside the lock
node hotrow.mjs sale inside # Black Friday: 85% on three products, payment inside the lock
node hotrow.mjs sale outside # Black Friday: payment first, lock held only while writingOn my machine (Node.js 22.18, two 45-second runs each):
| Scenario | Checkout p50 | Checkout p95 | Product page p95 | Waiting in pool (max) |
|---|---|---|---|---|
| Normal day, payment inside the lock | 447–456 ms | 591–596 ms | 6 ms | 0–1 |
| Black Friday, payment inside the lock | 682–983 ms | 2.2–3.0 s | 214–980 ms | 34–72 |
| Black Friday, payment outside the lock | 463 ms | 590–594 ms | 6 ms | 0 |
Notice three things:
- Same code, same volume: changing only the product distribution pushes checkout p95 from 0.6 s to 2–3 s. The code can run “without problems” for a whole week.
- The product page touches no lock at all, yet its p95 goes from 6 ms up to 1 s: orders sitting in the lock queue are holding the pool’s connections.
- Moving payment outside the lock brings checkout back to normal-day levels. Payment still takes ~400 ms; it just doesn’t make anyone else wait anymore.
2. The incident: Black Friday, twenty to one in the morning
🔥 [FIRING] CheckoutSlow: p95 of
POST /api/ordersis above 1 s (currently ~8 s)
Black Friday, 00:40. ShopFlow’s sale started at midnight; the home page features three “doorbuster” products: products 1, 2 and 3 (running shoes, a bicycle, headphones). Since then:
- Checkout takes seconds, up to ten; some customers give up before getting a response.
- Product pages and “My orders” are slow too, now and then between one and four seconds. Yet nothing changed in them.
ApiHighLatencyP95,OrderHistorySlowand thenDatabaseBusyalerts followed. But the database’s CPU is idle, and so is the API’s.- Order volume is twice a normal day, as forecast.
- The status page of PayFlow, the card payment provider, shows no incident.
- Recent deploys:
| Version | When | Change |
|---|---|---|
| 2.23.0 | 9 days ago | feat(checkout): card payment with PayFlow, authorized when the order is placed |
| feat(catalog): stock levels; checkout reserves the stock it sells, a product can’t be oversold | ||
| 2.22.1 | 5 weeks ago | fix(checkout): every checkout path ends its transaction and returns its connection (the fix from Part 7) |
2.23.0 ran without problems all week.
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 008💡 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 008. The symptoms build up with the traffic over the first two or three minutes.
3. Investigation, step by step
Step 1: Where does the time go?
Look at the Latency measured by the API (p95 by route) panel in the dashboard’s Inside the API row, then at the Latency of calls to other services (p95) panel in the Calls to other services row. How much of checkout’s time is spent in PayFlow?
What do we see?
POST /api/ordersp95 swings between 2.5 and 8.6 s; 7.2 s over the last 5 minutes.- p95 for the product page (
/api/products/:id) and order detail (/api/orders/:id) is ~2.1 s, order history (/api/customers/:id/orders) ~3 s. Categories, on the other hand, is 5 ms: the only route that doesn’t touch the database. - PayFlow call p95 in the panel is ~0.7 s, dead flat. Its mean in the same window is 405 ms. TaxRate is ~50 ms.

On the left, the blue area is checkout. Product pages and order history (the colored peaks at the bottom) rise and fall at the same moments as checkout’s waves. On the right, PayFlow (yellow) doesn’t budge: it’s not what’s slowing down.
Checkout takes 7 seconds, PayFlow 0.4. The 6.5 seconds in between aren’t spent in PayFlow. And pages that have nothing to do with checkout mimic checkout’s waves: they’re sharing something.
Lesson: The dependency you know to be slowest becomes the first suspect, but measure first: how much of checkout’s time is really spent in that call?
Step 2: Working, or waiting?
Look at the dashboard’s CPU panel and the Database query time seen by the API (p95 by query) panel. Check the database with docker stats too.
What are the API and the database doing?
- The API’s CPU is ~0.23 cores, flat. Comfortable for a 1-core container.
- The database container is at 5–19% CPU. The “DatabaseBusy” alert is firing, but the database isn’t busy.
- Query times as the API sees them: a single query,
products.lock-stock, has a p95 of 2–4 s. All the other queries rise with the same waves to around 1 s, up to 1.7 s at the peaks; in this panel their time also includes the time spent waiting for a connection from the pool.

The CPU on the left is flat and low: this isn’t a computation problem. The orange line on the right is products.lock-stock: the query that takes the stock lock, and it takes seconds.
If a primary key query (WHERE id = ANY($1)) takes seconds on an idle database, it isn’t running, it’s waiting. Just like in Part 7.
Lesson: A query that’s slow while the CPU is idle is waiting for something: a lock, the disk, the network. If the database’s “busy” alert looks at duration, it counts waiting as work too.
Step 3: The pool and the sessions
Look at the Database connection pool and Database sessions, by state panels.
What does the pool say?
- Open connections: 10 (the limit), idle close to 0, and the number of waiting requests rises in spiky waves to 40–130. It doesn’t climb linearly like in Part 7: the queue fills, drains and fills again.
- On the database side, once traffic starts there are constantly 2–5
idle in transactionand 2–10activesessions.

The waves on the left line up with the latency waves from Step 1. On the right, the blue line: idle in transaction sessions never drop to zero. In Part 7 a single session stayed that way for minutes; here there are always a few, but each one is short-lived.
Part 7’s question still applies: what are the sessions that look active doing, and why are there always idle in transaction sessions?
Lesson: If the pool says it’s “full”, ask the database who’s holding the connections. Growing a full pool doesn’t change what’s holding its connections.
Step 4: What are the sessions waiting for, and behind whom?
List the sessions in a transaction with ./lab psql. pg_blocking_pids(pid) returns the sessions blocking a session with a lock; the list includes both the lock holders (“hard block”) and those ahead in the queue for the same lock (“soft block”) (PostgreSQL, System Information Functions). Then use pg_locks to see which row the lock waiters are waiting for: the page and tuple columns of tuple-type locks give the row’s physical address (ctid) (PostgreSQL, pg_locks).
SELECT pid, state, wait_event_type AS wait_type, wait_event,
round(extract(epoch FROM now() - xact_start)::numeric, 2) AS in_xact_s,
pg_blocking_pids(pid) AS blocked_by,
left(regexp_replace(query, '\s+', ' ', 'g'), 80) AS last_query
FROM pg_stat_activity
WHERE datname = 'shop' AND backend_type = 'client backend' AND pid <> pg_backend_pid()
AND xact_start IS NOT NULL
ORDER BY xact_start;
SELECT l.pid, (SELECT id FROM products WHERE ctid = format('(%s,%s)', l.page, l.tuple)::tid) AS product_id
FROM pg_locks l
WHERE l.locktype = 'tuple' AND l.relation = 'products'::regclass;What does the database say?

The yellow rows are the lock holders: idle in transaction, blocked by nobody. The red ones are each chain’s first victim. The query at the bottom shows which rows the chains are queued on: product 3 and product 2.
In this snapshot (02:15:55) there are two chains:
- Product 3: 68 holds the lock and is
idle in transaction. 67 waits for 68’s transaction to finish (Lock / transactionid); 72 and 65 are behind it for the same row’s lock (Lock / tuple). - Product 2: 66 holds the lock; 62 waits for it, and 64 waits for 62.
- 69 is
idle in transactiontoo: its last query is the coupon redemption, and nobody is waiting for the product it locked right now.
There are two important differences from Part 7:
- The durations are short. The lock holders have been in their transactions for 0.35–1.38 s; in Part 7 it was 3 minutes 25 seconds. Here transactions aren’t abandoned, they finish. Run the same query a few seconds later: the pids change, the shape doesn’t. Always a few
idle in transactionlock holders, short queues behind them waiting on the sameFOR UPDATE, and the queues always on products 1, 2 and 3. - The lock holder isn’t doing anything in the database.
idle in transactionmeans the session is inside a transaction but not running a query at that moment (PostgreSQL, The Cumulative Statistics System). 68’s last query is theFOR UPDATEitself: it took the lock and has been waiting 1.38 seconds for the application’s next command. The lock holder is waiting for something not in the database but in the API.
That’s why the database’s CPU is idle: half the sessions are waiting for a lock, the other half are waiting for the application.
Lesson: If the session at the head of a lock chain is idle in transaction, what’s holding the lock isn’t the database but some other work the application is doing inside the transaction. Next question: what?
Step 5: Where is the database time going?
The dashboard’s Top queries by total time table, or pg_stat_statements in ./lab psql. The counters may have accumulated from earlier lab runs; for a clean picture, take two snapshots and look at the difference (or reset with SELECT pg_stat_statements_reset();).
What does pg_stat_statements say?

In 238 seconds the stock lock query “ran” for 955 seconds: 4 seconds of database time per second. The query in second place isn’t even one percent of that.
SELECT id, stock FROM products WHERE id = ANY($1::int[]) ORDER BY id FOR UPDATE: 1,405 calls, mean 680 ms. A query that reads at most three rows by primary key.- In the same minutes, the database uses 5–19% CPU.
pg_stat_statements’s total_exec_time counts the time from a statement’s start to its finish; if the statement spends most of that time waiting for a lock, that shows up as “execution time” too. Almost all of the 680 ms is lock waiting. That’s also why the dashboard’s Database time per second, by query panel shows 4–6 s per second: that isn’t “database load”, it’s a queue.
Lesson: If a cheap query’s mean in pg_stat_statements reaches seconds, don’t try to optimize the query; look at who it’s waiting for. Adding an index doesn’t shorten a lock queue.
Step 6: The trace of a checkout that got the lock
In Jaeger, select the POST /api/orders operation of the shopflow-api service, with Min Duration: 2s. Look at what a checkout that got the lock did after getting it.
What does the trace show?

The sequence tells the whole story: BEGIN, a 2.4-second FOR UPDATE (this order waited in the queue), then TaxRate (25 ms) and PayFlow (480 ms) while holding the lock, and finally the UPDATEs, the INSERTs and the COMMIT.
This one trace shows both halves of the investigation at once:
- This order is a victim: 2.4 of its 3.9 seconds went into
FOR UPDATE, i.e. waiting for the orders ahead of it to release the lock. - This order is also a culprit: after getting the lock, it called TaxRate and PayFlow inside the transaction. The lock was held for ~550 ms, from the moment
FOR UPDATEfinished untilCOMMIT; 505 ms of that was the two external calls. The order behind it waits exactly those 550 ms. Theidle in transactionsessions from Step 4 are these transactions, waiting for PayFlow’s response.
And it doesn’t even end at COMMIT: reading the order back needs another connection, which waits 485 ms in the pool.
What about the product pages? Their trace is shorter but just as clear:

The product page’s three queries total ~27 ms. The remaining 2 seconds are spent in pg-pool.connect, getting a connection from the pool.
The product page touches no lock. It just asks for a connection from a pool whose connections are with the orders in the lock queue.
Lesson: Find the transaction’s boundaries in a trace (BEGIN → COMMIT) and count everything in between. Every external call inside adds to the lock’s duration.
Step 7: Why today?
The code has been the same for 9 days, and volume is only double. Why did it run fine for a week and collapse today?
The answer
On a normal day orders spread across 20,000 products; two orders wanting the same product in the same half second almost never happens. Each order holds a lock for ~0.5 s, but nobody waits. Today ~85% of orders contain one of the three sale products (in the lab’s traffic, a “doorbuster” is added to most carts). The calculation from Section 1: ~1.7 orders per second per product × ~0.5 s = ~85% utilization. As in the demo, at 85% utilization the queues stretch to seconds.
If volume had doubled and orders were still spread across 20,000 products, nothing would have happened. Contention scales with concentration, not volume.
- Root cause: external service calls (TaxRate, PayFlow) inside the transaction while row locks are held. Lock duration = the duration of the network calls.
- Trigger: the sale products, which pile most orders onto three rows.
- Why it wasn’t caught: a week of normal traffic, and load tests that spread orders across random products.
Step 8: The latest code
Now you know where to look. The checkout in 2.23.0:
// orders/orders.service.ts (2.23.0)
const orderId = await transaction(async (client) => {
// Lock the products being bought until the order is written: two customers
// can never both get the last unit of a doorbuster.
const stock = await lockStock([...new Set(items.map((item) => item.productId))], client); // SELECT … FOR UPDATE
for (const item of items) {
if ((stock.get(item.productId) ?? 0) < item.quantity) throw conflict(`product ${item.productId} is out of stock`);
}
// … the coupon is locked and redeemed …
const { taxCents } = await quoteTax({ country: customer.country, amountCents: subtotalCents - discountCents }); // TaxRate, ~50 ms
const totalCents = subtotalCents - discountCents + taxCents;
// Charge while the stock is reserved; a declined card rolls everything back.
const authorization = await authorizePayment({ amountCents: totalCents, paymentToken: input.paymentToken, idempotencyKey: randomUUID() }); // PayFlow, 250–550 ms
await decrementStock(items, client);
return insertOrder({ /* … */ paymentId: authorization.id, items }, client);
}); // COMMIT: the locks are only released hereThe intent is good, and the comments spell it out: “two customers can’t both get the last unit” and “a declined card rolls everything back”. Both are the right goals. The problem is trying to achieve both with a single transaction’s lock: the stock row stays locked for as long as the card authorization takes. This is exactly the question from Part 7’s checklist: “Is there an external service call inside the transaction?”
Submitting your diagnosis: the lab’s questions and answers (./lab submit 008)
| Question | Answer |
|---|---|
| What are the slow checkouts waiting for inside the database? | Row locks on the products being bought |
| What is the transaction holding the locks doing in the meantime? | Waiting for the card authorization from PayFlow |
| Why does it only hurt during the sale? | Most orders contain one of three doorbusters, so they compete for the same rows |
4. Mitigation: stop the bleeding first
A proper fix needs a code change and a review. In the meantime:
-
Cut lock waits short: set
lock_timeouton the application’s database role. A statement that waits for a lock longer than this is cancelled; the default is 0, meaning off (PostgreSQL, Client Connection Defaults). Restart the API so new connections pick up the setting.ALTER ROLE shop SET lock_timeout = '2s';Orders that wait in the queue for more than 2 seconds get an error and release their connections; product pages and order history recover. The price: some sale checkouts fail. This is a trade-off, not a fix.
-
Don’t grow the pool. It moves the queue from the pool into PostgreSQL and makes it longer: more orders waiting on the same three rows. Product pages get their connections back, but each sale product still sells ~2 per second.
-
Taking the sale products off the home page would work. It’s also the one thing nobody will accept on Black Friday.
5. The fix: don’t do anything slow while holding a lock
Reverse the order: the slow work first (with no lock), then a short transaction (database statements only), and compensation if the order can’t be written.
// orders/orders.service.ts (fix)
// 1. Price it without taking any lock: the coupon is only read, a tax quote is fetched.
let discountCents = 0;
if (input.couponCode) {
const coupon = await findCoupon(input.couponCode);
if (!coupon || !isRedeemable(coupon)) throw badRequest(`coupon ${input.couponCode} is not valid`);
discountCents = Math.round((subtotalCents * coupon.percentOff) / 100);
}
const { taxCents } = await quoteTax({ country: customer.country, amountCents: subtotalCents - discountCents });
const totalCents = subtotalCents - discountCents + taxCents;
// 2. The slow part (a few hundred ms on the card network), before any row is locked.
const authorization = await authorizePayment({ amountCents: totalCents, paymentToken: input.paymentToken, idempotencyKey: randomUUID() });
let orderId: number;
try {
// 3. A short transaction: take the stock conditionally (in product id order), lock and redeem the coupon, write the order.
orderId = await transaction(async (client) => {
for (const item of [...items].sort((a, b) => a.productId - b.productId)) {
if (!(await reserveStock(item, client))) throw conflict(`product ${item.productId} is out of stock`);
}
if (input.couponCode) {
const coupon = await lockCoupon(input.couponCode, client);
if (!coupon || !isRedeemable(coupon)) throw badRequest(`coupon ${input.couponCode} is not valid`);
await redeemCoupon(coupon.code, client);
}
return insertOrder({ /* … */ paymentId: authorization.id, items }, client);
});
} catch (err) {
// 4. If nothing was sold, release the authorization on the customer's card.
await voidPayment(authorization.id).catch((voidErr: unknown) =>
logger.error({ err: voidErr, authorizationId: authorization.id }, 'could not void the card authorization'),
);
throw err;
}// orders/orders.repository.ts: the lock lasts only from this statement to COMMIT
export async function reserveStock(item: { productId: number; quantity: number }, client: pg.PoolClient): Promise<boolean> {
const rows = await query(
'products.reserve-stock',
'UPDATE products SET stock = stock - $2 WHERE id = $1 AND stock >= $2 RETURNING id',
[item.productId, item.quantity],
client,
);
return rows.length > 0; // no row returned means not enough stock → 409
}Three details matter:
Why no overselling? A single conditional UPDATE instead of “read, check, write”. When two orders for the last unit send an UPDATE to the same row, the second waits for the first one’s COMMIT (now tens of milliseconds). Under Read Committed, once the first commits, PostgreSQL re-evaluates the second one’s WHERE condition against the row’s new version (PostgreSQL, Transaction Isolation). stock >= $2 no longer holds, no row comes back, and the order gets a 409. There’s still a lock; it just lasts a few statements now instead of a network call.
Why product id order? If two multi-product carts lock rows in different orders, they can wait for each other forever (a deadlock). The PostgreSQL documentation’s advice: all applications should lock multiple objects in the same order (Explicit Locking). The original code did this with ORDER BY id; the fix sorts the cart to keep that order.
Why voidPayment? The card is now authorized before the order is written. If stock runs out in the meantime, the coupon is used up, or the database returns an error, the customer’s card is left with a hold for an order that doesn’t exist. An authorization only drops off on its own after days; according to Stripe’s documentation, typically 7 days for online card payments (Stripe, Place a hold on a payment method). Balancing an external operation that can’t be rolled back with a reverse operation is called compensation (Microsoft, Compensating Transaction pattern). The lab’s functional checks verify this separately: a rejected order must not leave an authorization on the card.
The trace of the same kind of checkout after the deploy:

Same steps, different order: TaxRate (17.5 ms) and PayFlow (399 ms) now come before BEGIN. The stock row is locked from the first UPDATE to the end of COMMIT, i.e. for ~45 ms; nearly all of that is round trips between the API and the database (~9 ms per statement). Getting a connection from the pool now takes microseconds.
Lock time dropped from ~550 ms to ~45 ms. Redo the calculation from Section 1: ~1.7 orders per second per product × 0.045 s ≈ 8% utilization. At that utilization, a queue almost never forms.
6. Verification
./lab deploy
./lab verify 008verify runs Black Friday traffic for 60 seconds: ~72 req/s, 6 orders per second, most with a sale product. Clients give up after 10 s.
| Metric | Target | Before | After |
|---|---|---|---|
| Checkout p95 | < 1 s | 5.19 s | 658 ms |
| Catalog p95 | < 250 ms | 1.33 s | 25 ms |
| Error rate | < 0.5% | 0% | 0% |
| Requests waiting for a connection (p90 over the run) | < 20 | 97.5 | 0 |
| Requests waiting for a connection (max) | 102 | 0 | |
| CPU | 0.25 cores | 0.24 cores | |
| Event loop utilization | 29% | 29% |
All the functional checks passed too: sale products can be ordered, an out-of-stock product gets a 409, a declined card gets a 402, and a rejected order leaves no authorization on the card.
Note two rows:
- The error rate is 0% in both columns. The broken version produced no errors at all; it was just slow. Waiting for a lock isn’t an error, and the pool’s 5 s timeout was rarely reached. This incident was caught by a latency alert, not an error rate alert.
- CPU and event loop utilization are the same. The API does the same work before and after the fix: the same queries, the same PayFlow calls. The only things that changed are the order of that work and how long the lock is held. The remaining ~0.65 s of checkout time is PayFlow (250–550 ms) and TaxRate, which the customer would wait for anyway; but now without making anyone else wait.
The pg_stat_statements delta for the 5 minutes after the deploy says the same thing: the FOR UPDATE query is gone from the list; the conditional UPDATE … RETURNING that replaced it averages 0.81 ms over 3,129 calls. The database container’s CPU is at 8–13%, as before.
The graphs say the same thing too. The second orange dashed line is the moment the fix was deployed (02:23:50):

On the left: after the deploy, checkout (blue) is flat at ~0.7 s and every other route is on the floor (over the last 5 minutes, product page p95 is 25 ms, order history 49 ms). On the right: PayFlow (yellow) is the same on both sides of the deploy. We didn’t touch PayFlow; we just stopped holding a lock while waiting for it.

Waiting in the pool is flat at zero, idle connections (yellow) close to 10: the pool is now almost always idle. On the right, idle in transaction is at zero; when it occasionally pops up to 1, that’s the milliseconds between a transaction’s two statements. We didn’t touch the pool size.

CPU doesn’t change at all: same work, different order. On the right, the pink products.lock-stock line ends at the deploy; its replacement, products.reserve-stock, sits on the floor with the other queries.
7. Fixes that look right but aren’t
| Attempt | Why it’s not enough |
|---|---|
| “PayFlow is slow”, opening a ticket with the provider | PayFlow is at its usual 250–550 ms. The problem isn’t the expected duration but the lock held while waiting. |
| Growing the pool (10 → 30) | More orders queue on the same three rows. Product pages partly get their connections back; checkout doesn’t improve, and the database pays for every new connection. |
| Scaling up the database | Its CPU is idle. Its sessions are waiting for locks, not for CPU or disk. |
FOR UPDATE NOWAIT / SKIP LOCKED | Errors out or skips the locked row instead of waiting. SKIP LOCKED is designed for queue-like tables and gives an inconsistent view for general-purpose work (PostgreSQL, SELECT). Here there’s a single stock row per product: there’s no other row to skip to, and most sale orders fail. (It works in Shopify’s design because they split stock into a separate row per unit.) |
| Reading stock without a lock and decrementing unconditionally | A race condition: two orders read “1 left”, and both take it. A CHECK (stock >= 0) constraint turns the oversell into a 500. A conditional UPDATE is atomic. |
Authorizing first, but without voidPayment | Solves the lock problem, but every order that hits out-of-stock or a used-up coupon leaves a hold on the customer’s card. Tickets for the support team, red on the functional check. |
Only lock_timeout | Turns waiting into errors; saves the pages, loses some of the sale checkouts. A safety net, not a fix. |
8. In production: alternatives and prevention
Other correct solutions to the same problem:
| Approach | When |
|---|---|
| Reserve and commit the stock first, then authorize the card | This also keeps locks short. This time, on a declined card (~2% of orders), the stock has to be given back in a second transaction. Choose based on which compensation is cheaper and safer for you. |
| A time-limited reservations table (reserve → pay → confirm or release) | If payment can take minutes (3-D Secure, wallets): no lock is held while the customer pays. More moving parts, worth it at scale. Shopify’s model belongs to this family. |
| Splitting a hot product’s stock across multiple rows | If a single product gets hundreds of orders per second. Once the lock is down to tens of milliseconds, it isn’t needed at this scale. |
Rule: no network calls inside a transaction. A transaction should contain only database statements. Make this a review rule or a lint rule: no fetch, callService or any other HTTP client inside a transaction() callback.
Safety nets on the database role: lock_timeout, statement_timeout and idle_in_transaction_session_timeout. All three default to 0, meaning off (Client Connection Defaults). An idle in transaction that lasts longer than a fraction of a second is a sign that something else is being done inside the transaction.
ALTER ROLE shop SET lock_timeout = '2s';
ALTER ROLE shop SET statement_timeout = '10s';
ALTER ROLE shop SET idle_in_transaction_session_timeout = '30s';Make lock waits visible. log_lock_waits = on writes a log line when a session waits for a lock longer than deadlock_timeout (default 1 s); it’s off by default (PostgreSQL, Error Reporting and Logging; Lock Management). In this incident the log would have filled up from the first minute with the pids of the waiting and blocking sessions.
Alert on the cause, not the symptom:
- alert: LongTransactions
# postgres-exporter: age of the longest open transaction (seconds)
expr: pg_stat_activity_max_tx_duration{datname="shop"} > 5
for: 1m
- alert: DbPoolWaiting
expr: quantile_over_time(0.9, db_pool_connections{job="api", state="waiting"}[5m]) > 20
for: 5m
labels:
severity: pageTrack the number of sessions waiting on locks too: sessions with wait_event_type = 'Lock' in pg_stat_activity, via your own exporter query. It’s normally close to zero.
Load test the hot path. A flash sale isn’t “an average day × 2”: it means lots of customers buying the same few products. If your load test spreads orders across random products, you’ll never see this incident. Before the sale, run a scenario that piles most orders onto a handful of products.
Code review checklist:
- Is there an external service call (payment, tax, email, queue) inside
transaction()? - Is the lock taken with
FOR UPDATEheld only for the shortest time actually needed? Would a single conditionalUPDATE … RETURNINGdo instead? - If multiple rows are locked, does every path lock them in the same order?
- If an irreversible external operation (authorization, reservation, email) happens before the transaction, is there a step that compensates for it when the transaction fails? And what happens if the compensation fails too (a background job that retries it, an alert)?
Key takeaways
- A lock lasts as long as the slowest thing inside the transaction. No network calls inside a transaction.
- Contention scales not with volume but with concentration on the same rows. Code that ran fine for a week collapses when everyone buys the same three products.
- A database waiting on locks has an idle CPU.
pg_stat_statementscounts waiting as time too: if a cheap query’s mean is in seconds, don’t ask about the query, ask who it’s waiting for. pg_blocking_pids()gives you the head of the chain,pg_locksthe row, andidle in transactiontells you the lock holder is waiting for something in the application, not in the database.- Every request in the lock queue holds a pool connection; that’s why pages unrelated to the lock slow down.
- Short-lock patterns: a conditional
UPDATE … WHERE stock >= $2 RETURNING, a fixed lock order, and compensation (void) for irreversible external operations. - Once again, the trigger (the sale products) and the root cause (an external call while holding a lock) are different. “PayFlow is slow” and “the pool is small” are the two wrong answers that look closest to the root cause.
Test yourself
1. PayFlow’s p95 is 0.7 s, but checkout’s p95 is 7 s. Why is blaming PayFlow wrong, and why does PayFlow’s duration still matter?
Most of checkout’s time isn’t spent in PayFlow but in the lock queue. But what determines the queue’s length is how long the lock holder holds the lock, and that’s mostly PayFlow’s duration. If PayFlow slowed to 1 s, each sale product could sell ~1 per second and utilization would exceed 100%: checkout would stop entirely. The problem isn’t PayFlow’s speed, it’s waiting for it while holding a lock.
2. In pg_stat_statements, SELECT id, stock FROM products WHERE id = ANY($1) … FOR UPDATE averages 680 ms. Would adding an index help?
No. The query already reads at most three rows by primary key; the read itself takes under a millisecond. Almost all of the 680 ms is spent waiting for a row lock held by another transaction. pg_stat_statements counts the time from a statement’s start to its finish, and waiting is included. The right question isn’t “why is the query slow?” but “who is it waiting for?”: wait_event_type = Lock and pg_blocking_pids() in pg_stat_activity.
3. In the fix, stock is still decremented under a row lock. Why isn’t that a problem anymore?
The lock is still there, but its duration changed: a few statements from the conditional UPDATE to COMMIT, ~45 ms in the lab (mostly network round trips; inside the database the UPDATE itself averages 0.8 ms). ~1.7 orders per second per product × 0.045 s ≈ 8% utilization; no queue forms. There’s no overselling either: a second UPDATE to the same row waits for the first one’s commit, then re-evaluates the stock >= $2 condition on the new row version.
4. Authorizing the card before the transaction creates a new problem. Which one, and how is it solved?
After the authorization, the order might not get written: stock runs out (409), the coupon is used up, the database returns an error. The customer’s card is left with a hold for an order that doesn’t exist. The solution is compensation: if the transaction fails, cancel the authorization with voidPayment. Since the void call can fail too, you also need a background job that retries it and an “authorization without an order” alert.
Further reading
Basics
- PostgreSQL, Explicit Locking: what
FOR UPDATEblocks, row locks being released at the end of the transaction, and a fixed lock order against deadlocks. - PostgreSQL, Transaction Isolation: how a concurrent
UPDATEunder Read Committed waits for the first transaction and re-evaluates itsWHEREcondition on the row’s new version; why a conditionalUPDATEdoesn’t allow overselling. - PostgreSQL, Client Connection Defaults:
lock_timeout,statement_timeout,idle_in_transaction_session_timeout.
Deep dives
- PostgreSQL, The Cumulative Statistics System: the
statevalues ofpg_stat_activityand theLockwait events (transactionid,tuple). - PostgreSQL, System Information Functions:
pg_blocking_pids(), “hard block” and “soft block”. - PostgreSQL, pg_locks: the
pageandtuplecolumns; why row lock waiters are mostly seen waiting on the lock holder’s transaction id. - PostgreSQL, SELECT: The Locking Clause:
NOWAITandSKIP LOCKED, and whySKIP LOCKEDis meant for queue-like tables, not general-purpose work. - PostgreSQL, Error Reporting and Logging:
log_lock_waits. - Microsoft, Compensating Transaction pattern: undoing completed steps with reverse operations; why compensation can fail too and must be idempotent.
- Stripe, Place a hold on a payment method: separating the authorization (hold) from the capture, how long an authorization stays valid, and how to cancel it.
Real-world incidents
- Shopify Engineering, We replaced Redis with MySQL for inventory reservations—and it scaled: stock reservations while payment is in progress, hot products in flash sales, the finding that connections are the bottleneck, and one row per unit,
SKIP LOCKEDand a fixed lock order.
Next up: Product pages are down. In the busiest hour of the week, product pages won’t load; browsers spin and then give up. There are no 5xx at the edge, the API’s own latency panel looks normal, and an optional recommendations service was added to the pages three days ago. We’ll look at timeout budgets, actually cancelling work with AbortSignal, and serving a page without a dependency (graceful degradation).
The full lab: https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab. If you’ve solved the lab, run ./lab report 008 to generate a postmortem template and compare it with your own write-up.