Building a Fault-Tolerant Payment System with Zero Duplicates
System DesignModel answerLast updated
Design a payment platform that prevents duplicate charges through idempotency, handles gateway timeouts safely, and maintains financial correctness.
Problem Context
You're building the core transaction engine for a SaaS billing platform. This engine receives payment requests from multiple sources—checkout flows, subscription renewals, invoice processors—and executes them against third-party payment processors like Stripe or PayPal. The system must record every financial event in an immutable ledger.
The central challenge: guarantee that network failures, retries, and async notifications never cause a customer to be charged twice.
Your Task
Design a system that enforces strict idempotency while handling real-world failure modes: requests that time out mid-flight, webhooks that arrive out of order, and scenarios where you cannot determine if a charge succeeded.
Functional Goals
- Duplicate Prevention: When a client retries the same payment request, return the original outcome without re-executing the charge
- Timeout Resolution: When a gateway call times out, safely discover the actual outcome without risking a duplicate charge
- Concurrent Event Handling: Process both synchronous API responses and asynchronous webhook notifications without creating race conditions
- Audit Trail: Keep an append-only record of all state transitions that supports forensic analysis
- Recovery Mechanisms: Support automated reconciliation against external settlement files and provide guarded manual intervention for edge cases
Performance & Reliability Targets
- Correctness First: No duplicate charges under any combination of failures—network partitions, process crashes, database failovers
- Availability: 99.99% uptime for accepting new payment requests
- Throughput: Handle 100 million daily transactions (roughly 1,200 TPS average, 5,000 TPS peak)
- Monetary Precision: Support exact decimal arithmetic across multiple currencies without rounding errors
Design Scope
Your design should address:
- Request Interface & Storage Schema: How clients submit payments with idempotency keys, how you fingerprint requests, what payment states exist, and how the ledger is structured
- Concurrency Strategy: How you prevent two concurrent requests with the same key from both executing, and how state transitions are protected
- External Gateway Protocol: How you isolate timeout scenarios, implement safe retry logic, and query for transaction status
- Webhook Integration: How you handle payment status updates arriving through async callbacks, possibly before or after your synchronous call returns
- Reconciliation & Manual Operations: How you verify correctness against daily settlement reports and what safeguards exist around operator-initiated fixes
Focus on the mechanisms that guarantee correctness under failure. You can assume standard infrastructure (load balancers, databases, message queues) exists.
Hints
Hint 1
Think about what makes a payment request unique and how to enforce 'execute once' semantics at the database level
Hint 2
Consider what happens when your gateway HTTP call times out: did the charge go through or not? How do you find out safely?
Hint 3
Webhooks and API responses might report different outcomes for the same payment. Which source of truth wins, and how do you handle conflicts?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach to a Fault-Tolerant Payment System
1. Establish Core Constraints and Scale
The fundamental invariant: each logical payment intent produces exactly one charge at the gateway, regardless of retries or failures.
Quick capacity planning:
- 100M transactions/day ≈ 1,160 TPS average, 5,000 TPS peak
- Each payment generates multiple writes (idempotency record, payment record, events, ledger entries, notification queue), so expect 20–35K writes/sec at peak
- Storage: roughly 2 KB per payment across all tables = 200 GB/day or ~70 TB/year, requiring partitioning and archival strategies
- Idempotency key retention window: maintain keys for at least the client retry window, typically 7–30 days (700M–3B keys in active storage)
Key clarifications to gather:
- Single-step charge or separate authorization/capture?
- How do refunds and chargebacks fit into the model?
- Is tenant context always provided? (Assume yes for multi-tenant SaaS)
2. API Contract and Data Schema
Endpoint design:
POST /v1/payments
Headers:
Idempotency-Key: <client-generated-uuid>
X-Tenant-Id: <tenant>
Body: {
amount_minor: 129900,
currency: "USD",
payment_method_id: "pm_...",
customer_id: "cust_...",
metadata: {}
}
Response: 201 { payment_id, status, gateway_reference }
Monetary representation: Store amounts as BIGINT amount_minor (smallest currency unit) paired with an ISO-4217 currency code. Maintain a currency metadata table with decimal exponents (USD=2, JPY=0, KWD=3). Use DECIMAL(38,18) for exchange rate calculations. Never use floating-point types.
Core tables:
idempotency_keys
- Primary key:
(tenant_id, idempotency_key)with UNIQUE constraint - Fields:
request_fingerprint(SHA-256 of normalized request body),payment_id(FK),status(IN_PROGRESS | COMPLETED),response_snapshot,created_at - The unique constraint provides the actual synchronization mechanism
payments
- Primary key:
payment_id(UUID, also forwarded as the gateway's idempotency key) - Fields:
tenant_id,amount_minor,currency,state,optimistic_version,gateway_provider,gateway_transaction_id,retry_count state: INITIATED → GATEWAY_PENDING → SUCCEEDED | FAILED | NEEDS_VERIFICATION
payment_state_log
- Append-only audit trail
- Fields:
payment_id,previous_state,new_state,trigger_source(API | WEBHOOK | RECONCILIATION | OPERATOR),actor_id,event_payload,timestamp
webhook_events
- Primary key:
(gateway_provider, provider_event_id)with UNIQUE constraint for deduplication - Fields:
raw_payload,signature_valid,processed_at,linked_payment_id
financial_ledger
- Double-entry bookkeeping with cryptographic chaining
- Fields:
entry_id,transaction_group_id,account_id,debit_minor,credit_minor,currency,previous_entry_hash,entry_hash - Hash chaining:
entry_hash = SHA256(previous_entry_hash || canonical_entry_data), periodically anchored to immutable storage
event_outbox
- Transactional outbox pattern for publishing events to Kafka/similar
- Written atomically with payment state changes, processed by separate publisher
3. State Machine and Concurrency Control
State flow:
INITIATED → GATEWAY_PENDING → SUCCEEDED
↓
NEEDS_VERIFICATION → SUCCEEDED | FAILED
↓
FAILED
Terminal states (SUCCEEDED, FAILED) are immutable.
State transition enforcement:
UPDATE payments
SET state = :new_state,
optimistic_version = optimistic_version + 1,
updated_at = NOW()
WHERE payment_id = :id
AND state = ANY(:allowed_previous_states)
AND optimistic_version = :expected_version
RETURNING *;
If zero rows updated, another process won the race. Reload current state and either treat as no-op (already terminal) or retry the transition logic.
Request processing flow:
- Acquire idempotency lock:
INSERT INTO idempotency_keys (tenant_id, idempotency_key, request_fingerprint, status, created_at)
VALUES (:tenant, :key, :fingerprint, 'IN_PROGRESS', NOW())
ON CONFLICT (tenant_id, idempotency_key) DO NOTHING
RETURNING payment_id;
- Insert succeeded: you own this request
- Conflict detected: read existing row
- If
request_fingerprintdiffers: return HTTP 422 (different request, same key) - If
status = COMPLETED: return cached response (replay) - If
status = IN_PROGRESS: return HTTP 409 withRetry-Afterheader
- If
-
Record intent: Create payment in INITIATED state, then transition to GATEWAY_PENDING before calling the gateway. This write-ahead intent ensures the payment exists before any external communication.
-
Execute gateway call: Use the payment's UUID as the gateway's idempotency key. Configure aggressive timeouts (3s connect, 10s read).
-
Finalize: Apply state transition based on response, update idempotency record to COMPLETED, write ledger entries and outbox events—all in one transaction.
Why not distributed locks? Redis or Zookeeper locks introduce failure modes: if a holder experiences GC pause and the lease expires, mutual exclusion breaks. Instead, layer three mechanisms:
- Database UNIQUE constraint (ensures single writer)
- Optimistic locking via version field (detects concurrent updates)
- Gateway-side idempotency key (prevents duplicate charges even if coordination fails)
4. Gateway Communication Strategy
Adapter isolation: Run dedicated adapter services per gateway provider, each with independent connection pools, circuit breakers, and timeout configurations.
Response classification:
| Gateway Response | Interpretation | Action |
|---|---|---|
| 2xx with success indicator | Definitive success | Transition to SUCCEEDED |
| 4xx decline | Definitive failure | Transition to FAILED |
| Timeout / connection error | Unknown outcome | Transition to NEEDS_VERIFICATION |
| 5xx server error | Unknown outcome | Transition to NEEDS_VERIFICATION |
| 429 rate limit | Unknown if received | Transition to NEEDS_VERIFICATION |
Never assume timeout means failure—the gateway may have received and processed the request.
Verification worker process:
For payments in NEEDS_VERIFICATION state, a background worker executes exponential backoff (1s, 2s, 4s, 8s... capped at 5 minutes) for up to 10 attempts:
- Call the gateway's transaction status API using our payment_id reference
- If gateway reports definitive status, apply that state transition
- If gateway has no record, retry the original charge request with the identical idempotency key—this is safe because the gateway deduplicates
- After bounded retry window expires, escalate to reconciliation queue and alert operators
Critical principle: Never automatically mark a payment as FAILED if uncertainty remains. False failures damage trust more than delayed resolution.
5. Webhook Event Handling
Ingestion pipeline:
-
Immediate acceptance:
- Validate HMAC signature
- Insert into
webhook_events(unique constraint on provider_event_id deduplicates replays) - Return HTTP 200 within milliseconds
-
Async processing:
- Worker maps webhook to payment_id
- Calls the same state transition function used by the synchronous path
- Optimistic locking handles races naturally
Race condition resolution:
The state machine and optimistic locking solve ordering problems:
- Webhook arrives first: Transitions payment from GATEWAY_PENDING → SUCCEEDED. Later sync response finds terminal state, becomes no-op.
- Sync response first: Marks SUCCEEDED. Webhook arrives, attempts same transition, version check causes no-op.
- Conflicting outcomes: If webhook says SUCCEEDED but sync path recorded FAILED (or vice versa), log critical alert for investigation. In practice, using the payment UUID as the gateway idempotency key ensures both paths see the same gateway outcome.
Late-arriving webhooks: If webhook references unknown payment_id (extremely rare given write-ahead intent), retry processing with backoff until payment record appears.
6. Reconciliation and Operational Safety
Automated reconciliation:
Daily batch job:
- Download settlement reports from each gateway (CSV/API export)
- Match gateway transaction IDs to payment records
- Flag discrepancies:
- Payment marked SUCCEEDED, not in settlement → potential refund or chargeback
- Payment in NEEDS_VERIFICATION, found in settlement → apply SUCCEEDED transition
- Payment in settlement, no local record → critical data loss alert
Manual operator interventions:
Require two-person approval for state override commands. Log includes:
- Operator identities
- Justification ticket reference
- Gateway evidence (screenshots, support ticket)
- Automatic notification to finance team
Never allow deletion or silent correction—only compensating entries.
Common failure modes:
- Split brain during database failover: Optimistic locking prevents; at most one transaction commits
- Webhook replay attacks:
provider_event_idunique constraint deduplicates - Gateway reporting delays: Verification worker plus reconciliation catches these within 24 hours
- Byzantine failures (gateway reports success, never settles): Reconciliation detects; escalate to gateway support with ledger proof
Key Design Decisions
- Database-level synchronization over distributed locks: Simpler failure model, no lease expiry edge cases
- Treat timeouts as unknown, not failed: Correctness over latency
- Gateway idempotency key = payment UUID: Single source of truth across all paths
- Append-only state log: Enables audit, debugging, and replay without data loss
- Bounded retry with escalation: Automated recovery for transient issues, human review for persistent problems
Time Complexity: Each payment request involves O(1) database lookups and writes. Verification and reconciliation are O(n) batch processes over pending/recent transactions.
Space Complexity: O(n) storage proportional to transaction count, with time-based partitioning and archival to cold storage after retention period.