Skip to main content
  1. References/
  2. Architecture Design Basics/
  3. Pattern Taxonomy/
  4. Domain-Specific Patterns/

Idempotency Keys

·· 191 words· 1 min

πŸ”΄ P0 — Stripe’s public API is built on this; the implementation of idempotency for APIs

Problem #

A client sends POST /v1/charges and gets a timeout. Did the charge succeed? The client must retry, but retrying might create a duplicate charge. Idempotency keys solve this.

Mechanism (Stripe’s model) #

Client β†’ POST /v1/charges
         Header: Idempotency-Key: "key_abc123"
         Body: {amount: 5000, currency: "usd", customer: "cus_xyz"}

Server flow:
  1. BEGIN TRANSACTION
  2. SELECT * FROM idempotency_keys WHERE key = "key_abc123"
  3. If found AND completed β†’ return stored response (200 + original body)
  4. If found AND in-progress β†’ return 409 Conflict (concurrent request)
  5. If not found:
     a. INSERT INTO idempotency_keys (key, request_hash, status='started')
     b. Execute the charge
     c. UPDATE idempotency_keys SET status='completed', response=...
  6. COMMIT
  7. Return response

Design Decisions #

DecisionTrade-off
Key TTL24h–72h typical. Too short β†’ retries after TTL create duplicates. Too long β†’ storage cost.
Request body matchingSame key + different body = error (prevent misuse). Check body hash against stored hash.
Key generationClient-generated (most flexible). UUIDv4 or deterministic hash of request params.
Concurrent requestsSame key concurrently = 409. Only one request “wins.”

Instinct #

The idempotency key is the client’s contract with the server: “this is the same logical operation.” The server’s job is to guarantee that the operation’s side effects happen exactly once regardless of how many times the key is presented. For Stripe interviews, know this pattern cold β€” it’s core to their API design philosophy.

References #