StoicBuilder

HandbookXI the TabulariumIdempotency

XIthe Tabularium, Model the data

Idempotency

1 min readUpdated 28 November

In plain words

An operation is idempotent when doing it twice has the same effect as doing it once, which lets clients retry after a timeout without creating a second charge, invoice or email.

Where you see it

A customer clicks Pay on a Harbor invoice, their train enters a tunnel, and the app retries. With an Idempotency-Key header, the server recognises the repeated key and returns the first result instead of charging again. Stripe's API accepts the same header on POST requests for exactly this reason.

app/api/invoices/[id]/pay/route.tsserver
const key = req.headers.get("Idempotency-Key");if (key === null) return Response.json({ error: { code: "idempotency_key_required" } }, { status: 400 }); const earlier = await findPaymentByKey(key);if (earlier) return Response.json(earlier); const intent = await stripe.paymentIntents.create({ amount, currency, customer }, { idempotencyKey: key });
The same key twice returns the first answer. Passing the key on to Stripe protects the charge itself as well.

What goes wrong

  1. Checking for the key without a unique constraint

    Two retries arrive together, both find no earlier payment, and both charge. Store keys in a column with a unique index, and record the key before doing the work, so the second insert fails.

  2. A new key on every retry

    If the client makes a fresh key for each attempt, the server sees separate requests. Create the key once per user action, such as clicking Pay, and reuse it for every retry of that action.

  3. Assuming every request is safe to retry

    GET, PUT and DELETE are meant to be idempotent; POST is not. Retry logic that resends POSTs without a key turns a slow network into duplicate charges.

What to tell your agent

Copy this into Lovable, Bolt, Cursor or any agent
Make the pay-invoice endpoint idempotent: require an Idempotency-Key header, store it under a unique index before charging, return the stored result for a repeated key, and pass the key on to Stripe. Also make our Stripe webhook handler skip event ids it has already processed.

Quick check

Sign in to earn +10 XP for it

Harbor's mobile app retries a payment request after a timeout, and the customer is charged twice. Which fix addresses the cause?

Got a prompt that touches idempotency?

Paste it. You get a better prompt first, then the cards that explain it.

Check your own prompt

Free, no sign-up.