Concurrency and races · Chapter 2 of 15

Double submit, double charge

Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Two requests at once
  • 3 tasks
  • JavaScript
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

The lesson

By the end of this case

You can tell why an idempotency check that looks only at finished work still lets duplicates through, make the double charge happen on purpose, fix it by remembering the key before the work starts, and guard it with a test that checks both sides.

The ticket

TAP-815: Charged twice for one order. Assigned to you by Kabir. Priority: high. Since: the rains started.

Meera, in the founders' channel at 7:55 pm: "A customer in Whitefield paid ₹130 twice for order 5120, two masala chai and two cutting chai. She says the Pay button did nothing, so she tapped it again. We refunded her, but this is the third one this week, all on bad network days. Don't we have something that stops this?"

The payments log for order 5120:

19:41:07.902  payments  order 5120: ₹130 SUCCESS (pay_8812)
19:41:07.951  payments  order 5120: ₹130 SUCCESS (pay_8813)

Kabir: "We do. The app sends an idempotency key with every attempt to pay, and the API checks it: same key, same receipt, no new charge. And both of those requests carried the same key, I checked. Look at the gap between the two lines, then at when the key gets remembered. Reproduce it, fix it, and make sure it never comes back. You are in payments.js."

What an idempotency key promises

An idempotency key is a random id the app makes once per attempt to pay and sends with every retry of that attempt. The server promises: whatever happens to the network, one key means at most one charge, and every request with that key gets the same answer. A new attempt, after a decline, gets a new key, and may be charged.

So the key names the attempt, not the order. That difference matters in the fix.

Remembered too late

Here is the same kind of check on a kitchen printer that must print each ticket once. It remembers a ticket after printing it:

let prints = 0;
const printer = {
  async print(id) {
    await new Promise((r) => setImmediate(r)); // the printer is slow
    prints += 1;
    return `${id} on paper`;
  },
};

const printed = new Set();
async function printKot(id) {
  if (printed.has(id)) return 'already printed';
  await printer.print(id);
  printed.add(id);
  return 'printed';
}

console.log(await Promise.all([printKot('KOT-9'), printKot('KOT-9')]), 'prints:', prints);
console.log(await printKot('KOT-9'), 'prints:', prints);
[ 'printed', 'printed' ] prints: 2
already printed prints: 2

The check works for a duplicate that arrives after the work is done, and fails for one that arrives during it. Both calls looked at the set before either had added to it: the gap between the await and the add is the race. On good network the second tap comes seconds later and finds the key; on a slow network the first request is still waiting for the bank when the second one lands.

Making it happen on purpose

Start two calls with the same input together, before awaiting either, against a fake gateway that counts its charges. To look inside the gap, as the check does, make the fake return a promise you settle yourself with Promise.withResolvers(): while it is unsettled, every request that came in is waiting, and you can count how many charges started.

A guard that checks both sides

One test sends two requests with one key together and expects one charge and the same receipt for both. That fails on the bug. But a fix that remembers the order instead of the key passes it, and is wrong: after a declined attempt, every new attempt for that order gets the old declined receipt. So a second test declines one attempt and expects a new key for the same order to be charged. In vitest, vi.fn() makes a fake that counts its calls, and mockResolvedValueOnce sets its answer for one call at a time.

Your turn

Three tasks, one file each. In repro.js, charge a customer twice on purpose with a counting fake gateway, and run it with node repro.js in the case's folder. In payments.js, remember the key from the moment its charge starts. In payments.test.js, write the guard: the check runs it beside the original code, the fix and a wrong fix that remembers the order. Then answer Kabir's interview question at the bottom of the case, in your own words.

What you build: 3 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    repro.js: charge a customer twice on purpose

    Write reproduce() in repro.js. Build a fake gateway, an object whose charge(orderId, amount) counts its calls and resolves to { paymentId, status: 'SUCCESS' } (any payment id). Make payments with createPayments({ gateway }) from payments.js, then send two pay requests with the same { orderId, amount, key } at the same time, as two taps on Pay do. Wait for both, and resolve to how many times the gateway charged.

    The check runs your reproduce() twice: beside the original payments.js it must resolve to 2 (one key, two charges), and beside a fixed payments.js it must resolve to 1. Requests made one after another never race, so start both before waiting for either. No real waiting: the fake answers straight away, and reproduce() must finish within 2 seconds.

  2. Task 2

    payments.js: one key, one charge

    Fix createPayments({ gateway }) in payments.js so a key is remembered from the moment its charge starts, not when it finishes. Requests with the same key that arrive while the gateway is still busy make no new charge: they wait for the first one and resolve to the same receipt { orderId, amount, paymentId, status }. The same key later gets the same receipt, with no new charge. A new key is a new attempt and is charged, even for the same order (after a DECLINED attempt, say).

    When the charge rejects (the gateway cannot be reached), every request waiting for it rejects with that error, and the key is forgotten, so the same key can try again. Keep the receipt's shape and both log lines as they are. The check uses its own orders and keys, holds the gateway's answers back and counts the charges.

  3. Task 3

    payments.test.js: a test that would have caught it

    Write a vitest test file, payments.test.js, that would have caught the double charge. The check runs your file three times: beside the original payments.js, where at least one test must fail; beside the fixed payments.js, where every test must pass; and beside a wrong fix that remembers the order instead of the key, where at least one test must fail.

    So test both sides with fake gateways: two pays with the same key at the same time make one charge and get the same receipt; and after an attempt the gateway answers DECLINED, a new attempt for the same order with a new key is charged again. No real waiting: each test must finish within 3 seconds.

What you will learn

  • repro.js: charge a customer twice on purpose
  • payments.js: one key, one charge
  • payments.test.js: a test that would have caught it

More in Two requests at once

Build "Double submit, double charge" yourself

Tapri's backend grew busy, and Kabir keeps handing you incidents that only happen when two things run at once. Each is a race interviews love to ask about. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.