Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Designing Idempotent APIs to
Prevent Duplicate Billing.

Mobile SDKs and Envoy auto-retry timed-out POST /v1/charges requests, creating duplicate Stripe/card charges because the payment API lacks atomic idempotency enforcement.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

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.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

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 (SELECT then INSERT without unique constraints is forbidden); retain ~216M keys/day for 24h at < 3 ms p99.
02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

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:

  1. Duplicate Charges: Concurrent retries arriving 5 ms apart both pass a naive SELECT check and charge the card twice.
  2. Connection Pool Starvation: Holding a PostgreSQL transaction open during a 2.1s external PSP HTTP call exhausts HikariCP connections under load.
  3. Payload Reuse Bugs: Reusing the same Idempotency-Key with a different amount or currency silently returns a stale receipt instead of 422 Unprocessable Entity.
Atomic Idempotency Protocol

Two-Phase Claim & Finalize vs. Concurrent Retry

Mobile / EnvoyBilling APIPostgres 16Stripe / Adyen1. POST /charges (Idempotency-Key:K)2. Tx1: INSERT (K, sha256,IN_PROGRESS)3. Concurrent retry (K) 5ms later4. Unique violation -> 409Retry-After5. Call PSP with K (outside DBTx!)6. Tx2: UPDATE COMPLETED + body

Claiming the unique key in a fast Tx1 before calling the PSP prevents concurrent duplicate charges without holding DB locks for 2.1s.

Engineering Decision Framework
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.
Decision Exercise · Make the Call

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?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

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.

Design Trade-Off

Naive Solution (and Why It Breaks)

Before · Async Primary / Split-Brain
  • Stale leader overwrites state
  • Clock skew breaks lease order
  • Full-table sync on reboot
After · Quorum + Monotonic Fencing
  • Majority quorum prevents split-brain
  • Fencing tokens reject zombies
  • Merkle/WAL catch-up in O(log N)
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

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, compare req_hash (422 on mismatch), return 409 Conflict (Retry-After: 1) if IN_PROGRESS, or replay the cached http_status + response_body if COMPLETED.
  • External PSP Call (No DB Lock Held): Forward idempotency_key to 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. Partition idempotency_keys by hour/day for instant DROP TABLE TTL cleanup of 216M keys/day.
Two-Phase Idempotency Storage

PostgreSQL Authoritative Claim + Partitioned Cache

API + UUIDv4SHA-256 payload checkPostgres Tx1/Tx2UNIQUE(merchant, key)Redis Read-Through<3ms replay cacheDaily Partitions216M keys/day TTL drop

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);
}
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

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_id instead of double-decrementing stock.
  • Webhook & Saga Orchestrators: Makes at-least-once message delivery behave as exactly-once state transitions.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

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?

Recommended Learning Flow