If latency budgets leave no room for synchronous retries, require client-generated `Idempotency-Key` (UUIDv4) persisted with a unique DB constraint `(merchant_id, idempotency_key)` + payload SHA-256 hash inside the initial transaction, caching the exact response for safe replays.
TL;DR30-second simplified summary▾
Core Mechanics: A billing-service (Java 21 + PostgreSQL 16 + Redis) processing 2,500 POST /v1/charges req/s sees mobile SDKs and Envoy auto-retry when a 2.1s card processor response drops on flaky 4G networks.
Visual & Structural Flow: Depicts Two-Phase Claim & Finalize vs. Concurrent Retry (Mobile / Envoy -> Billing API -> Postgres 16 -> Stripe / Adyen); PostgreSQL Authoritative Claim + Partitioned Cache (API + UUIDv4 -> Postgres Tx1/Tx2 -> Redis Read-Through -> Daily Partitions).
Trade-Offs & Production: Checking SELECT * FROM charges WHERE idempotency_key = $1 before calling Stripe suffers from a classic TOCTOU race: two retries arriving 5 ms apart both see 0 rows and both charge the card. Implement crash-safe atomic idempotency using PostgreSQL unique constraints and short transactions: Tx 1 (Atomic Claim): `INSERT INTO idempotency_keys (merchant_id, key.
Failure Modes & Application: Idempotency keys are a core building block for reliable distributed mutations: Payment Gateways & Fintech Ledgers: Prevents duplicate card captures and ledger postings across mobile retries.
Why Idempotent Payment APIs Matter.
Why this matters: The mechanism: understand how Why Idempotent Payment APIs Matter works from first principles.
A billing-service (Java 21 + PostgreSQL 16 + Redis) processing 2,500 POST /v1/charges req/s sees mobile SDKs and Envoy auto-retry when a 2.1s card processor response drops on flaky 4G networks. Without idempotency enforcement, 0.4% of transactions (10/sec) are double- or triple-charged—costing $180,000/day in chargebacks.
Constraints:
- PostgreSQL 16 handles OLTP ledger writes; Redis is not durable across failover.
- External PSP (Stripe/Adyen) accepts our
idempotency_key. - Zero TOCTOU race conditions (
SELECTthenINSERTwithout unique constraints is forbidden); retain ~216M keys/day for 24h at< 3 msp99.
Real-World Impact of Non-Idempotent Retries.
Why this matters: The problem: see what breaks without Real-World Impact of Non-Idempotent Retries under real concurrency or scale.
Without atomic idempotency keys, retries cause three severe production failures:
- Duplicate Charges: Concurrent retries arriving 5 ms apart both pass a naive
SELECTcheck and charge the card twice. - Connection Pool Starvation: Holding a PostgreSQL transaction open during a 2.1s external PSP HTTP call exhausts HikariCP connections under load.
- Payload Reuse Bugs: Reusing the same
Idempotency-Keywith a different amount or currency silently returns a stale receipt instead of422 Unprocessable Entity.
Two-Phase Claim & Finalize vs. Concurrent Retry
Claiming the unique key in a fast Tx1 before calling the PSP prevents concurrent duplicate charges without holding DB locks for 2.1s.
- Problem
- How to implement Designing Idempotent APIs to Prevent Duplicate Billing without hitting unbounded tail latency, state divergence, or operational fragility.
- Naive Solution
- Use a single unpartitioned path with unbounded retries and synchronous global coordination.
- Why It Fails
- Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
- Alternatives
- Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
- Engineering Decision
- If latency budgets leave no room for synchronous retries, require client-generated
Idempotency-Key(UUIDv4) persisted with a unique DB constraint(merchant_id, idempotency_key)+ payload SHA-256 hash inside the initial transaction, caching the exact response for safe replays. - Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When Designing Idempotent APIs to Prevent Duplicate Billing experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Naive Solution (and Why It Breaks).
Why this matters: The problem: see what breaks without Naive Solution under real concurrency or scale.
Think of Naive Solution (and Why It Breaks) as the intuition layer for Designing Idempotent APIs to Prevent Duplicate Billing: The problem: see what breaks without Naive Solution under real concurrency or scale.
Checking SELECT * FROM charges WHERE idempotency_key = $1 before calling Stripe suffers from a classic TOCTOU race: two retries arriving 5 ms apart both see 0 rows and both charge the card. Relying solely on Redis SETNX loses keys during failover, while holding a Postgres transaction open across the 2.1s PSP call exhausts the DB connection pool.
Naive Solution (and Why It Breaks)
- Stale leader overwrites state
- Clock skew breaks lease order
- Full-table sync on reboot
- Majority quorum prevents split-brain
- Fencing tokens reject zombies
- Merkle/WAL catch-up in O(log N)
Enterprise Solution: Two-Phase DB Claim + SHA-256 Guard + Redis Fast Path.
Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.
Implement crash-safe atomic idempotency using PostgreSQL unique constraints and short transactions:
- Tx 1 (Atomic Claim):
INSERT INTO idempotency_keys (merchant_id, key, req_hash, status) VALUES (...) ON CONFLICT DO NOTHING. If inserted, proceed; if conflict, comparereq_hash(422on mismatch), return409 Conflict(Retry-After: 1) ifIN_PROGRESS, or replay the cachedhttp_status+response_bodyifCOMPLETED. - External PSP Call (No DB Lock Held): Forward
idempotency_keyto Stripe/Adyen so even a mid-flight pod crash cannot double-charge on recovery. - Tx 2 (Finalize) & Partitioned Retention: Update status to
COMPLETED(or release key on guaranteed non-execution) and populate Redis as a read-through cache. Partitionidempotency_keysby hour/day for instantDROP TABLETTL cleanup of 216M keys/day.
PostgreSQL Authoritative Claim + Partitioned Cache
1.Unique Constraint: Eliminates TOCTOU races without table-level locks.
2.Payload Hash: SHA-256 check returns 422 if key is reused with different body.
3.Crash Recovery: Stale IN_PROGRESS keys (>30s) re-query PSP using same key.
4.Partitioned TTL: Drop daily partitions instead of running expensive DELETEs.
PostgreSQL provides durable atomic locking via unique constraints while Redis accelerates <3 ms replay lookups.
if (idempotencyKey == null || !UUID_REGEX.matcher(idempotencyKey).matches()) {
return ResponseEntity.badRequest().body("Missing or invalid Idempotency-Key");
}
ClaimResult claim = repo.claimKey(merchantId, key, sha256(body));
if (claim.isDuplicate()) {
if (!Arrays.equals(claim.hash(), sha256(body))) throw new UnprocessableEntityException();
if (claim.status() == IN_PROGRESS) throw new ConflictException("Retry-After: 1");
return ResponseEntity.status(claim.httpStatus()).body(claim.responseBody());
}
// Execute PSP call with key, then Tx 2 finalize()
if (pspResponse.isTerminal()) {
repo.complete(key, pspResponse.status(), pspResponse.body());
} else if (pspResponse.isGuaranteedNotProcessed()) {
repo.releaseKey(key);
}
Where Idempotent APIs Apply in System Design.
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Idempotency keys are a core building block for reliable distributed mutations:
- Payment Gateways & Fintech Ledgers: Prevents duplicate card captures and ledger postings across mobile retries.
- Order & Inventory Reservation APIs: Ensures checkout retries return the same
order_idinstead of double-decrementing stock. - Webhook & Saga Orchestrators: Makes at-least-once message delivery behave as exactly-once state transitions.
Practice: Make the trade-off yourself.
Why should an idempotent payment API commit a short `IN_PROGRESS` row before calling the external card processor instead of holding one DB transaction open during the 2.1s HTTP call?