BeCuriouzBeCuriouz

Learn something new every day

🛠️ Tools & Services
💳

How Stripe makes sure you're never charged twice

💡 An idempotency key lets a client safely retry a request because the server runs the operation only once and replays the original result for every repeat.

Stripe is a developer platform for accepting payments online. Instead of wrestling with banks, card networks, and PCI compliance yourself, you make a single API call and Stripe handles the messy machinery of moving money. Its real product isn't a checkout page — it's a clean set of APIs that hide decades of financial plumbing behind a few lines of code.

But payments have a nasty edge case: the internet is unreliable. Imagine your server sends a "charge this card" request, the payment succeeds, but the network drops before Stripe's response gets back. Your code doesn't know if it worked, so it retries — and now the customer is charged twice. Stripe's elegant fix is the idempotency key: a unique string (they suggest a random V4 UUID) you attach to a request via the Idempotency-Key header.

Here's the non-obvious part. Stripe saves the status code and response body of the first request under that key. Any later request with the same key returns the saved result instead of running the operation again — even replaying the original 500 error. So retrying is always safe: the second call is a no-op that just echoes the first outcome. Stripe even compares the incoming parameters and errors if you reuse a key with different data, catching accidental misuse. Keys can be pruned after 24 hours, since retries realistically happen within seconds.

This is why idempotency — an operation that has the same effect whether run once or many times — is a foundational idea far beyond payments. Any API that mutates money, inventory, or state needs a way to make "try again" boringly safe.