Design an Idempotent Payment Processing Service
System DesignModel answerLast updated
Design a payment service that safely retries failed transactions without double-charging customers, handling scale of ~10,000 transactions per second.
Design an Idempotent Payment Processing Service
Background
You are a senior engineer at a fast-growing e-commerce platform. The checkout service calls a downstream Payment Service to charge customers. Due to network timeouts, client retries, and server restarts, the same payment request can arrive multiple times. Customers have complained about duplicate charges appearing on their credit card statements.
Your task is to redesign the Payment Service so that retrying a payment request is always safe — it either succeeds exactly once or fails cleanly.
Scale & Constraints
- Peak load: ~10,000 payment requests per second
- Payment amounts: $0.01 – $50,000 per transaction
- Retry window: clients may retry the same logical payment for up to 24 hours
- Latency SLO: p99 < 500 ms end-to-end
- Durability: no payment record may be silently lost
- Downstream: you call an external payment processor (think Stripe/Adyen) that is NOT idempotent by default — each call creates a new charge
What is Expected
- Requirements & clarifying questions — functional and non-functional
- API design — how clients communicate idempotency intent
- Data model — what you store and why
- Architecture — components, flows for the happy path and retry path
- Deep dives — at least two: (a) how you prevent double charges at the DB layer, (b) how you handle the case where the external processor responds but your service crashes before saving the result
- Trade-offs — discuss at least one alternative you considered and why you chose your approach
Hints
Hint 1
Think about where the idempotency key comes from and who is responsible for generating it — the client or the server?
Hint 2
What database property (e.g., a unique constraint) can act as your last line of defense against duplicate writes, even if application-level checks race?
Hint 3
Consider the window between 'call external processor' and 'write result to DB' — what patterns (e.g., outbox, status machine) help you survive a crash there?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Clarifying Questions & Requirements
Functional
- Clients must be able to retry a payment and receive the same outcome as the first attempt.
- The service must call an external processor exactly once per logical payment.
- Clients can query the status of a payment by its idempotency key.
Non-functional
- 10,000 TPS peak → ~864 M transactions/day; plan storage accordingly.
- 24-hour retry window → idempotency records must be retained at least 24 hours (keep 7 days for disputes).
- p99 < 500 ms, so any locking strategy must be fast.
- Strong durability: at-least-once delivery to the external processor, exactly-once recording internally.
2. API Design
POST /v1/payments
Headers:
Idempotency-Key: <client-generated UUID v4> # required
Authorization: Bearer <token>
Body:
{
"amount_cents": 4999,
"currency": "USD",
"payment_method_token": "pm_abc123",
"order_id": "ord_xyz"
}
Response 200 (first success or idempotent replay):
{
"payment_id": "pay_...",
"status": "succeeded",
"idempotency_key": "...",
"created_at": "...",
"replayed": false // true if this was a retry returning a cached result
}
Response 409 Conflict: key exists but with different request body (fingerprint mismatch)
Response 422: validation error
Response 503: processor unavailable
Key decision: The client generates the idempotency key (a UUID), not the server. This means the client can generate it before sending and use the same key on every retry. The server treats the key + request body hash as a compound fingerprint to detect mismatched retries.
3. Data Model
payments table (PostgreSQL)
| Column | Type | Notes |
|---|---|---|
idempotency_key | UUID | UNIQUE constraint — the critical guard |
payment_id | UUID PK | Internal identifier |
order_id | UUID | FK to orders |
amount_cents | BIGINT | |
currency | CHAR(3) | |
request_fingerprint | CHAR(64) | SHA-256 of canonical request body |
status | ENUM | pending, processing, succeeded, failed |
processor_charge_id | TEXT NULL | External processor's charge ID |
processor_response | JSONB NULL | Full response for audits |
created_at | TIMESTAMPTZ | |
completed_at | TIMESTAMPTZ NULL | |
locked_until | TIMESTAMPTZ NULL | Optimistic in-flight lock |
The UNIQUE constraint on idempotency_key is the database-level safety net. Even if two concurrent retries slip past the application layer simultaneously, only one INSERT will succeed; the other receives a unique violation and returns the cached result.
4. Architecture
Client → API Gateway → Payment Service → [PostgreSQL]
↘ External Processor
Happy path
- Client sends POST with
Idempotency-Key: K. - Payment Service attempts
INSERT INTO payments (idempotency_key=K, status='pending', ...). If the INSERT succeeds, proceed. If it fails with a unique violation, jump to step 5. - Service calls external processor (Stripe et al.) with its own idempotency key derived as
HMAC(K, internal_secret)— this makes the external call idempotent too. - On processor success:
UPDATE payments SET status='succeeded', processor_charge_id=..., completed_at=now(). - Retry path: SELECT the existing row by
K. Verifyrequest_fingerprintmatches (else 409). Return the stored result; if status is stillpending/processing, return 202 and let the client poll.
Status machine: pending → processing → succeeded | failed
The processing state with a locked_until timestamp prevents two concurrent requests from both calling the external processor. A request that finds a row in processing state waits briefly or returns 202. A background sweeper reclaims rows stuck in processing past their lock timeout (handles crashed workers).
5. Deep Dives
(a) Preventing double charges at the DB layer
The UNIQUE constraint on idempotency_key is the last line of defense. Application-level "check then insert" patterns have a TOCTOU race under concurrent retries. With the DB constraint:
- First writer wins the INSERT.
- All other concurrent writers receive a constraint violation and read-then-return the winning row.
- This works even with multiple Payment Service pods, no distributed lock needed.
For extra safety, pass the HMAC(K, secret) key to the external processor's own idempotency header. Even if the processor is called twice (network timeout before response), the processor deduplicates and returns the same charge.
(b) Crash between processor response and DB write (the "ghost charge" problem)
This is the hardest failure mode. The processor charged the card, but your service crashed before writing processor_charge_id to the DB.
Solution — status + reconciliation loop:
- Before calling the processor, set
status = 'processing'and recordlocked_until = now() + 30s. - Call the processor.
- On response, immediately write the result.
- A reconciliation job runs every minute and finds rows stuck in
processingwithlocked_until < now(). For each, it calls the processor's "retrieve charge" API using the deterministicHMAC(K, secret)key to check if the charge exists. If yes, update the row tosucceeded. If no, markfailedand allow retry.
This pattern is sometimes called a "two-phase outcome": you commit intent before the external call and confirm outcome after, with a background process to close the gap.
6. Trade-offs
Alternative considered: Redis-based idempotency cache (SET NX)
Use Redis SET idempotency_key result EX 86400 NX as the deduplication layer. Faster reads (sub-millisecond), but:
- Redis is not durable by default; an AOF-flush or replication lag could lose the key, allowing a double charge.
- Adds operational complexity (Redis cluster + Postgres).
- The DB unique constraint already achieves the goal with one fewer moving part.
Chosen approach: Postgres unique constraint is slower (~5–10 ms for indexed lookup) but offers ACID durability with no extra infrastructure. At 10,000 TPS and a read-heavy retry ratio, connection pooling (PgBouncer) keeps this within SLO.
Idempotency key expiry: After 24 hours, rows are archived to cold storage. Keys older than 24 hours that arrive (stale retry) return 410 Gone, telling the client to generate a fresh key and resubmit if needed.
Common Mistakes to Avoid
- Generating the key server-side on first receipt: the client loses the ability to retry before the server ever responds.
- Using
SELECTthenINSERTwithout a DB constraint: classic TOCTOU race. - Forgetting to pass an idempotency key to the external processor: even if you deduplicate internally, a timeout can cause you to re-call the processor and create a second charge externally.
- No status machine: without a
processingstate, a crashed worker leaves no evidence it was mid-flight, making reconciliation impossible.