Ömer Faruk YILDIRIM
tutorials

Node.js Production Failure Lab · part 10

The App Said "Payment Failed" and the Card Was Charged Four Times: Retries, Idempotency Keys and a Unique Constraint

Customers get four orders, four card authorizations and four confirmation emails for a single purchase, while the app tells them the payment failed. We trace why a timed-out request keeps running on the server, the Idempotency-Key header the API ignores, and the key + unique constraint + 409/Retry-After fix that collapses retries into a single order.

35 min read90 min hands-oncode(opens in a new tab)

Node.js Production Failure Lab · Part 10 · Difficulty ★★☆ · Reading ~25 min · Lab ~60–90 min

On the afternoon of Thursday, 5 September 2019, some customers of Commonwealth Bank (CBA), one of Australia’s big banks, noticed that payments they had made from NetBank and the newly refreshed mobile app had gone out more than once (iTnews report). According to the bank, the cause was a “faulty error screen”: the screen said the payment had not gone through when in fact it had. So customers did the most natural thing in the world and tried again. The report says at least a few thousand duplicate transactions went through that afternoon; some had already reached other banks, and getting the money back meant working with the recipients’ banks one by one.

The lesson fits in one sentence: a request that looks “failed” may have completed successfully on the server. If there is a timeout, a dropped connection or a misleading error screen in between, the client cannot know the outcome. Retrying is the right reflex; but if the server cannot recognize the retry, every attempt is a new movement of money.

In this part we live through the automated version of that incident. This time it is not the customer who retries but the mobile app itself, and it does so “correctly”, with the same Idempotency-Key on every attempt. The result is still four orders for a single purchase, four authorizations on the card, four confirmation emails, and “Payment failed” on the screen.

In Part 9 the API spent 30 seconds of resources on requests nobody was waiting for any more, and we ended with “don’t retry after a timeout”. This part is the other side of that warning: sometimes you have to retry, and then the server must be able to tell a retry apart from the original request.

What you’ll learn

  • Why a request that timed out keeps running on the server and completes; why “timeout = failure” is a false assumption
  • What an idempotency key actually has to guarantee, and why it is not enough for the client merely to send one
  • Why “look up the key, insert if missing” races exactly when the first attempt is slow, and how a unique constraint settles the race
  • Making idempotency end-to-end: sending the payment provider a key derived from the client’s key
  • Answering a retry of a first attempt that is still running with 409 + Retry-After
  • Tying 499s at the edge, the payment provider’s counts and the database into one chain of evidence

Prerequisites

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

TopicWhySource
Idempotent HTTP methodsWhy POST should not be retried automaticallyRFC 9110, HTTP Semantics, sections 9.2.2 and 10.2.3 (Retry-After)
Idempotency keyThe core tool of this articleStripe, Designing robust and predictable APIs with idempotency
Making retries safeClient token, a “semantically equivalent” responseMalcolm Featonby, Making retries safe with idempotent APIs (Amazon Builders’ Library)
Edge vs. in-service measurement, 499For reading the dashboardPart 1, Step 1 · Part 9, Step 1
Unique index, ON CONFLICTLetting the database settle the racePostgreSQL, INSERT

1. Concept: a timeout is not an answer, it is the absence of one

When a client sends a request and gives up after 2 seconds, it knows exactly one thing: no answer arrived within 2 seconds. The request may never have arrived. The server may have crashed halfway through the work. Or the server may have finished the work completely, and the response got lost on the way or the client simply stopped waiting. Stripe’s idempotency post draws these three scenarios separately; from the client’s side, all three look the same.

In Node.js the third scenario is the default. When the client closes the connection, your Express handler does not stop: the awaits carry on, the database gets written, the email gets sent. (In Part 9 we saw this as wasted resources; here we will see it as a side effect.)

time ────────────────────────────────────────────────────────────────►
client:   attempt 1 ── 2 s: give up ─┐ attempt 2 ── 2 s: give up ─┐ ...
server:   [authorize 3 s ····················][write order #1]
                                     [authorize 3 s ····················][write order #2]

The server is still processing the first attempt while the client retries. If the server cannot tell that the second request is a retry, it writes a second order.

The solution is called idempotency: asking for the same operation once or ten times has the same end effect. In HTTP, GET, PUT and DELETE are idempotent by definition; POST is not. RFC 9110 says clients should not automatically retry non-idempotent requests unless they know the request is in fact idempotent. Payment APIs answer this as follows: the client generates a unique idempotency key for each operation and sends the same key on every attempt of that operation; when the server sees the key, it returns the first result instead of doing the work again.

This contract has two sides. The client sending the key is half of it; the other half is the server reading it, storing it and recognizing retries by it. With half missing, the key is just a header.

See for yourself: a 50-line experiment

Before we get into the lab, let’s compare three server behaviours with the same client. The client behaves like the mobile app in the lab: 2 s timeout, at most 4 attempts, waits of 0.5 / 1 / 2 s between attempts, the same Idempotency-Key on every attempt, and it honours Retry-After if the server sends one. The “authorization” on the server takes 3 seconds (a slow bank).

// retry.mjs: node retry.mjs <naive|lookup|key>
import http from 'node:http';
import { randomUUID } from 'node:crypto';
import { setTimeout as sleep } from 'node:timers/promises';

const MODE = process.argv[2];
const orders = [];          // the "database"
let charges = 0;            // authorizations on the card
const inFlight = new Set(); // key mode: keys currently being processed
const t0 = Date.now();
const at = () => ((Date.now() - t0) / 1000).toFixed(1).padStart(4) + ' s';

const server = http.createServer(async (req, res) => {
  const key = req.headers['idempotency-key'];
  const send = (status, body, headers = {}) =>
    res.writeHead(status, { 'Content-Type': 'application/json', ...headers }).end(JSON.stringify(body));

  if (MODE !== 'naive') {
    const existing = orders.find((o) => o.key === key);       // "look up the order by key"
    if (existing) return send(200, existing);
  }
  if (MODE === 'key') {
    // Claim the key in a single step, BEFORE any await (in a database: a unique constraint).
    if (inFlight.has(key)) return send(409, { error: 'in_progress' }, { 'Retry-After': '1' });
    inFlight.add(key);
  }
  try {
    charges++;
    console.log(`${at()}  server: authorization ${charges} started`);
    await sleep(3000);                                        // slow bank: a 3 s authorization
    const order = { id: orders.length + 1, key };
    orders.push(order);                                       // written even if the client is gone
    console.log(`${at()}  server: order #${order.id} written`);
    send(201, order);
  } finally {
    inFlight.delete(key);
  }
}).listen(3003);

// --- "App 5.2": 2 s timeout, at most 4 attempts, same key, honours Retry-After ---
const key = randomUUID();
const backoff = [0.5, 1, 2];
let result = 'failed';
for (let attempt = 1; attempt <= 4; attempt++) {
  try {
    const r = await fetch('http://localhost:3003/orders', {
      method: 'POST', headers: { 'Idempotency-Key': key }, signal: AbortSignal.timeout(2000),
    });
    const retryAfter = Number(r.headers.get('retry-after'));
    console.log(`${at()}  client: attempt ${attempt} → ${r.status}`);
    await r.text();
    if (!retryAfter) { result = `order ${r.status}`; break; }
    await sleep(Math.max(retryAfter, backoff[attempt - 1] ?? 2) * 1000);
  } catch {
    console.log(`${at()}  client: attempt ${attempt} → 2 s timeout`);
    if (attempt < 4) await sleep(backoff[attempt - 1] * 1000);
  }
}
console.log(`${at()}  client result: ${result}`);
await sleep(3500); // let leftover work finish
console.log(`RESULT [${MODE}]  orders: ${orders.length}  authorizations: ${charges}`);
server.close();
for m in naive lookup key; do node retry.mjs $m; done

On my machine (Node.js 22.18) the result is:

== naive                                       == lookup
 0.0 s  server: authorization 1 started         0.0 s  server: authorization 1 started
 2.0 s  client: attempt 1 → 2 s timeout         2.0 s  client: attempt 1 → 2 s timeout
 2.5 s  server: authorization 2 started         2.5 s  server: authorization 2 started
 3.0 s  server: order #1 written                3.0 s  server: order #1 written
 4.5 s  client: attempt 2 → 2 s timeout         4.5 s  client: attempt 2 → 2 s timeout
 5.5 s  server: order #2 written                5.5 s  server: order #2 written
 5.5 s  server: authorization 3 started         5.5 s  client: attempt 3 → 200
 7.5 s  client: attempt 3 → 2 s timeout         5.5 s  client result: order 200
 8.5 s  server: order #3 written               RESULT [lookup]  orders: 2  authorizations: 2
 9.5 s  server: authorization 4 started
11.5 s  client: attempt 4 → 2 s timeout        == key
11.5 s  client result: failed                   0.0 s  server: authorization 1 started
12.5 s  server: order #4 written                2.0 s  client: attempt 1 → 2 s timeout
RESULT [naive]  orders: 4  authorizations: 4    2.5 s  client: attempt 2 → 409
                                                3.0 s  server: order #1 written
                                                3.5 s  client: attempt 3 → 200
                                                3.5 s  client result: order 200
                                               RESULT [key]  orders: 1  authorizations: 1

Three results, three lessons:

  1. naive: the key is sent but never read. 4 orders, 4 authorizations, and after 11.5 s the client says “failed”. Every order is written after the client has given up on that attempt.
  2. lookup (“look up by key, insert if missing”): better, but not enough: 2 orders, 2 authorizations. When attempt 2 arrives, order #1 has not been written yet (the authorization is still running); the lookup comes back empty and a second authorization starts. The window between lookup and insert is as wide as the time the first attempt is slow. And retries arrive precisely while the first attempt is slow.
  3. key: the key is claimed before the work starts, in a single step. Attempt 2 arrives while the first attempt is still running and gets 409 + Retry-After: 1; attempt 3 finds the finished order. 1 order, 1 authorization, and the client sees its order at 3.5 s.

The Set in the demo is a single-process toy. A real service has several instances and a database; there, the equivalent of “claim in a single step” is a unique constraint. That is exactly what the lab’s fix will do.


2. The incident: Thursday morning, the support team is on fire

🔥 [FIRING] DuplicateCharges: PayFlow flagged possible duplicate charges in the last 10 minutes

Thursday, 10 December, 11:30. You are on call at ShopFlow. Since yesterday the support team has been flooded with complaints: customers were charged two, three, even four times for a single purchase and received as many confirmation emails. Most of them say the app told them the payment had failed. What you know:

  • Most customers are fine: a few hundred complaints against thousands of orders.
  • ShopFlow app 5.2 shipped on Monday. From the release notes: “Checkout works better on slow networks: an attempt that takes longer than 2 seconds is retried automatically with the same Idempotency-Key, as recommended by PayFlow’s integration guide, up to 4 attempts.”
  • PayFlow’s status page, since Wednesday 08:00: “Authorizations for cards issued by CrediBank are taking several seconds.”
  • There has been no notable change to the API for a while:
VersionWhenChange
2.24.22 days agoversion bumps for pg, express and the OpenTelemetry packages
2.24.15 days agoproduct pages wait at most 250 ms for Recommendations (the fix from Part 9)

If you have 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 010

💡 Want to try it yourself first? Stop here, open Grafana (http://localhost:3000), PayFlow’s dashboard (http://localhost:8090/v1/risk/duplicates) and ./lab psql, and investigate on your own for 30 minutes. The results of the steps below are in collapsed boxes; open them when you get stuck. For the lab’s own hints: ./lab hint 010.


3. Investigation, step by step

Nothing in the system is “red” in this incident: no 5xx, CPU is calm, the database is relaxed. The evidence is in numbers that don’t add up.

Step 1: Follow one duplicate end to end

Start with one concrete example from the complaints. PayFlow’s dashboard lists the cards it has flagged: GET /v1/risk/duplicates. Pick one and look at every authorization on that card: GET /v1/authorizations?paymentToken=<token>.

What does PayFlow show?

All 50 of the last 50 flagged cards are tok_credibank_…. On the card I picked there are four authorizations for the same amount ($3,610.92), spread over 10 seconds: 00:11:55.6 → 00:11:57.2 → 00:12:01.6 → 00:12:05.8 (UTC). All four are still authorized: the customer has a pending charge of $14,443 on their card.

PayFlow dashboard: four authorizations for the same amount (361092 cents) on card tok_credibank_6mq6fdrm4m, all authorized, between 00:11:55 and 00:12:05

A single CrediBank card: four authorizations for the same amount, 10.2 s between the first and the last. Four different ids: PayFlow saw them as four separate requests.

Now match them up in the database. orders.payment_id is the authorization’s id:

SELECT id, customer_id, total_cents, created_at::time(3), payment_id
  FROM orders WHERE payment_id IN (/* the four authorization ids */) ORDER BY id;

Four authorizations, four orders: the same customer (1427), the same amount, a few milliseconds after each authorization. To see the bigger picture, the query from the answer key, for the last 10 minutes:

SELECT customer_id, total_cents, count(*) AS orders,
       min(created_at)::time(0) AS first, max(created_at)::time(0) AS last
  FROM orders
 WHERE created_at > now() - interval '10 minutes'
 GROUP BY 1, 2 HAVING count(*) > 1;

./lab psql: at the top, customer 1427's four orders matching the four authorizations; at the bottom, multiple orders with the same customer and amount in the last 10 minutes, most of them 4 orders 9–11 s apart

Top: four authorizations, four orders. Bottom: most duplicates are exactly 4 orders, 9–11 s between the first and the last. The rows with 2 and 3 orders at the very top are checkouts that were still in progress when the query ran.

Summary of the same 10 minutes: ~991 checkouts, 1,213 orders. 77 checkouts (~7.8%, roughly one in twelve) have more than one order, and 72 of them have exactly four.

Lesson: Start not from the complaint but from a single concrete example, and follow it through every system (payment provider, database) by the same identifier.

Step 2: Do the sums

We’ve seen that duplicates exist; now for their scale and source. How many checkouts arrive per second, how many does the API think it answered, and how many authorizations does PayFlow grant?

Do the numbers add up?

They don’t. I put five series on the same graph in Grafana Explore:

Grafana Explore: edge POST 201 ~2.6/s and the API's own count of POST /api/orders ~2.6/s on top of each other; edge POST 499 ~1/s; PayFlow authorizations ~3.5/s; duplicates flagged by PayFlow ~0.75/s

Green (201 at the edge) and blue (POST /api/orders as counted by the API itself) sit on top of each other at ~2.6/s. But PayFlow (orange) grants ~3.5 authorizations per second. The ~1/s difference is the requests that end as 499 at the edge (yellow); red is the ~0.75/s that PayFlow counts as duplicates.

  • At the edge, POST /api/orders: ~2.6 201s per second and ~1 499. 499 is Traefik’s code for “the client closed the connection without waiting for the response” (familiar from Part 9). No 5xx.
  • The API’s own metrics see only ~2.6/s: the 499s are not there at all. The API finishes the request even though the client is gone, but it measures duration on the response’s finish event (platform/request-telemetry.ts), and for a response whose connection has been closed that event never fires.
  • PayFlow grants ~3.5 successful authorizations per second: ~1/s more than the API thinks it “finished”.

In other words, the requests clients gave up on don’t go to waste. Each one turns into an authorization and an order.

Lesson: A 499 at the edge does not mean “the work wasn’t done” on the server. On the contrary, it often means the work was done but the response reached no one.

Step 3: Why only some customers?

All the duplicates are on CrediBank cards. From the API’s point of view, how long do checkouts take, and how long do PayFlow calls take?

Latency panels

Grafana: on the left, per-route p95 as measured by the API, /api/orders flat at ~740 ms; on the right, p95 of calls to other services, payments at 4–4.7 s, the others at the floor

On the left, checkout p95 as measured by the API: ~740 ms. On the right, p95 of that same API’s PayFlow calls: 4–4.7 s. A request cannot be shorter than a call made inside it: the API’s panel doesn’t see the slow checkouts.

The two panels seem to contradict each other. The explanation is in Step 2: the checkouts the client gave up on never enter the API’s latency histogram, because their responses can’t be written. The panel only shows checkouts that finished within 2 s, i.e. cards from fast banks.

The distribution of PayFlow calls has two humps: most cards at ~0.25–0.55 s, CrediBank cards (~8%) at 2.5–4 s. The p95 falls inside that slow group. The app waits 2 s: cards from fast banks always make it, CrediBank’s never do.

Lesson: When you see “only some customers”, look for the dimension that separates them from everyone else: bank, country, app version, basket size. Here, the separator is where the bank’s authorization time falls relative to the client’s timeout.

Step 4: The trace of a single slow checkout

In Jaeger: shopflow-api, operation POST /api/orders, Min Duration 2s.

What does the trace show?

Jaeger: traefik POST span ends with 499 at 2.0 s; the API's POST /api/orders span also closes at 2.0 s, but the POST 201 span to PayFlow lasts 2.9 s; followed by UPDATE, INSERT, COMMIT and 202 from MailWave

The proxy gives up at 2.0 s with a 499 (red exclamation mark). The API’s PayFlow call (POST 201), however, takes 2.9 s, followed by the stock UPDATEs, the order INSERTs, COMMIT and the confirmation email (POST 202, MailWave). All of it after nobody was left waiting for the response.

The whole trace is 3.1 s. The customer saw “timed out” at 2.0 s; the order was written at 2.97 s and the email went out at 3.03 s. By then the app is about to send attempt 2.

Step 5: Finally, the code

Now you know where to look. If the app sends the same key, what does the API do with it?

// orders/orders.routes.ts
ordersRouter.post('/', async (req, res) => {
  const order = await placeOrder(parseNewOrder(req.body));   // Idempotency-Key is never read
  res.status(201).location(`/api/orders/${order.id}`).json(order);
});

// orders/orders.service.ts
const authorization = await authorizePayment({
  amountCents: totalCents,
  paymentToken: input.paymentToken,
  idempotencyKey: randomUUID(),                               // a new key on every request
});

Two gaps:

  1. The API never reads the Idempotency-Key header. It has no way of recognizing a retry on its own side.
  2. It gives PayFlow a new random key on every request. PayFlow supports idempotency; but granting four authorizations for four requests with four different keys is the correct behaviour from its point of view. The API switches off the protection the payment provider offers with its own hands.

The full timeline, for one CrediBank card:

 0.0 s  attempt 1 → API → PayFlow, key k1 (CrediBank: ~3 s)
 2.0 s  app gives up on attempt 1 (499 at the edge). The API carries on.
 2.5 s  attempt 2 → API → PayFlow, key k2: a second authorization
~3 s    attempt 1's authorization → order #1, email #1
 4.5 s  app gives up on attempt 2
 5.5 s  attempt 3 → PayFlow, key k3  ...  order #2, email #2
 7.5 s  app gives up on attempt 3
 9.5 s  attempt 4 → PayFlow, key k4  ...  order #3, email #3
11.5 s  app gives up on attempt 4: "Payment failed, please try again"
~13 s   order #4, email #4

And what does the customer do? Since the app said “failed”, most of them try once more by hand.

The lab’s diagnosis questions and answers (./lab submit 010)
QuestionAnswer
Where are the extra orders coming from?The app retries checkouts that take too long, and every attempt places an order
Why does a retried checkout become a new order and a new charge?The API ignores the Idempotency-Key the app sends, and gives PayFlow a new key for every attempt
Why does it only happen to some customers?Their bank takes longer to authorize the card than the app waits

Red herrings:

  • “PayFlow is charging twice.” PayFlow received four requests with four different keys; four authorizations is the correct answer.
  • “The app is buggy.” The app does what the integration guide says: retry with the same key. Honouring the key is the server’s job.
  • “The problem is CrediBank.” Being slow is not being wrong. A dependency will always get slow at some point; the API has to stay correct when it does.
  • “Customers are tapping the button twice.” Then the duplicates would show up on every bank’s cards, not just CrediBank’s; and two taps wouldn’t be spread over 10 seconds.

Trigger and root cause: The trigger is app 5.2’s automatic retries coinciding with CrediBank’s slowdown. The root cause is that order creation is not idempotent. Why didn’t it show up in testing? Because a retry only does damage when the first attempt times out after the server has finished the work; while PayFlow answered in half a second, that never happened.


4. Mitigation

  • Ask the mobile team to turn off retries or raise the timeout (within minutes, if the app has remote config). This stops new duplicates; it doesn’t make the API safe.
  • Cleanup: find the duplicates (same customer, same amount, within a minute), keep the first order of each group, cancel the rest and void their authorizations. Tell customers before their bank statement does.
  • Don’t: try to “speed up” the API. The bank’s 2.5–4 seconds aren’t yours to fix; the next slow dependency will bring the duplicates back.

5. The fix: one checkout, one order, one authorization

Goal: however many times the app attempts a checkout, there is one order and one authorization, and every checkout eventually gets an answer. We don’t touch the app, PayFlow or CrediBank.

1. Read and validate the key. Without a key, behaviour is unchanged.

// orders/orders.routes.ts
ordersRouter.post('/', async (req, res) => {
  const order = await placeOrder(parseNewOrder(req.body), idempotencyKey(req));
  res.status(201).location(`/api/orders/${order.id}`).json(order);
});

function idempotencyKey(req: express.Request): string | undefined {
  const key = req.get('Idempotency-Key');
  if (key === undefined) return undefined;
  if (!/^[\w-]{8,128}$/.test(key)) throw badRequest('Idempotency-Key must be 8 to 128 letters, digits, "-" or "_"');
  return key;
}

2. The order remembers its key, and there can be only one order per customer + key. The schema change ships with the code, as a migration (the API applies it on startup):

-- migrations/0006_orders_idempotency_key.sql
ALTER TABLE orders ADD COLUMN IF NOT EXISTS idempotency_key text;

-- migrations/0007_orders_idempotency_key_index.sql
-- no-transaction
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS orders_customer_idempotency_key_idx
    ON orders (customer_id, idempotency_key) WHERE idempotency_key IS NOT NULL;

CONCURRENTLY builds the index without locking the table against writes while orders keep coming in (it can’t run inside a transaction, hence no-transaction). The partial index (WHERE idempotency_key IS NOT NULL) leaves old orders without a key out of scope. The key is per customer: two customers randomly generating the same key won’t hand one customer’s order to the other.

3. An attempt that already has an order gets that order back; and PayFlow recognizes the retry too.

// orders/orders.service.ts
export async function placeOrder(input: NewOrder, idempotencyKey?: string) {
  if (idempotencyKey) {
    const placed = await findOrderIdByIdempotencyKey(input.customerId, idempotencyKey);
    if (placed !== undefined) return existingOrder(placed);       // same body, no new email
  }
  // ... price, coupon, tax ...
  const authorization = await authorizePayment({
    amountCents: totalCents,
    paymentToken: input.paymentToken,
    // Every attempt of the same checkout uses the same key at PayFlow:
    // PayFlow returns the first authorization for a retry instead of a second one.
    idempotencyKey: idempotencyKey ? `order-${input.customerId}-${idempotencyKey}` : randomUUID(),
  });

  try {
    orderId = await transaction(async (client) => {
      // ... stock, coupon ...
      return insertOrder({ /* ... */ paymentId: authorization.id, idempotencyKey: idempotencyKey ?? null, items }, client);
    });
  } catch (err) {
    // Another attempt of the same checkout wrote its order first (the unique index stopped us):
    // return its order. The authorization is shared, don't void it.
    if (idempotencyKey) {
      const placed = await findOrderIdByIdempotencyKey(input.customerId, idempotencyKey);
      if (placed !== undefined) return existingOrder(placed);
    }
    await voidPayment(authorization.id).catch(/* log */);
    throw err;
  }
  // ...
}

The key sent to PayFlow is prefixed with the customer’s id: the same key from two different customers won’t collide at PayFlow.

4. An attempt that arrives while the first is still at PayFlow. PayFlow doesn’t wait when a request with the same key is still in flight; it returns 409 (like most payment APIs). The API passes this on to the customer as “hold on, still processing”:

// checkout/payments.ts
if (response.status === 409) throw stillInProgress('this checkout is still being processed');

// shared/http-errors.ts
export const stillInProgress = (message: string) =>
  new HttpError(409, 'in_progress', message, { 'Retry-After': '1' });

HttpError is extended to take optional headers; the error handler adds them to the response. Retry-After is critical: when the app sees it, it waits a moment and tries again. A 409 without the header, on the other hand, it treats as a definitive rejection and tells the customer “failed” — right while the order is being written.

A CrediBank checkout now looks like this: attempt 1 times out (but keeps running), attempt 2 gets 409 + Retry-After, attempt 3 finds the finished order. One order, one authorization, one email; the customer sees the order 3.5–5.5 s after tapping “Pay”. The same as the demo’s key mode, but this time robust across multiple instances.

Why three layers at once?

LayerWhat it catches
Look up by key firstRetries that arrive after the first attempt has finished (the most common case)
Derived key to PayFlowRetries that arrive while the first attempt is still running (409), and a second authorization on the card
Unique indexThe rare case where two attempts race between PayFlow and the database; however careful the application code, “look up, insert if missing” misses this race

6. Verification

./lab deploy
./lab verify 010

verify runs 60 seconds of normal Thursday traffic: ~66 requests/s, of which 3 per second are checkouts from the app, with about one card in twelve from CrediBank. Before each measurement it restores the database to its original state; that’s why the schema change has to ship as a migration rather than being applied by hand from psql.

MeasurementTargetBeforeAfter
Duplicate orders (SQL: same customer, same amount, within a minute)= 0310
Authorizations PayFlow counted as duplicates= 0290
Checkouts the app gave up on after all attempts< 1%5.99%0%
CPU0.23 cores0.26 cores
Event loop utilization25%27%
Event loop delay (max)124 ms169 ms
Waiting in pool (max)00

All the functional checks passed as well; two of them matter for this incident: two checkouts with different Idempotency-Keys are two orders (catches content-based deduplication) and a rejected order leaves no authorization on the card.

Note three things:

  • The abandoned-checkout rate equals CrediBank’s share. Before, all four attempts of every CrediBank checkout timed out: the app told all of them “failed”, and every one of them had four orders. In this run the rate is 5.99%; ~8% of cards are from CrediBank, and over a 60-second measurement that share varies from run to run (the lab’s own solution notes show 10.2%). After: 0%. The same customers now see their orders.
  • CPU, event loop, pool: unchanged. The API didn’t get faster, and neither did CrediBank. A CrediBank checkout still times out on its first attempt; the fix didn’t change the slowness, it changed the consequence of the slowness.
  • The problem in the Before column doesn’t show up on any “technical” panel. No 5xx, no latency alert, resources are relaxed. The only things that show the incident are business numbers: orders per checkout, authorizations per order.

The graphs say the same thing. The orange dashed line is when the fix was deployed (around 03:15:55):

Grafana Explore, before and after the fix: after 03:16, PayFlow authorizations (orange) overlap with 201s at the edge (green); the duplicate flags (red) drop to zero; 499s fall to ~0.25/s and 409s appear next to them at the same rate

Deploy at 03:15:55. Before: PayFlow’s authorizations (orange, ~3.5/s) sit clearly above the 201s at the edge (green, ~2.6/s). After: the two lines overlap at ~3/s; every authorization corresponds to one order and one response. Duplicate flags (red) hit zero within a minute. The 499s (yellow) don’t vanish entirely and stay at ~0.25/s: the first attempt of CrediBank checkouts still times out at 2 s. Right next to them, at the same rate, are the 409s (blue): second attempts getting the “still processing” answer.

Before and after the fix: on the left, checkout p95 as measured by the API at ~740 ms, the same on both sides of the deploy; on the right, PayFlow call p95 flat at 4–4.7 s before the deploy, then swinging between 0.4 s and 3.5–4 s

Nothing changes on the left: the API didn’t get faster, and neither did CrediBank. On the right, the p95 of PayFlow calls goes from a flat line at 4–4.7 s to a line jumping between 0.4 s and ~4 s. Why? Before, every CrediBank checkout made four slow calls to PayFlow; slow calls were about a quarter of the total and the p95 always fell inside them. Now it makes one slow call (retries either get the 409 in milliseconds or never reach PayFlow at all); the share of slow calls drops to ~8% and the p95 sits right on the boundary.

Jaeger: a second attempt after the fix, 47.8 ms in total; the order lookup by key returns empty in 8.4 ms, customer and price queries, the tax call, then PayFlow 409 in 1.1 ms; the API responds with 409

A second attempt arriving while the first is still at PayFlow: the order lookup by key is empty (8.4 ms), PayFlow recognizes the same key and returns 409 in 1.1 ms, and the API answers the customer with 409 + Retry-After: 1. 47.8 ms in total; no second authorization.

Jaeger: the next attempt after the fix, 28.5 ms in total, API returns 201; only three SELECT queries, no calls to PayFlow or MailWave

The next attempt: the lookup by key finds the order, the API reads the order and its items and returns 201. Only three SELECTs; no authorization at PayFlow, no email from MailWave. 28.5 ms.

./lab psql, ~6 minutes after the deploy: multiple orders with the same customer and amount in the last 5 minutes: 0 rows; 884 of 884 orders carry a key and there are 884 distinct customer + key pairs

~6 minutes after the deploy, last 5 minutes: no repeated orders with the same customer and amount. All 884 orders carry a key and there are 884 distinct (customer, key) pairs: every checkout is a single order.


7. Fixes that look right but aren’t

AttemptWhy it falls short
Look up the key, insert if missing; no unique indexTwo attempts both find nothing, both insert. In the demo: 2 orders instead of 4. Attempts race precisely while the first attempt is slow.
Deduplicating by content (same customer, same amount, within a minute)A customer who deliberately buys the same thing twice gets one order. The lab’s functional check catches this: two purchases with different keys must be two orders.
Deduplicating orders but still sending PayFlow a random keyEvery retry puts a new authorization on the card. Even voiding it later leaves the customer with a pending charge for a while; PayFlow flags it too.
409 without Retry-AfterThe app treats it as a definitive rejection and tells the customer “failed” while the order is being written. The customer retries by hand: new key, new order.
Making the API faster, raising the app’s timeout from 2 s to 5 sWorks tonight; the next slowdown will exceed 5 s. Right as a mitigation, wrong as a fix.
Cancelling the work when the client goes away (as in Part 9)A half-cancelled payment is worse: the authorization may be taken and the order never written. Work with side effects, like moving money, is made safe by idempotency, not by cancellation.

8. In production: alternatives and prevention

What you can build on top of this fix:

ApproachAssessment
A general idempotency_keys table: key, request fingerprint, status (processing/done), stored response, expiryThe payment APIs’ way. Works for every POST, catches the same key being reused with a different body, and replays the first response exactly. Brandur Leach’s post describes it in Postgres with “recovery points”. More code than tonight’s fix.
422 if a key is reused with a different bodyA real API should reject this; otherwise it may return the order for a different basket. The IETF Idempotency-Key draft also recommends 422.
Making the second attempt wait for the first instead of 409Nicer for the client, but it holds a request (and maybe a connection) open, and needs a lock or polling on the key.
Checking the status of a replayed authorizationIf the first attempt was rejected after authorization (out of stock), PayFlow will replay an authorization that has since been voided. Production code should check the status before using it.
An expiry for keysKeys should live as long as clients retry; a day is more than enough. Stripe also says it may delete keys older than 24 hours.

The Idempotency-Key header is an IETF draft today (draft-ietf-httpapi-idempotency-key-header). The draft’s error recommendations line up with this article’s fix: 409 Conflict for the same key as a request still in flight, 422 for a key reused with a different body, 400 if the key is required and missing.

Alert on the duplicate, not the symptom. In this incident the signal was there from the first minute: PayFlow’s DuplicateCharges flags were going to a finance mailbox that the on-call engineer never read.

- alert: DuplicateCardAuthorizations
  expr: sum(increase(payflow_duplicate_authorizations_total[10m])) > 0
  labels:
    severity: page

- alert: CheckoutsAbandonedAtEdge
  expr: |
    sum(rate(traefik_entrypoint_requests_total{entrypoint="web",method="POST",code="499"}[5m]))
      / sum(rate(traefik_entrypoint_requests_total{entrypoint="web",method="POST"}[5m])) > 0.01
  for: 5m
  labels:
    severity: ticket

As business metrics, too: orders per checkout should never go above 1, and the payment provider’s authorization count should equal the number of orders you write. When the two diverge (the graph in Step 2), something is being done either twice or not at all.

Code review checklist:

  • Does every non-idempotent endpoint that clients may retry (POST /orders, POST /payments, POST /transfers) accept an idempotency key? Is a header that never gets read caught by a contract test?
  • Does every call to the payment provider carry a key derived from the client’s key? randomUUID() is not an idempotency key; if it’s different on every request, the protection is zero.
  • Is “look up, insert if missing” backed by a unique constraint?
  • Does the server say when a retry is welcome (Retry-After)?
  • What happens when a key arrives with a different body?

A retry policy across teams. The app team did the right thing and things got worse, because the server wasn’t holding up its half of the contract. The client’s timeout should be longer than the server’s worst normal latency; retries should have a budget; and if someone writes a guide saying “retry with the same key”, there should be a test that verifies the server honours it. Featonby’s Builders’ Library article explains that this is why the AWS SDKs generate the client token themselves and reuse it on retries.

Test with a slow dependency. This bug only exists when the first attempt times out after the work has finished. A 3-second delay on the fake payment provider in staging would have shown it before the merge.


Key takeaways

  • A timeout is not an answer, it is the absence of one. A request the client gave up on has most likely completed on the server.
  • A 499 at the edge doesn’t mean “the work wasn’t done”. The API’s own metrics may never see those requests.
  • An idempotency key is a two-sided contract: the client sends it, the server reads it, stores it and recognizes the retry. Downstream (to the payment provider) goes a key derived from it.
  • “Look up, insert if missing” races on its own; the race is settled not by application code but by the database’s unique constraint.
  • Answer a retry of a request still in flight with 409 + Retry-After; an error without the header leads the client to the wrong conclusion.
  • Don’t guess duplicates from content: some customers really do buy the same thing twice.

Test yourself

1. There’s ~1 499 per second at the edge and no 5xx. Why doesn’t that mean “everything is fine”?

A 499 says the client closed the connection without waiting for the response; it says nothing about what the server did. In this incident the API finished the work after every 499: it took an authorization, wrote an order, sent an email. Comparing PayFlow’s authorization count (~3.5/s) with what the API “finished” (~2.6/s) exposes the gap.

2. The app was already retrying with the same Idempotency-Key. Why wasn’t that enough?

The server didn’t read the header, and it gave PayFlow a new random key on every request. An idempotency key isn’t a header the client sends, it’s a promise the server keeps; a key nobody reads protects nothing.

3. Why isn’t “look up the order by key first” enough, and why is a unique index needed?

Retries arrive precisely while the first attempt is slow. When the second attempt arrives, the first may still be waiting on PayFlow and may not have written its order yet: the lookup comes back empty and both carry on. In the demo that meant 2 orders instead of 4. The only atomic guarantee between lookup and insert lives in the database’s constraint: the second INSERT is rejected and the code returns the winner’s order.

4. Why is it wrong to block duplicates with a “same customer, same amount, within a minute” rule?

A customer may deliberately buy the same thing twice (two gifts, the same coffee capsules twice). Content doesn’t tell you intent; only the key generated by the client says “this is a retry of the same operation”. A content-based rule is good as a detection tool, like the SQL query in verify, not as a blocking tool.

Further reading

Basics

Deep dives

Real-world incidents


Next up: The outage that doesn’t recover. The tax provider TaxRate has a ten-second hiccup and gets over it; checkout, however, doesn’t come back, and two restarts change nothing. TaxRate says “all fine on our side, you’re just sending us a lot of traffic”. In this part we saw how to make a retry safe; in the next one we’ll count how many requests a single checkout generates and watch why a system where everyone retries at once can’t recover on its own.

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