पाठ 19 / 25

Idempotency Keys

Making POST requests safe to retry.

Retry without double charging

Networks fail: a request to create a payment might succeed at Stripe while your server times out waiting for the reply. If you simply retry, you might create a second payment. An idempotency key is a unique string you send with a POST request; if Stripe sees the same key again, it returns the saved result of the first request instead of performing the operation twice. Use a key derived from your own operation, such as an order ID plus an action, and reuse it only for retries of the same request with the same parameters. Keys are kept for at least 24 hours. The Node.js library can retry network failures automatically with maxNetworkRetries and adds idempotency keys to those retries.

Never charge twice, never charge wrong

Correct payment code handles retries safely, represents money precisely and treats errors by type.

Three ideas: idempotency keys, amounts and metadata, and error handling with retries.
Figure 7.1 — Request, idempotency check, result and reconciliation.

Passing an idempotency key

Node.js request options.

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
  maxNetworkRetries: 2,   // automatic retries for network errors
});

const intent = await stripe.paymentIntents.create(
  {
    amount: 4200,
    currency: 'usd',
    customer: 'cus_...',
    metadata: { orderId: 'ord_123' },
  },
  { idempotencyKey: 'ord_123-create-payment' },  // same key on every retry
);

A numbered cheque

Writing the order number on a cheque means the bank can refuse to cash the same cheque twice, however many times it is presented.

त्वरित जाँच: What happens when you repeat a create request with the same idempotency key and parameters?

  • Stripe deletes the original object
  • Stripe creates a second object
  • Stripe always returns an error
  • Stripe returns the result of the original request
Answer

Stripe returns the result of the original request — That is what makes retries safe.