When nodes partition or reboot past retry windows, because distributed networks only guarantee at-least-once delivery, every mutating API and consumer must pair a client-generated idempotency key with an atomic database/transaction check—not a separate read-then-write.
TL;DR30-second simplified summary▾
Core Mechanics: In distributed systems, timeouts are ambiguous: when a client or Kafka consumer times out waiting for an ACK, it cannot tell whether the server crashed before processing or after committing.
Visual & Structural Flow: Depicts Idempotency Key State Machine (With Crash-Safe Lease) (IN_PROGRESS -> COMPLETED -> 409 / 422 REJECT); Stripe-Pattern Idempotency Handling Timeout & Retry (Mobile Client -> Checkout API -> Postgres Idem).
Trade-Offs & Production: Choose your deduplication store based on whether the business mutation lives in an ACID database. When an idempotent API must call an external gateway (like Stripe), hold the database transaction open only for the fast IN_PROGRESS insert, execute the external call with the.
Failure Modes & Application: Explore concrete production problems on duplicate charges, SQS visibility timeouts, and Kafka exactly-once fencing.
outbox table inside the exact same ACID database transaction as the business state change, then relaying them asynchronously to Kafka/RabbitMQ.What is Idempotency & Deduplication.
Why this matters: The mechanism: understand how Idempotency & Deduplication works from first principles.
In distributed systems, timeouts are ambiguous: when a client or Kafka consumer times out waiting for an ACK, it cannot tell whether the server crashed before processing or after committing. Idempotency guarantees that repeating the same logical request yields the exact same side effect as executing it once.
Clients generate a unique Idempotency-Key (UUIDv4) before the first attempt and reuse that exact key on all retries. The server atomically records (key, request_hash, status) and caches the original response.
Idempotency Key State Machine (With Crash-Safe Lease)
A 30s lease on IN_PROGRESS prevents a crashed worker from leaving an idempotency key wedged forever.
Why Check-Then-Act & Dual-Writes Break Under Concurrency.
Why this matters: The problem: see what breaks without Why Check-Then-Act & Dual-Writes Break Under Concurrency under real concurrency or scale.
Think of Why Check-Then-Act & Dual-Writes Break Under Concurrency as the intuition layer for Idempotency & Deduplication: The problem: see what breaks without Why Check-Then-Act & Dual-Writes Break Under Concurrency under real concurrency or scale.
Doing SELECT * FROM idem WHERE key = ? followed by INSERT has a classic check-then-act race: two concurrent double-clicks both see empty, both charge the card, and both insert. Similarly, checking Redis for dedup before committing Postgres creates a split-brain window if the pod crashes between Redis and Postgres.
Why Check-Then-Act & Dual-Writes Break Under Concurrency
- Problem
- How to implement Idempotency & Deduplication 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
- When nodes partition or reboot past retry windows, because distributed networks only guarantee at-least-once delivery, every mutating API and consumer must pair a client-generated idempotency key with an atomic database/transaction check—not a separate read-then-write.
- Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When Idempotency & Deduplication experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Payload Hash Validation
Store request_hash = SHA256(method + path + canonical_body). Reusing the same Idempotency-Key with a different amount must return 422 Unprocessable Entity, not silently replay the old charge.
Same-DB Atomic Transaction
For Kafka/SQS consumers, INSERT INTO processed_events(event_id) ON CONFLICT DO NOTHING inside the same ACID transaction as the business update guarantees exactly-once state.
Where Idempotency Keys Are Mandatory (and Where They're Redundant).
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Think of Where Idempotency Keys Are Mandatory (and Where They're Redundant) as the intuition layer for Idempotency & Deduplication: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Add explicit idempotency keys to non-idempotent mutations (POST) and at-least-once consumers; skip them on reads and natural full-replacements.
| Choice | What it buys | What it costs |
|---|---|---|
| Mandatory: Payment & Ledger `POST` APIs | Stripe-style `Idempotency-Key` prevents double-charging on mobile network drops and client retries. | Requires TTL pruning (7–30 days) on the idempotency table to bound index size. |
| Mandatory: Kafka / SQS At-Least-Once Consumers | Absorbs consumer rebalances and SQS visibility-timeout redeliveries cleanly. | Adds 1 unique-index insert per consumed message. |
| Redundant: `GET` / `HEAD` or Full `PUT` Replacement | `PUT /users/42` or `DELETE /sessions/9` is already naturally idempotent. | Adding idempotency-key storage on reads wastes write IOPS. |
Atomic Postgres Idempotency Guard with Payload Hash.
Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.
Think of Atomic Postgres Idempotency Guard with Payload Hash as the intuition layer for Idempotency & Deduplication: Operational control: configure bounds, failure handling, and safe production defaults.
Use INSERT ... ON CONFLICT DO NOTHING RETURNING id inside the ACID transaction (for consumer dedup) or with a short locked_until lease when wrapping external side effects.
Atomic Postgres Idempotency Guard with Payload Hash
-- Atomic consumer deduplication inside the same PostgreSQL transaction
BEGIN;
WITH ins AS (
INSERT INTO processed_events (event_id, processed_at)
VALUES (:event_id, NOW())
ON CONFLICT (event_id) DO NOTHING
RETURNING event_id
)
UPDATE ledger_accounts
SET balance_cents = balance_cents + :delta_cents
WHERE account_id = :account_id
AND EXISTS (SELECT 1 FROM ins);
COMMIT;
Alternatives: Same-DB ACID Table vs. Redis Dedup vs. Conditional Put.
Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.
Think of Alternatives: Same-DB ACID Table vs. Redis Dedup vs. Conditional Put as the intuition layer for Idempotency & Deduplication: The trade-off: compare competing approaches across latency, consistency, and operational cost.
Choose your deduplication store based on whether the business mutation lives in an ACID database.
Alternatives: Same-DB ACID Table vs. Redis Dedup vs. Conditional Put
| Choice | What it buys | What it costs |
|---|---|---|
| Same-DB ACID Table (`ON CONFLICT DO NOTHING`) | Zero dual-write split-brain; if the business tx rolls back, the dedup key rolls back too. | Adds write IOPS to primary OLTP DB; needs daily partition drops for TTL cleanup. |
| Redis `SET key val NX EX` | Sub-millisecond checks and automatic TTL expiration with zero SQL index bloat. | Async replication can lose keys on failover, and Redis+DB is a dual-write unless paired carefully. |
| DynamoDB `attribute_not_exists(pk)` | Single-request conditional write with native TTL attribute expiration. | Requires `TransactWriteItems` if updating a separate business item atomically. |
Production Payment API: Atomic Lock -> External Call -> Cached Replay.
Why this matters: Production architecture: see how the components compose end to end under real load.
Think of Production Payment API: Atomic Lock -> External Call -> Cached Replay as the intuition layer for Idempotency & Deduplication: Production architecture: see how the components compose end to end under real load.
When an idempotent API must call an external gateway (like Stripe), hold the database transaction open only for the fast IN_PROGRESS insert, execute the external call with the same downstream idempotency key, then commit COMPLETED + cached response.
Stripe-Pattern Idempotency Handling Timeout & Retry
Caching the original response body lets retries succeed identically without re-executing the charge.
Idempotent APIs, SQS Retries & Distributed Locking.
Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.
Think of Idempotent APIs, SQS Retries & Distributed Locking as the intuition layer for Idempotency & Deduplication: Applied problems: connect these internals to concrete system design and debugging scenarios.
Explore concrete production problems on duplicate charges, SQS visibility timeouts, and Kafka exactly-once fencing.
Idempotent APIs, SQS Retries & Distributed Locking
- 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)
Practice: Make the trade-off yourself.
A client sends `POST /v1/charges` with `Idempotency-Key: k1` and `amount: 5000`, which succeeds. Later, a buggy client retries with the *same* `Idempotency-Key: k1` but `amount: 9000`. What should the server do?