Idempotency and Retries
Networks fail in an annoying way: when a request times out, you don't know whether it was processed. Maybe the request was lost, maybe the server did the work and the response was lost. Retrying is the obvious answer, and it is only safe if the operation is idempotent: doing it twice has the same effect as doing it once.
client --- POST /payments {amount: 50} ---> server (charges the card)
client <------------ 201 Created ----X (response lost: timeout)
client --- retry: POST /payments ---------> server (charges AGAIN?!)Naturally idempotent operations
| Operation | Idempotent? | Why |
|---|---|---|
SET balance = 100 |
Yes | Same final state however often you repeat it |
balance = balance + 50 |
No | Each repeat adds 50 more |
DELETE /orders/7 |
Yes | After the first call the order is gone; later calls change nothing |
POST /orders |
No | Each call creates another order |
| "Mark message 9 as read" | Yes | Setting a flag twice is the same as once |
Non-idempotent operations can be made safe with an idempotency key: the client generates a unique id for the logical operation and sends it with every attempt. The server remembers the keys it has processed and returns the saved result for a repeat.
class PaymentService:
def __init__(self):
self.balance_charged = 0
self.results = {} # idempotency key -> stored response
def charge(self, key, amount, lose_response=False):
if key in self.results:
return self.results[key] + " (replayed)"
self.balance_charged += amount # the real side effect
response = f"charged {amount}"
self.results[key] = response
if lose_response:
raise TimeoutError("response lost")
return response
svc = PaymentService()
def pay_with_retries(key, amount):
for attempt in range(1, 4):
try:
return svc.charge(key, amount, lose_response=(attempt == 1))
except TimeoutError as e:
print(f" attempt {attempt}: {e}, retrying")
print(pay_with_retries("order-7-payment", 50))
print(pay_with_retries("order-8-payment", 20))
print("total charged:", svc.balance_charged) attempt 1: response lost, retrying
charged 50 (replayed)
attempt 1: response lost, retrying
charged 20 (replayed)
total charged: 70
In production the key store must be durable and written in the same transaction as the side effect (or with a unique constraint), otherwise a crash between the two reintroduces duplicates. Stripe's API, for example, accepts an Idempotency-Key header and keeps keys for 24 hours.
Exponential backoff
Retrying immediately and repeatedly turns a small outage into a big one: every client hammers the struggling server at once. Exponential backoff waits longer after each failure: base × 2^attempt, capped at a maximum.
def backoff_schedule(base_ms=100, cap_ms=5_000, attempts=8):
return [min(cap_ms, base_ms * 2 ** n) for n in range(attempts)]
delays = backoff_schedule()
print("delays (ms):", delays)
print("total wait before giving up:", sum(delays), "ms")delays (ms): [100, 200, 400, 800, 1600, 3200, 5000, 5000]
total wait before giving up: 16300 ms
Jitter
Backoff alone isn't enough. If 1,000 clients failed at the same moment, they all retry at 100 ms, then all at 200 ms, and so on, in synchronised waves. Adding randomness, jitter, spreads them out. The popular "full jitter" strategy waits a random time between 0 and the backoff value:
import random
from collections import Counter
def retry_times(strategy, clients=1000, attempt=3, base_ms=100, seed=42):
rng = random.Random(seed)
cap = base_ms * 2 ** attempt # 800 ms for the 4th try
times = []
for _ in range(clients):
if strategy == "no jitter":
times.append(cap)
else: # full jitter
times.append(rng.uniform(0, cap))
return times
for strategy in ["no jitter", "full jitter"]:
per_100ms = Counter(int(t // 100) * 100 for t in retry_times(strategy))
busiest = max(per_100ms.values())
print(f"{strategy:<12} busiest 100 ms slot gets {busiest:4} retries; slots used: {len(per_100ms)}")no jitter busiest 100 ms slot gets 1000 retries; slots used: 1
full jitter busiest 100 ms slot gets 139 retries; slots used: 8
Without jitter, all 1,000 retries land in the same instant. With full jitter they spread over all eight 100 ms slots and the busiest gets only 139, about what an even spread would give.
When not to retry
Retries must be bounded and selective:
- Retry: timeouts, connection errors,
429 Too Many Requests(respectRetry-After),503 Service Unavailable. - Don't retry:
400 Bad Request,401,403,404,422. The request will fail the same way every time. - Limit total attempts and use a deadline: if the caller's own request has a 2-second budget, there's no point retrying after 1.9 s.
- Beware retry amplification: if each of 4 layers retries 3 times, one failing call at the bottom becomes 3^4 = 81 attempts.
def amplification(layers, attempts_per_layer):
return attempts_per_layer ** layers
for layers in [1, 2, 3, 4]:
print(f"{layers} layer(s) each trying 3 times -> up to {amplification(layers, 3):3} calls to the bottom service")
print("retry only at one layer (e.g. the edge) ->", amplification(1, 3), "calls")1 layer(s) each trying 3 times -> up to 3 calls to the bottom service
2 layer(s) each trying 3 times -> up to 9 calls to the bottom service
3 layer(s) each trying 3 times -> up to 27 calls to the bottom service
4 layer(s) each trying 3 times -> up to 81 calls to the bottom service
retry only at one layer (e.g. the edge) -> 3 calls
A retry budget (for example, "retries may add at most 10% extra load") and circuit breakers keep retries from becoming a self-inflicted denial of service.
Exactly-once is built, not given
Real systems combine three ideas to get effectively exactly-once behaviour over unreliable networks:
- At-least-once delivery: retry until acknowledged.
- Idempotent processing: idempotency keys, unique constraints, or upserts.
- Atomic bookkeeping: record "processed key K" in the same transaction as the effect.
Tip: Generate the idempotency key on the client, once per user action (for example when the "Pay" button is clicked), not per HTTP attempt. Otherwise every retry looks like a new operation.
Test yourself
Which operation is idempotent?
balance = balance + 10POST /orderscreating an orderSET status = 'shipped'for order 7- Appending a line to a log
Why add jitter to exponential backoff?
- To make retries faster
- To spread retries from many clients over time instead of synchronised waves
- To reduce the number of retries
- To encrypt requests
Which response should a client generally NOT retry?
- 503 Service Unavailable
- A connection timeout
- 429 Too Many Requests
- 422 Unprocessable Entity