- rtshkmr's digital garden/
- References/
- Architecture Design Basics/
- Pattern Taxonomy/
- Domain-Specific Patterns/
- Idempotency Keys/
Idempotency Keys
··
191 words·
1 min
Table of Contents
π΄ 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 responseDesign Decisions #
| Decision | Trade-off |
|---|---|
| Key TTL | 24hβ72h typical. Too short β retries after TTL create duplicates. Too long β storage cost. |
| Request body matching | Same key + different body = error (prevent misuse). Check body hash against stored hash. |
| Key generation | Client-generated (most flexible). UUIDv4 or deterministic hash of request params. |
| Concurrent requests | Same 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 #
- Stripe: Idempotent Requests
- Implementing Stripe-like Idempotency Keys in Postgres β Brandur Leach
- Designing Robust and Predictable APIs with Idempotency β Stripe Engineering