Skip to content

Lesson 6 of 9 · 28m

Idempotency and Concurrency: Retries Without Double Charges

Idempotency keys, conditional requests with ETags, unique constraints, and the exact behaviors needed when networks retry.

Every network client retries. Sometimes the user double-clicks, sometimes the mobile SDK retries after a tunnel drops, sometimes your own load balancer replays a request after a timeout. If mutation endpoints are not idempotent, duplicates are not an edge case; they are the normal case.

Idempotency keys make unsafe POSTs replayable

POST /payments HTTP/1.1
Idempotency-Key: 01JZX8S7N2ZKJ7M0X8QM6YP7YB
Content-Type: application/json

{"invoice": "inv_9Zk2", "amount": 12900, "currency": "usd"}

On first execution, store the key, the request fingerprint, the resulting status code, and the response. On retry, return the stored result instead of running the operation again. If the same key arrives with a different payload, reject it:

HTTP/1.1 422 Unprocessable Content

{"code": "idempotency_key_reused", "detail": "This key was already used with a different request body."}

The key should have a defined retention window. Twenty-four hours is common for payment-style APIs; longer may be necessary for asynchronous imports.

The database is your last line of defense

Application-level checks are races. Two requests can both see "no payment exists" before either commits. Back idempotency with unique constraints:

CREATE UNIQUE INDEX payments_idempotency_key_uq
ON payments (account_id, idempotency_key);

CREATE UNIQUE INDEX invoice_open_payment_uq
ON payments (invoice_id)
WHERE status IN ('pending', 'requires_action');

When the constraint fires, translate it into the correct domain response or fetch the winner and return its representation. Do not surface a naked database conflict.

ETags turn updates into compare-and-swap

For collaborative resources, idempotency is not enough because two different updates can overwrite each other. Use entity versions:

GET /projects/prj_88Kd
ETag: "41"
PATCH /projects/prj_88Kd
If-Match: "41"

{"name": "Customer Portal"}

If the stored version is still 41, apply the patch and increment it. If not, return 412 Precondition Failed and let the client re-read. Strongly prefer numeric internal versions or content hashes over timestamps; clock precision and replication make timestamps unreliable.

Async work still needs exactly-once effects

You cannot truly execute a distributed operation exactly once. You can make the observable effect idempotent. A worker consuming payment.capture.requested should write capture_attempts keyed by payment and attempt, ignore completed states, and make downstream calls with provider idempotency keys.

request accepted (202)
  -> durable job row created
  -> worker executes with provider key
  -> state transition recorded exactly once

The durable job row matters. Retrying from a queue without a database state transition creates ghosts when workers crash after the external call but before acknowledgement.

Field notes

  • Do not hash only the body for an idempotency fingerprint unless method, path, and account context cannot vary; include the meaningful request scope.
  • Keys should expire, but expiry behavior must be documented.
  • PUT is naturally idempotent only if the client sends the complete replacement; partial JSON bodies are usually PATCH.
  • Test the nasty case: kill the server after committing the database write but before sending the response.

Was this lesson helpful?

Sign in to rate