Skip to content
Optimal Lab

System Design · interactive

Idempotency and request deduplication

Networks lose responses. When that happens the client can't know whether the payment went through, so it retries. Without a way to spot the retry, the customer pays twice.

Client

Network

Payment server

  1. client

    POST /charge $50

Card statement

  • nothing yet

Idempotency keys stored

  • not used

POST /charge $50 The client sees: waiting…

Request

step 1 of 5

Step 1 of 4

  1. 1

    The client sends a unique key with the request

    A random id made once per purchase, not once per attempt. Retries reuse it.

    No key sent.

  2. 2

    The server records the key with the result

    Store the key and the outcome in the same transaction as the charge, so the two can't disagree.

    Nothing is recorded that identifies this attempt.

  3. 3

    The client retries with the same key

    Timeouts are ambiguous: the request may or may not have run. Retrying is right, as long as it's safe to repeat.

    Retry with exponential backoff, and the same key every time.

  4. 4

    A seen key returns the saved result

    The server does no new work: it replays the first response. The operation becomes idempotent: doing it twice equals doing it once.

    Keep stepping.