HardPremium

API Idempotency & Distributed Systems

How do you ensure a payment API does not charge a customer twice if the network fails halfway through?
30 min read14 Jan 2026

Solution

The Idempotency Key Pattern

  1. Client Responsibility: The client generates a unique ID (UUID v4) called an Idempotency-Key and sends it in the header of the request.
  2. Server Responsibility: * Before processing, the server checks a key-value store (like Redis) for this key.
    • If found: It returns the cached response immediately without talking to the bank.
    • If not found: It processes the payment, saves the response in the cache with the key, and returns the result.

Atomic Operations

The check-and-set operation in the database must be atomic to prevent race conditions where two parallel requests with the same key slip through.