← Back to Home

🔁 Idempotency, Retries, Timeouts and Backoff

Duplicate charges reproduced and fixed with idempotency keys, timeouts and hedged requests measured, a retry storm that outlives its cause, and why backoff needs jitter.

Every call across a network can end three ways: it worked, it failed, or you don't know. The third outcome is the one that matters. A request times out: did the server never get it, or did it charge the card and lose the response on the way back? The client can't tell, and the obvious response, retrying, is right only if retrying is safe.

This article is about making it safe, and about retrying without making things worse. It reproduces duplicate payments against a real API on PostgreSQL and fixes them with idempotency keys. It also measures how timeouts and hedged requests cut tail latency, simulates a retry storm that keeps a service down after its problem has gone away, and compares backoff strategies.

It connects to earlier pieces: TCP showed how long a connect can hang without a timeout, rate limiting covered the server side of overload, and messaging delivers messages at least once, which needs the same idempotency techniques.

The Unknown Outcome

When a request times out, any of these may have happened:

  1. The request never reached the server.
  2. The server received it and crashed before doing the work.
  3. The server did the work, and the response was lost or is still on its way.

From the client's side these look identical. Retrying is correct in cases 1 and 2 and harmful in case 3, if the operation isn't safe to repeat.

You can't solve this by being clever with acknowledgements: no protocol over an unreliable network can guarantee both sides agree on whether something happened exactly once. What you can build is at-least-once delivery (retry until you get an answer) combined with idempotent processing (doing it twice has the same effect as doing it once). Together they give the effect of exactly-once, which is what people actually need.

Which Operations Are Safe to Repeat?

An operation is idempotent if performing it many times has the same effect as performing it once. HTTP defines which methods should be:

Method Idempotent? Example Effect of a duplicate
GET, HEAD Yes (and safe: no side effects) Fetch an order None
PUT Yes Set the shipping address to X Address is still X
DELETE Yes Delete order 42 Order 42 is still deleted (the second call may return 404, which is fine)
POST No Create a charge A second charge
PATCH Depends Increment a counter (no); set a field (yes) Depends

The pattern: operations that set state are idempotent; operations that change state relative to its current value (append, increment, create) are not. balance = 100 can run twice; balance = balance + 10 can't.

Idempotent isn't the same as order-independent. Two PUTs with different values, retried and reordered, can still leave the wrong one last. Version checks (below) handle that.

Duplicate Charges, Reproduced

A small Flask API stores charges in PostgreSQL. The test hook delays the response after the charge has been committed: a slow network, a garbage-collection pause, or a load balancer that drops the connection. The client uses a 0.5-second timeout and retries up to four times, the way many HTTP client wrappers do:

@app.post("/charges")
def charge_naive():
    body = request.get_json()
    conn = pool.getconn()
    try:
        with conn, conn.cursor() as cur:
            cur.execute("INSERT INTO charges (customer, amount) VALUES (%s, %s) RETURNING id", (body["customer"], body["amount"]))
            cid = cur.fetchone()[0]
    finally:
        pool.putconn(conn)
    maybe_slow()                              # the response is slow (or lost) AFTER the money moved
    return jsonify(id=cid, amount=body["amount"]), 201
1. Naive POST, server answers slowly (0.8 s) after committing; client timeout 0.5 s, up to 4 attempts
    attempt 1: timed out after 0.5s, retrying
    attempt 2: timed out after 0.5s, retrying
    attempt 3: timed out after 0.5s, retrying
    attempt 4: timed out after 0.5s, retrying
   client result: None after 4 attempts | charges in DB (count, total cents): (4, 10000)

The client reports failure. The customer was charged four times: $100 for a $25 order. Worse is the case where the server recovers after two slow responses:

2b. Naive POST under the same conditions, for comparison
    attempt 1: timed out after 0.5s, retrying
    attempt 2: timed out after 0.5s, retrying
   client result: 201 {'amount': 2500, 'id': 3} after 3 attempts | charges in DB: (3, 7500)

The client sees a clean 201 Created, logs success, and moves on. The customer was charged three times, and nothing in the client's logs suggests a problem.

Idempotency Keys

The standard fix, used by Stripe, PayPal, Adyen and most payment APIs: the client generates a unique idempotency key for each logical operation (one payment, not one HTTP attempt) and sends it with every retry. The server remembers keys it has seen, with the response it gave, and replays that response instead of doing the work again.

CREATE TABLE idempotency_keys (
    key           text PRIMARY KEY,
    request_hash  text NOT NULL,
    status        text NOT NULL,            -- 'processing' or 'done'
    response_code int,
    response_body jsonb,
    created_at    timestamptz DEFAULT now()
);

The endpoint:

@app.post("/v2/charges")
def charge_idempotent():
    key = request.headers.get("Idempotency-Key")
    if not key:
        return jsonify(error="Idempotency-Key header required"), 400
    body = request.get_json()
    req_hash = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
    conn = pool.getconn()
    try:
        with conn, conn.cursor() as cur:
            # Claim the key. Exactly one concurrent request can insert it; the rest see the existing row.
            cur.execute("""INSERT INTO idempotency_keys (key, request_hash, status) VALUES (%s, %s, 'processing')
                           ON CONFLICT (key) DO NOTHING""", (key, req_hash))
            if cur.rowcount == 1:
                cur.execute("INSERT INTO charges (customer, amount) VALUES (%s, %s) RETURNING id", (body["customer"], body["amount"]))
                resp = {"id": cur.fetchone()[0], "amount": body["amount"]}
                cur.execute("UPDATE idempotency_keys SET status = 'done', response_code = 201, response_body = %s WHERE key = %s",
                            (json.dumps(resp), key))
                code = 201                    # charge and key are committed together, or not at all
            else:
                cur.execute("SELECT request_hash, status, response_code, response_body FROM idempotency_keys WHERE key = %s", (key,))
                h, status, code, stored = cur.fetchone()
                if h != req_hash:
                    return jsonify(error="Idempotency-Key reused with a different request"), 422
                if status != "done":
                    return jsonify(error="request with this key is still in progress"), 409
                resp = stored
    finally:
        pool.putconn(conn)
    maybe_slow()
    return jsonify(resp), code

The same three scenarios:

2. Same, with an Idempotency-Key (one key per logical payment, reused on every retry); server recovers after 2 slow responses
    attempt 1: timed out after 0.5s, retrying
    attempt 2: timed out after 0.5s, retrying
   client result: 201 {'amount': 2500, 'id': 1} after 3 attempts | charges in DB: (1, 2500)

3. Ten identical retries arrive at the same instant (fast server)
   status codes: [201, 201, 201, 201, 201, 201, 201, 201, 201, 201] | charges in DB: (1, 2500)
   a later retry gets the stored response: 201 {'amount': 2500, 'id': 1}

4. Same key, different request body
   422 {'error': 'Idempotency-Key reused with a different request'} | charges in DB: (1, 2500)

One charge each time. The details that make it correct:

And the decisions you need to make:

Other Ways to Be Idempotent

Idempotency keys are general, but often the data model gives you idempotency for free:

Technique Example How duplicates are absorbed
Natural unique keys INSERT INTO payments (order_id, …) with UNIQUE (order_id) The second insert fails or does nothing (ON CONFLICT DO NOTHING)
Set, don't increment UPDATE stock SET quantity = 7 instead of quantity - 1 Repeating it sets 7 again
Conditional updates UPDATE accounts SET balance = 90, version = 8 WHERE id = 1 AND version = 7 A repeat finds version 8 and updates nothing
Deduplication table A message consumer records each processed message ID, in the same transaction as its work A redelivered message is skipped
Upserts with timestamps Apply an event only if its timestamp is newer than what's stored Old and duplicate events are ignored

The deduplication table (sometimes called an inbox) is how you make message consumers safe. RabbitMQ, Kafka and SQS all deliver at least once, so every consumer will eventually see a duplicate.

Timeouts: Every Call Needs One

A call without a timeout can wait forever: #0034 measured a connect() that took 134 seconds to give up on Linux defaults. Meanwhile the thread, connection and memory serving that request are stuck, and enough stuck calls take the whole service down. That's how one slow dependency causes a cascading failure.

Most HTTP clients have no timeout by default: Python's requests, Go's http.Client{}, and Java's HttpURLConnection all wait forever unless told otherwise. Set them explicitly, and distinguish:

How long should a read timeout be? Look at the dependency's latency percentiles. A timeout below its p99 causes a steady 1% of timeouts and retries even when everything is healthy. A timeout far above its p99.9 adds nothing but waiting. A common starting point is a little above the p99.9.

Deadlines should shrink as they travel inward. If the user-facing request has 2 seconds, a service that has spent 1.5 seconds already should give its downstream call at most 0.5 seconds, not a fresh 2 seconds. gRPC does this automatically by passing the remaining deadline with each call; with HTTP, pass it in a header. A server that knows its caller's deadline can also refuse work that can't finish in time, which turns out to be crucial below.

Timeouts and hedging against slow outliers

Timeouts also fight tail latency. A server where 2% of requests stall for one second (a GC pause, a slow disk, a noisy neighbour on the same host) and the rest take 10 ms. 2,000 requests from 8 concurrent clients:

strategy                   |   p50   |   p99   |  p99.9  |   max   | server requests per call
no timeout                 |  12.5ms |  1003ms |  1009ms |  1014ms | 1.000
100 ms timeout + 1 retry   |  14.1ms |   116ms |   122ms |  1110ms | 1.012
hedge after 30 ms          |  16.1ms |    47ms |    53ms |    54ms | 1.017

Hedging is the technique Google described in "The Tail at Scale". Two conditions: the request must be idempotent (both copies may complete), and hedges must be limited, for example only after the p95 delay and only for a small share of traffic, or a slow server will receive double load when it can least afford it.

Retries: When, How Many, Where

Retry only errors that might succeed next time:

Retry Don't retry
Timeouts, connection refused or reset 400 Bad Request, 422 (your request is wrong)
502, 503, 504 (upstream trouble) 401, 403 (you're not allowed)
429 Too Many Requests, after its Retry-After 404 (it isn't there)
Deadlock or serialisation failure in a database 409 conflicts that need a decision, not a repeat

And a few rules:

Retry Storms

Retries feel free: one retry seems to cost "just one more request". But retries arrive when the server is already struggling, because that's when requests fail. Under overload, retries multiply the load at the worst moment.

Here's a simulated service with capacity for 100 requests per second, receiving 80. From t = 10 s to t = 15 s a brownout makes every request three times slower (capacity drops to about 33 per second). Clients time out after one second and retry up to three times, with different policies:

attempts sent per secondsucceeded per secondfailed per second

The same simulation, summarised:

policy                         | deadline-aware | peak/s | attempts/req | success | wasted | recovery
No retries                     | no             |     89 |         1.00 |   67.8% |   1033 | 13 s
Immediate retries (×3)         | no             |    333 |         3.05 |   29.7% |   2598 | none
Exponential backoff            | no             |    333 |         3.00 |   30.9% |   2598 | none
Backoff + full jitter          | no             |    343 |         3.02 |   30.5% |   2598 | none
Jitter + retry budget (10%)    | no             |    126 |         1.08 |   35.2% |   2333 | none
No retries                     | yes            |     89 |         1.00 |   94.5% |      0 | 3 s
Immediate retries (×3)         | yes            |    235 |         1.18 |   97.0% |      0 | 8 s
Exponential backoff            | yes            |    191 |         1.16 |   97.4% |      0 | 8 s
Backoff + full jitter          | yes            |    217 |         1.17 |   97.0% |      0 | 8 s
Jitter + retry budget (10%)    | yes            |    132 |         1.02 |   94.6% |      0 | 4 s

("Wasted" counts requests the server completed after the client had already given up. "Recovery" is the time after the brownout ends until three consecutive seconds with no failures and a short queue, within the 25 seconds simulated.)

The top half is a metastable failure: the brownout lasted five seconds, but with retries the service never recovered within the simulation. The mechanism:

  1. During the brownout, requests queue up and start timing out.
  2. Each timeout produces a retry, so the queue grows faster.
  3. The server processes requests in order, including the ones whose clients gave up long ago. It's busy doing wasted work (2,598 requests' worth), so fresh requests time out too.
  4. When the brownout ends, the server is fast again, but the backlog of dead requests and retries keeps it overloaded. The trigger is gone; the failure sustains itself.

Even with no retries at all, recovery took 13 seconds, because of the dead backlog. Backoff and jitter didn't help: they change when retries arrive, not how many. A retry budget reduced the load but couldn't clear the backlog either.

What fixed it was the server refusing work nobody was waiting for. With deadline awareness (here, skipping a queued request whose client's timeout will pass before it can finish), every policy recovered within 3 to 8 seconds, and retries became helpful: 97% success, against 94.5% without retries on the same deadline-aware server. The lesson generalises:

Backoff and Jitter

Backoff and jitter matter in a different situation: when many clients fail at the same moment. A database restarts, a leader election happens, a deploy cuts all connections, and every client sees its error within the same few milliseconds.

Simulating 100 clients that all fail at once and retry against a dependency that can accept 10 requests per 100 ms (rejected requests back off and try again), median of 50 runs:

strategy                       | total calls | done after
no backoff (retry each slot)   |         550 |    1.0 s
exponential, no jitter         |         550 |   32.8 s
exponential + equal jitter     |         399 |    3.0 s
exponential + full jitter      |         359 |    1.9 s
decorrelated jitter            |         275 |    1.9 s

The formulas, with base the first delay, cap the maximum and n the attempt number:

exponential:          delay = min(cap, base × 2^n)
full jitter:          delay = random(0, min(cap, base × 2^n))
equal jitter:         d = min(cap, base × 2^n);  delay = d/2 + random(0, d/2)
decorrelated jitter:  delay = min(cap, random(base, previous_delay × 3))

Use full or decorrelated jitter; there's no good reason to back off without jitter. And honour Retry-After when a server sends one: it knows more about its own state than your formula does.

Checklist

For every outbound call:

For every endpoint that changes state:

For every server:

Key Takeaways

Copied to clipboard!