Skip to the workspace
Pebellslearn by building
Robust Endpoints  ›  Lesson

Idempotency

Idempotency 14 minAn idempotent operation has the same effect whether it runs once or many times, and non-idempotent operations such as payments use an idempotency key so a retry is applied only once.

api design / Idempotency

Explore each scene at your own pace.

01 · The rule

The rule

Idempotency

A member taps "Pay fine" on a train. The request reaches BookNook and the payment goes through, but the tunnel swallows the response. The app sees a timeout and retries. Did the member just pay twice? Idempotency is what lets a client retry without fear.

The rule

Same request twice, same result as once.

An operation is idempotent if repeating it leaves the server in the same state as doing it once. The response may differ, but the effect does not.

  • GET /v1/books/42: reading changes nothing. Idempotent (and safe).
  • PUT /v1/books/42 with a full book: the second replace writes the same thing. Idempotent.
  • DELETE /v1/loans/901: after the first call the loan is gone; the second may return 404, but the state is the same. Idempotent.
  • POST /v1/payments: each call creates a new payment. Not idempotent.
  • PATCH depends on the change: "set shelf to C2" is idempotent; "add 1 to the renewal count" is not.

For operations that are not naturally idempotent, the client sends an idempotency key: a unique value it generates once per intended action and reuses on every retry of that action.

POST /v1/payments HTTP/1.1
Idempotency-Key: 5f2b8e0c-6a3d-4c1e-9b7a-2d4e8f1a0c93
Content-Type: application/json

{"fine_id": 312, "amount": 150}

The server records the key with the result of the first successful attempt. When the same key arrives again, it does not charge again; it returns the stored response. Keys expire after a window, say 24 hours. If the same key comes back with a different body, that is a client bug, and the server should refuse it rather than guess, often with 422 or 409.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.