Return to Essays
Backend Engineering7 Min Read

How to build idempotency that survives races, crashes, and bad networks

Published October 30, 2026By Henry A.

Part 1: Architecture, Race Conditions, and Distributed Systems Traps

Key Takeaways (1-Minute Summary)

  • Idempotency is a stateful contract, not a response cache. It guarantees that retrying an operation produces the exact same side-effects as executing it once—even across client retries, network drops, and server crashes.

  • Read-then-write creates a race condition. You cannot "check if key exists, then run." You need an atomic reservation backed by a database unique constraint, scoped per authenticated tenant, and fingerprinted against the payload.

  • External side-effects cannot participate in database transactions. You cannot 2-phase-commit with an external bank or payment gateway. You must propagate a stable idempotency key downstream so third parties deduplicate on their end.

  • PostgreSQL is the source of truth; Redis is the accelerator. If Redis crashes or gets evicted, performance degrades, but data integrity and financial safety remain mathematically intact.

  • An indeterminate failure is NOT a failed payment. A network timeout from a bank or a 5xx does not mean money didn't move. Blindly marking records as failed and re-running them causes duplicate debits.

The ₦50,000 That Left Twice

Picture this: Ada is sitting in a bus in Lagos with one bar of 3G signal. She opens her mobile banking app and taps Send ₦50,000. The app displays a loading spinner for 15 seconds, and then surfaces an alert: "Network error. Transaction failed."

Ada taps Send ₦50,000 again.

Here is what actually happened behind the scenes:

  1. Attempt 1 reached your NestJS API gateway.

  2. Your server processed the request, called the central payment switch, and debited Ada's wallet.

  3. While your server was sending the HTTP 201 Created response back to Ada's phone, the cellular tower dropped the TCP connection.

  4. Ada's client never received the acknowledgment. Because the mobile app was built to handle flaky networks, it automatically retried the request with a fresh HTTP call.

  5. Attempt 2 hit your server. Your server saw a valid payload, authenticated Ada, executed the transfer logic a second time, and debited her wallet another ₦50,000.

Ada has now been debited ₦100,000. Her balance is negative, your support queue has a high-priority ticket, and your accounting team faces an expensive reconciliation dispute with the payment rail.

Article Image

Retries Are Normal Traffic

In social media or content platforms, a duplicate request results in a duplicate comment or like—an annoyance. In financial infrastructure, a duplicate request is an unauthorized movement of capital.

On mobile and distributed clients, retries are standard operating traffic. Network timeouts, proxy resets, and load balancer failovers will continuously replay requests. If your backend cannot guarantee at-most-once execution semantics, you are shipping a system that will inevitably double-spend.

What Idempotency Is (And What It Isn't)

An operation is idempotent if applying it multiple times yields the exact same outcome as applying it once:

f(f(x))=f(x)f(f(x))=f(x)

In HTTP semantics, GET, PUT, and DELETE are defined by RFC 9110 as naturally idempotent. POST is not. When we design an endpoint like POST /payments, we must deliberately engineer idempotency into the application layer.

To prevent bugs, we must distinguish idempotency from two concepts it frequently gets confused with

Dimension

Caching

Deduplication

Idempotency

Primary Goal

Minimize latency and compute.

Drop identical spam or redundant messages.

Enforce exactly-once business side effects.

Identifier

URL, query params, or cache key.

Hash of the message content.

Client-supplied Intent Key (Idempotency-Key).

If Record is Lost

Performance drops; recomputation is safe.

Duplicate message processed.

Disaster: Money is moved twice.

Multiple Identical Payments?

Replaces or skips.

Often drops the second genuine payment.

Allows both, as long as they carry distinct keys.

State Tracking

Binary: hit or miss.

Transient window.

Lifecycle: PROCESSING →→ COMPLETED / FAILED.

An idempotency key represents client intent, not request content. If Ada intentionally sends ₦5,000 to her landlord, and 30 seconds later sends another genuine ₦5,000 to the same landlord, the payloads are identical. However, because they are two distinct financial decisions, the client sends two different Idempotency-Key headers. Both must execute.

The Naive Implementation

Most online tutorials suggest an implementation that looks deceptively simple:

// ❌ NAIVE TUTORIAL CODE — DO NOT USE IN PRODUCTION
@Post()
async createPayment(@Headers('idempotency-key') key: string, @Body() dto: PaymentDto) {
  const cached = await this.redis.get(`idem:${key}`);
  if (cached) {
    return JSON.parse(cached);
  }

  const result = await this.paymentService.processPayment(dto);
  await this.redis.set(`idem:${key}`, JSON.stringify(result), 'EX', 86400);
  return result;
}

This passes unit tests on a developer's laptop. In production under load, it fails immediately.

The Time-of-Check to Time-of-Use (TOCTOU) Race

When two requests carrying the same Idempotency-Key arrive at your server at the same millisecond (e.g., automated client retries or rapid double-taps), they execute concurrently across event loops or worker processes:

Time

Thread A (Request 1)

Thread B (Request 2)

t0t0​

GET idem:key-123 →→ null

t1t1​

GET idem:key-123 →→ null

t2t2​

Calls Payment Gateway (Charges Ada ₦50k)

Calls Payment Gateway (Charges Ada ₦50k)

t3t3​

SET idem:key-123

SET idem:key-123 (Overwrites)

Both threads checked before either wrote. This gap between checking and claiming is the race window where duplicate debits happen.

To solve this, checking and claiming must be a single, atomic operation.

The Core Invariants of Production Idempotency

Before writing code, let's establish the architectural rules that govern our design:

Article Image

Invariant 1: Tenant Scope Isolation

Never allow an idempotency key to be globally unique on its own. If User A generates key: "tx-1001" and User B coincidentally sends key: "tx-1001", User B would either be blocked or, worse, receive User A’s cached payment response. Keys must be strictly scoped to the authenticated tenant and endpoint:

Scope=METHOD:Path:UserIdScope=METHOD:Path:UserId

Invariant 2: Request Fingerprinting

What if an attacker or a buggy client reuses key: "tx-1001", but changes the recipient from Ada to an attacker's account, or changes the amount from ₦5,000 to ₦500,000? We must compute a cryptographic fingerprint (SHA-256) of the canonical payload. If a key is sent with a mismatched fingerprint, the server must reject it with 422 Unprocessable Entity.

Invariant 3: PostgreSQL is the Source of Truth, Redis is the Accelerator

Redis is an in-memory data store. Keys can be evicted under memory pressure, nodes can reboot, or replication can lag. You cannot stake customer funds exclusively on an ephemeral cache. PostgreSQL enforces the ultimate contract via a database UNIQUE constraint. Redis is used solely as a distributed lock to prevent thundering herds and as a fast-path read cache.

Invariant 4: Local Writes Must Commit Atomically

The internal ledger mutation (inserting the Payment record) and updating the IdempotencyKey state to COMPLETED must commit in the exact same database transaction.

Invariant 5: Downstream Idempotency Propagation

Your backend is rarely the end of the line. When you call an external card processor or banking partner, your server acts as the client. You must propagate your internal idempotency reference downstream.

Distributed Systems Traps (What Most Tutorials Skip)

Trap 1: The Crash Window & External Side Effects

Consider this sequence of events:

request ──▶ call bank API ──▶ [ SERVER CRASH ] ──▶ commit DB transaction
                 │
           money moved in bank

If the server crashes after the bank call finishes but before the database transaction commits:

  • The local database rolls back. The record remains in PROCESSING (or is lost).

  • The money has already left the bank account.

  • When Ada retries, the server sees no completed local transaction.

If you don't propagate your idempotency key downstream, the retry will call the bank again and create a double debit. By passing a stable reference downstream, the bank recognizes the retry and responds: "This transfer was already processed. Here is the confirmation reference."

Trap 2: An Indeterminate Timeout Is NOT a Failure

If an HTTP call to a bank gateway times out after 30 seconds, you do not know whether the money moved.

  • If the gateway processed the payment and the response dropped, the money moved.

  • If the gateway dropped the request before processing, the money did not move.

Marking the transaction FAILED and allowing an immediate fresh retry is dangerous. In financial systems, an indeterminate timeout must transition to PENDING_RECONCILIATION or remain locked until a background reconciliation worker verifies the status with the provider.

Summary & What's Next

Idempotency is not an optional optimization—it is the foundational guarantee that makes financial APIs reliable over unreliable networks.

Rule

Production Requirement

Identification

Mandatory Idempotency-Key header (UUIDv4)

Isolation

Unique per (Method, Path, UserId, Key)

Integrity

SHA-256 fingerprint check (reject mismatches with 422)

Concurrency

Atomic distributed lock with heartbeat lease renewal

Source of Truth

PostgreSQL unique constraint (@@unique([scope, key]))

External Calls

Propagate stable idempotency reference downstream

Now that we have established the architectural rules, how do we write the code? how do we implement this in a real application without deadlocks, unhandled promise rejections, or database pool starvation? In Part 2, we’ll build the complete production implementation in NestJS with PostgreSQL and Redis."