Core Concepts

Idempotency

Make retries safe when the first request may already have charged, reserved, or changed something.

Free~14 min

An idempotent operation has the same intended effect when repeated. A retry can reach the server after the first request already succeeded. If a repeat could create a second charge or job, give both attempts the same operation identity and enforce it where the change takes effect.

HTTP methods by idempotency

MethodIntended effect of repeating the same request
GETReads the resource again. The value can change between reads.
PUTStores the supplied representation at the same location again.
DELETELeaves the resource absent. A later response may say it is already gone.
POSTThe API defines the action. A charge endpoint can create a separate charge per request unless it recognizes retries.
PATCHThe patch defines the action. Setting a field to Alex is repeatable. Appending Alex to a list can add it twice.

HTTP defines safe methods such as GET, plus PUT and DELETE, as idempotent. This applies to the effect the caller requests. A server can still log each attempt separately. An API can also make a specific POST or PATCH safe to repeat.

Sources: HTTP semantics, section 9.2.2 . HTTP PATCH, section 2

Three delivery semantics

The first request might have reached the server even if the response never made it back. A new application request after that timeout is a separate attempt. TCP retransmits missing bytes within a connection. It cannot tell the application whether a charge committed.

  • At-most-once delivery permits loss and exposes a message at most once. Sending once without retry is one way to accept that tradeoff.
  • At-least-once delivery uses retries or replay to recover missing work when the system recovers. The same message may reach the handler more than once, for example when the first acknowledgment is lost.
  • Exactly-once effects require a specified boundary. A database can use an atomic commit to apply one change for a request key even if the handler runs more than once. Kafka can commit an output record and input progress in one Kafka transaction. A payment outside that transaction needs its own protection.

Sources: TCP, section 2.2

The conditional write as dedup boundary

Suppose Pay spends credits stored in our own database. The client sends the same request key on both attempts. A separate lookup leaves a race. Two workers can look up the key at the same time, both see no record, and both debit the balance.

A conditional write succeeds only when a condition is still true. Put a unique constraint on the account and request key. In one transaction, claim the key, debit the balance, and record the outcome. One transaction can commit that change. A competing attempt reads the committed record and returns its outcome if the input matches.

The stored result in this figure is the effect being protected. Try the same race with a local charge and check that the charge count stays at one when the operation uses the key.

A result row does not protect a charge sent to a separate payment provider. That call could succeed before the worker crashes, while the result row remains empty. Save a stable provider operation key before the call and send it on every attempt. Keep uncertain outcomes pending and look them up or reconcile them with the provider before issuing another charge. Stripe idempotent requests describes one provider's retry contract.

For expensive jobs, recording a claim before dispatch can avoid duplicate computation. Make sure the job is recoverable if the process stops after saving the claim and before handing off the work. A worker can claim a durable pending job and then commit the result once.

Choose the key before the first attempt

The client can generate a key before sending the request or obtain a token from the server ahead of time. If the server only returns the identity in the response to the operation, a lost response leaves the client without it.

Keep the key alongside the pending operation and reuse it on retry. Retain it across a reconnect or reload if the client offers to resume. In ChatGPT, the client supplies the retry ID and the server still assigns its own ID when it accepts the turn.

Natural keys vs random UUIDs

Use a business identifier when it names one intended operation. An order number can identify a single final payment for an order. A content hash can identify a file by its bytes.

Use a random UUID when the same inputs can represent separate actions. Two deliberate purchases of the same item need different keys. A well-generated random UUID makes collisions unlikely. UUID collision resistance

Scope a key to its owner and operation. Compare the repeat request with the input stored for that key. Keep the record for as long as you accept retries or replay. For an effect that must stay unique beyond that period, keep a lasting business constraint.

Building idempotency at each layer

Place the check where it can protect the effect. An earlier check can still save work.

At the gateway, read the request key and look up an existing result in shared state. That can shorten a retry. Keep the service-side transaction or provider check for cases that reach the actual operation twice.

At the service, use a durable store to make the operation record and local business change commit together. If Redis only holds a derived result, a command such as SET result:key value NX protects that key while it is present. The durable operation still needs its own constraint.

At the queue boundary, a consumer that stops before saving its progress can process the same message again. A repeat should use the same business-operation key. In Batched Inference, the conditional result write chooses one visible result even if a replacement worker repeats the computation.

At the state machine: when the side effect is an ordered transition, the state itself rejects duplicates. Online chess gives every move a seq: N and applies it only when seq == serverSeq + 1.

When at-most-once is the right answer

Some measurements can tolerate an occasional missing event. A service counting routine requests may choose a low-cost delivery path without per-event retries. That tradeoff depends on what the data is for. An audit trail or a usage record used for billing may need durable delivery and replay.

Compare the cost of a missed effect with the cost of repeating it. A charge needs a recovery path that can resolve an unknown outcome while honoring the original operation key.

See also

  • Kafka - shows how a transaction commits a retained output and a consumer group's progress together.
  • Transactional Outbox - records work to publish in the same transaction as a business change. The consumer handles repeat delivery.
  • Saga Pattern (forthcoming) - explains how to retry steps and compensations when several services must act.

Used in

  • ChatGPT - the client sends a clientTurnId before submitting. A matching retry gets the saved server turn ID and stream URL. Reusing the client key for different input returns a conflict.
  • Batched Inference Service - the result store keeps the first result for a request while its result key exists, even if replay repeats the model call.
  • Online Chess - the per-game serverSeq monotone counter makes a replayed move a no-op: the server applies a move only when seq == serverSeq + 1, so a duplicate after reconnect is dropped before it touches game state.
  • Prompt Playground - the sweep and cell coordinates identify which requests belong to the same intended model run.
  • Crossword Solver - the puzzle identity lets repeated submissions and reprocessed jobs find a shared result.
  • Web Crawler (Distributed) - storing bytes under their content hash gives repeated fetches of the same bytes the same destination.

Done reading? Mark it so it sticks in your dashboard.

Discussion