Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 38 ยท Checkout and Payment Intents

Idempotency Keys and Safe Retries

Learn why network failures cause duplicate payments and how Stripe idempotency keys, exponential backoff and jitter let you retry safely, with a runnable stand-in of the server-side logic.

Here is a nightmare scenario. Your server asks Stripe to charge a customer $49. Stripe processes it. Then the network drops before the response reaches you. Your code sees a timeout. Did the charge happen? You do not know. If you retry blindly, the customer may be charged twice. If you do nothing, they may not be charged at all.

Distributed systems cannot remove this uncertainty, but they can make it harmless. The tool is the idempotency key. An operation is idempotent when doing it once or many times has the same effect. Stripe lets you make any POST request idempotent by attaching a unique key you choose.

How the key works

You send a header (the SDKs expose it as an option):

Terminal
curl https://api.stripe.com/v1/payment_intents \
  -u sk_test_YOUR_KEY: \
  -H "Idempotency-Key: order-A-1043-attempt-1" \
  -d amount=4900 -d currency=usd

Stripe stores the first response it produced for that key (together with the request parameters) for at least 24 hours. If the same key arrives again:

  • Same parameters: Stripe returns the saved response, status code and body, without doing the work again. That includes errors, with one exception: if the first request failed before Stripe started processing, the retry runs normally.
  • Different parameters: Stripe returns an error, because reusing a key for a different request is almost certainly a bug.
JavaScript
// Real SDK usage (read-only).
const intent = await stripe.paymentIntents.create(
  { amount: 4900, currency: "usd", metadata: { order_id: "A-1043" } },
  { idempotencyKey: `order-${order.id}-payment-intent` },
);

The double-charge problem

Request sent Stripe charges the card
Response lost Timeout on your side
Blind retry Second charge!
1 / 2

What makes a good key

  • Unique per logical operation, repeatable across retries of that operation. A random UUID generated once and stored with the order is excellent. A deterministic string like order-1043-charge is also good, because a crashed-and-restarted process rebuilds the same key.
  • Not reused for a different amount or customer.
  • Generated before the first attempt, never inside the retry loop. A fresh key per retry defeats the entire purpose.

A stand-in server with idempotency

The best way to understand the mechanism is to build the server side. This stand-in stores results by key, and also simulates a flaky network that loses the response once. Compare the "without key" and "with key" outcomes.

Node.js Duplicate charges, with and without a key (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Retry strategy: backoff and jitter

Idempotency makes retries safe; you still need them to be polite. If Stripe or your network is struggling, thousands of clients retrying instantly make it worse. Use exponential backoff: wait 1 s, then 2 s, then 4 s, and so on, up to a cap, and add jitter (a random spread) so all your instances do not retry in the same millisecond.

Which errors should you retry?

Situation Retry?
Network error or timeout Yes, same idempotency key
5xx from Stripe Yes
429 rate limit Yes, after backing off
409 conflict (key in use) Yes, shortly later
400 invalid request No, fix the request
402 card declined No, ask the customer for another method
Node.js Backoff with jitter (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Idempotency on your own side

Your server is also a place where duplicates arise: a customer double-clicks "Pay", a mobile app resends a request, a webhook arrives twice. Defend each entry point:

  • Disable the button after the first click, and again protect the server with an idempotency key you generate for the order.
  • Use database constraints: a unique index on stripe_event_id or payment_intent_id makes double inserts fail loudly instead of silently.
  • Make handlers re-runnable: updating status = "paid" twice is harmless; incrementing a counter twice is not.

What not to do

  • Do not generate a new key on each retry.
  • Do not use the same key for different customers or amounts.
  • Do not treat a replayed response as new; it carries the Idempotent-Replayed: true header so you can tell.
  • Do not depend on keys for GET requests; reads are already safe.

Next, what happens after the money is collected and something goes wrong: Refunds, Disputes and Payouts.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Stripe do when it receives the same idempotency key and the same parameters twice?

    The saved result is replayed, so the operation happens only once.
  2. 2. Where should the idempotency key be generated?

    A new key on each retry would create a new operation and defeat the protection.
  3. 3. Which response should NOT be retried unchanged?

    A 400 will fail the same way until you fix the request.
  4. 4. Why add jitter to backoff delays?

    Randomising delays spreads out load during recoveries.

Summary

  • A lost response leaves the outcome unknown; retrying blindly can double-charge.
  • An Idempotency-Key makes Stripe replay the first result instead of repeating the work.
  • Generate the key once per operation; never change it between retries.
  • Retry network errors, 429, 409 and 5xx with exponential backoff plus jitter; never retry 400 or 402 unchanged.
  • Protect your own endpoints with disabled buttons, unique constraints and re-runnable handlers.

Next: Refunds, Disputes and Payouts