Idempotency and Retries

How to retry failed requests without overloading a server or repeating an action, using timeouts, backoff, retry budgets and idempotency keys.

16 minLesson 4 of 8
On this page
  1. Where retries and idempotency fit
  2. Timeouts
  3. Retries with exponential backoff and jitter
  4. Retry storms and retry budgets
  5. Which operations are safe to retry
  6. Idempotency keys
  7. Other ways to make an operation idempotent
  8. Side effects and saved responses
  9. In the interview
  10. What to practise next

A retry is a second attempt at a request that failed or got no answer, and it is how a client copes with brief network and server failures. An operation is idempotent if doing it several times has the same effect as doing it once. Retries are safe only for idempotent operations, so a system that retries needs operations that are idempotent by nature, or a mechanism such as an idempotency key that makes them so.

Without idempotency, a client that sends "charge this card $40" and gets no response cannot know whether the charge happened. If it retries, the customer may be charged twice, and if it does not, the customer may not be charged at all. Unlimited retries cause a second problem: when a server is struggling, thousands of clients retrying at once can keep it from recovering.

Where retries and idempotency fit

The client retries on a timeout, and the API uses a key store to recognise a repeated request before it calls the card processor.Client (retries) to Payments API (POST + key); Payments API to Idempotency keys (claim key); Payments API to Card processor (charge).Client (retries)Payments APIIdempotency keysCard processorPOST + keyclaim keycharge
The client retries on a timeout, and the API uses a key store to recognise a repeated request before it calls the card processor.

Timeouts

A timeout is how long a client waits for a response before giving up. When it fires, the client has learned nothing about what the server did: the request may never have arrived, or the server may have finished and the response may have been lost. A timed-out request is therefore an unknown outcome, not a failure.

Set the timeout a little above the latency that almost all requests have, such as the 99th percentile. Too short, and the client abandons requests that would have succeeded and adds needless retries. Too long, and the client holds a thread for the whole wait and can run out of threads.

Retries with exponential backoff and jitter

A retry policy decides which failures to retry, how long to wait between attempts and when to stop. Retry only failures that can succeed on a later attempt: timeouts, connection resets, 503 and 429. A 400 or 404 will fail the same way again, so retrying it only adds load. If the server sends a Retry-After header, wait at least that long.

Exponential backoff

Waiting a fixed time between attempts keeps pressure on a server that is already struggling. Exponential backoff doubles the wait after each failure, for example 100 ms, 200 ms, 400 ms, up to a cap of a few seconds. Limit the total to a few attempts.

Jitter

When many clients fail at the same moment, backoff alone makes them all retry at the same moments, so the server receives load in synchronised waves. With full jitter each client waits a random time between zero and the current backoff value, which spreads the retries out.

Retry with exponential backoff and full jitter
async function withRetries(call, maxAttempts = 4, baseMs = 100, capMs = 2000) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await call();
    } catch (err) {
      if (!err.retryable || attempt === maxAttempts) throw err;
      const ceiling = Math.min(capMs, baseMs * 2 ** (attempt - 1));
      await sleep(Math.random() * ceiling); // full jitter
    }
  }
}
def with_retries(call, max_attempts=4, base_ms=100, cap_ms=2000):
    for attempt in range(1, max_attempts + 1):
        try:
            return call()
        except RetryableError:
            if attempt == max_attempts:
                raise
            ceiling = min(cap_ms, base_ms * 2 ** (attempt - 1))
            time.sleep(random.uniform(0, ceiling) / 1000)  # full jitter

Retry storms and retry budgets

Retries multiply across layers

A retry storm happens when retries add so much load that a failing service cannot recover. The worst case is retries at several layers. If a client, an API and an order service each make up to 3 attempts at a failed call, a failing database can receive 3 × 3 × 3 = 27 calls for one user request, exactly when it is least able to handle them. The usual fix is to retry at one layer, normally the one that knows how to repeat the whole operation, and let the layers below fail fast.

Retry budgets

A retry budget limits retries to a fraction of normal traffic, for example about 10% of a client's recent requests. When the service is healthy the budget is never reached. When it is failing, the budget caps the extra load and the client returns errors for the rest. The budget is shared by all calls from one client process, because a per-request limit still allows three attempts for every request at once.

Circuit breakers

A circuit breaker stops calls to a dependency that keeps failing and later lets a few test calls through. It limits retry load more strongly than a budget, and is covered in Reliability and Failure.

Which operations are safe to retry

Whether a retry is safe depends on the operation, not on the error. Reads are always safe to retry. An operation that sets a fixed value, such as "set the status to shipped" or a PUT that replaces a whole record, is idempotent. A DELETE of a specific record is too.

An operation that adds or creates something, such as "add $40 to the balance" or a POST that creates an order, changes the state on every repeat, so it needs one of the techniques below.

Idempotency keys

An idempotency key is a unique value that the client attaches to a request and reuses on every retry of it. The server remembers which keys it has processed and what it answered, so a repeated key returns the saved answer instead of repeating the work. This makes any operation, including a payment, safe to retry.

Who generates the key

The client generates the key, usually a random UUID, once per user action such as one press of "Pay", and sends the same value on every attempt. The server cannot generate it, because only the client knows that two requests are the same action. The key must be created before the first attempt and outside the retry loop, because a key created inside the loop makes every attempt a new payment.

What the server stores and the atomic insert

For each key the server stores the key itself, the owner of the key (such as the account id), a state (in progress or completed), a fingerprint of the request, and the saved response once there is one. The server must claim the key with a single atomic operation. A database unique constraint does this: the server tries to insert the key, and only one of several concurrent attempts succeeds.

Claiming a key atomically
INSERT INTO idempotency_keys (account_id, key, request_hash, state, created_at)
VALUES (:account_id, :key, :request_hash, 'in_progress', now())
ON CONFLICT (account_id, key) DO NOTHING;
-- 1 row inserted: this attempt does the work. 0 rows: read the existing row.

Checking whether the key exists and then inserting it in a second step does not work. Two retries that arrive together can both find that the key is missing, and both then do the work. The insert and the check have to be the same statement.

The in-progress state

A retry can arrive while the first attempt is still running, for example when the client's timeout is shorter than the processing time. The server finds the key in progress and must not start the work again. It usually answers with 409 Conflict so the client tries again shortly, or it waits briefly for the first attempt and returns its result.

If the first attempt crashes after charging the card but before saving the result, the key stays in progress and every retry gets a conflict. To avoid this, the claim carries a lease of some seconds. After the lease expires, a retry takes over and repeats the work. This is safe only if the downstream system accepts the same key, as in the tracer below, so that it returns the original charge. Otherwise a background job must ask it what happened first.

The request fingerprint

The server also stores a hash of the request body and compares it with any later request that uses the same key. The same key with a different amount is a client bug, so the server rejects it, commonly with 422, instead of returning the answer to a different request.

How long keys are kept

Keys must be kept longer than any client keeps retrying the same action. A day is a common choice for payment APIs. After that the key is deleted.

A lost response, a retry, one chargeUse the arrows or ← → keys
  1. A lost response, a retry, one charge, step 1Shop app to Payments API (POST /charges); Payments API to Idempotency keys; Payments API to Card processor.Shop appPayments APIIdempotency keysCard processorPOST /charges
    charges
    0

    1The user taps Pay. The app creates key k-7f3 and sends POST /charges for $40 with it.

  2. A lost response, a retry, one charge, step 2Shop app to Payments API (POST /charges); Payments API to Idempotency keys; Payments API to Card processor.Shop appPayments APIIdempotency keysk-7f3 startedCard processorPOST /charges
    charges
    0

    2The API inserts k-7f3 as "in progress". The insert succeeds, so this attempt owns the work.

  3. A lost response, a retry, one charge, step 3Shop app to Payments API (POST /charges); Payments API to Idempotency keys; Payments API to Card processor.Shop appPayments APIIdempotency keysk-7f3 doneCard processorcharged $40POST /charges
    charges
    1

    3It charges $40, passing the same key to the processor, and saves the response under the key.

  4. A lost response, a retry, one charge, step 4Shop app to Payments API (POST /charges); Payments API to Idempotency keys; Payments API to Card processor.Shop apptimeoutPayments APIIdempotency keysCard processorPOST /charges
    charges
    1

    4The reply is lost. After 2 seconds the app times out and does not know whether the charge happened.

  5. A lost response, a retry, one charge, step 5Shop app to Payments API (POST /charges); Payments API to Idempotency keys; Payments API to Card processor.Shop appretry, k-7f3Payments APIIdempotency keysCard processorPOST /charges
    charges
    1
    attempts
    2

    5The app waits a random time and resends with the same key. A new key would mean a new charge.

  6. A lost response, a retry, one charge, step 6Shop app to Payments API (POST /charges); Payments API to Idempotency keys; Payments API to Card processor.Shop appPayments APIIdempotency keysseen: replayCard processorPOST /charges
    charges
    1
    attempts
    2

    6The API finds k-7f3 completed and returns the saved response. The processor is not called again.

1 / 6

Other ways to make an operation idempotent

An idempotency key needs a key store on the write path, and it needs the client to cooperate. Some operations can be made idempotent without either.

Conditional writes

A conditional write applies a change only if the record is still in the expected state, for example UPDATE orders SET status = 'SHIPPED' WHERE id = 7 AND status = 'PAID', or a write that checks a version number. A repeat matches zero rows and changes nothing. This suits state machines, where an order moves from paid to shipped only once. The weakness is that zero rows changed can mean the change was already applied or that another writer changed the row, so the code must read the row to tell a duplicate from a real conflict.

Natural keys and unique constraints

Sometimes the data already identifies the action, such as an order number or a booking made of a user and a slot. A unique constraint on that value makes the second insert fail, and the code treats the failure as "already done". The identifier must be stable across retries, so it has to come from the client or the business data and not be generated by the server on each attempt.

Deduplication on the consumer

Message queues and streams usually deliver each message at least once: if a consumer crashes or does not acknowledge in time, the broker redelivers it. Consumers therefore deduplicate. Each message carries a unique id, and the consumer records that id in the same transaction as the message's effect and skips ids already recorded. Recording it in a separate step would let a crash lose the message or process it twice. The table of ids must be kept longer than the longest redelivery delay. At-least-once delivery combined with this deduplication gives an effect equivalent to exactly-once processing, even though the broker itself can still deliver a message twice. Queues are covered in Message Queues and Streams.

Side effects and saved responses

Side effects outside the database

If the handler also sends an email and crashes before saving the result, the retry sends it again. Pass the key to any downstream service that supports one, or write an outbox row in the same transaction as the key so one worker performs the side effect once.

Which responses to save

A saved response is replayed to every retry, so saving a transient failure such as a 503 would make the client see it forever. Save completed results, including a definitive refusal such as "card declined". For a failure that may succeed later, release the key so a retry runs the operation again.

In the interview

Raise idempotency whenever a client can repeat an action with side effects, such as a payment, an order or a message. For client-facing writes the answer is an idempotency key, and for state changes inside a database it is often a conditional write.

Questions to expect:

  • "What stops a double charge when the client retries?" The client sends one idempotency key per payment on every attempt. The server claims the key with an atomic insert before charging, so only one attempt does the work and a repeat gets the stored response. The key is also passed to the card processor, which covers a crash between the charge and saving the result.
  • "Who generates the key, and when?" The client, once per user action and before the first attempt, because only the client knows that two requests are the same action.
  • "What if the server crashes after charging but before saving the result?" The key stays in progress, so it needs a lease. After the lease expires a retry takes over and calls the processor with the same key, which returns the original charge. A processor without key support has to be queried for the charge first.
  • "Can a message queue give you exactly-once processing?" The broker delivers at least once, so a consumer can see the same message twice. The consumer stores each message id in the same transaction as the message's effect and skips ids it has seen, which makes the effect happen once.
  • "How do you stop retries from overloading a struggling service?" Use exponential backoff with jitter, a cap on attempts and a retry budget, and retry at one layer only. A circuit breaker then stops calls to a dependency that is clearly down.
The double chargeStrong answer
Interviewer

The client times out on a payment request and retries. What stops a double charge?

You

The client creates one idempotency key per checkout attempt and sends it on every retry. The server inserts the key under a unique constraint before it charges the card, so only one attempt does the work, and a repeat gets the stored response. I would also pass the key to the card processor, so that a crash after the charge does not lead to a second one.

Interviewer

What if the retry arrives while the first request is still running?

You

The key is still marked in progress, so the server answers with a conflict and the client retries after a short delay. The key has a lease, so if the first attempt died, a later retry can take over.

Quick check

A payment client times out and sends the request again. Where should the idempotency key be created?

Two retries with the same key reach the server at the same moment. Which design lets only one of them do the work?

What to practise next

Read about circuit breakers and load shedding in Reliability and Failure, and see idempotency keys used in a full design in Design a Payment System.