Idempotency, Retries & Resilience
Why networks force retries, idempotency keys implemented end to end (storage, concurrency, response replay), natural idempotency, retries with exponential backoff and jitter, retry budgets, timeouts and deadline propagation, circuit breakers, bulkheads, fallbacks and graceful degradation.
The fundamental problem
When a request times out, the client can't know whether the server:
- never received it,
- processed it but the response was lost, or
- is still processing it.
Networks are unreliable, so clients must retry — which means servers must make retries safe.
Idempotency
An operation is idempotent if applying it many times has the same effect as applying it once.
| Naturally idempotent | Not idempotent |
|---|---|
PUT /users/42 {…full state…} | POST /payments |
DELETE /carts/7/items/3 | POST /orders |
UPDATE … SET status = 'paid' WHERE id = 9 | UPDATE … SET balance = balance - 100 |
| "set flag", "upsert by natural key" | "append", "increment", "send email" |
Ways to make operations idempotent:
- Idempotency keys supplied by the client (general solution).
- Natural keys / unique constraints:
INSERT … ON CONFLICT DO NOTHINGon(order_id); message dedupe byevent_id. - Conditional writes:
UPDATE … WHERE version = 3orstatus = 'pending'(state machines). - Set instead of increment where possible.
Implementing idempotency keys
CREATE TABLE idempotency_key (
account_id BIGINT NOT NULL,
key TEXT NOT NULL,
request_hash TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('processing','completed')),
response_code INT,
response_body JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (account_id, key)
);
import hashlib, json
from fastapi import Header, HTTPException
def create_payment(body: dict, account_id: int, idempotency_key: str = Header(...)):
req_hash = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
with db.transaction():
inserted = db.execute(
"""INSERT INTO idempotency_key (account_id, key, request_hash, status)
VALUES (%s, %s, %s, 'processing') ON CONFLICT DO NOTHING""",
(account_id, idempotency_key, req_hash)).rowcount
if not inserted:
row = db.one("SELECT * FROM idempotency_key WHERE account_id=%s AND key=%s",
(account_id, idempotency_key))
if row.request_hash != req_hash:
raise HTTPException(422, "Idempotency-Key reused with a different request")
if row.status == "processing":
raise HTTPException(409, "Request with this key is still in progress")
return replay(row.response_code, row.response_body)
# pass the key downstream so the processor also deduplicates
result = payment_processor.charge(body, idempotency_key=f"{account_id}:{idempotency_key}")
with db.transaction():
db.execute("INSERT INTO payment (...) VALUES (...)", ...)
db.execute("""UPDATE idempotency_key SET status='completed', response_code=201,
response_body=%s WHERE account_id=%s AND key=%s""",
(json.dumps(result), account_id, idempotency_key))
return result
Retries done right
import random, time
RETRYABLE = {408, 429, 500, 502, 503, 504}
def call_with_retries(fn, max_attempts=5, base=0.1, cap=5.0):
for attempt in range(max_attempts):
try:
resp = fn()
if resp.status not in RETRYABLE:
return resp
delay = float(resp.headers.get("Retry-After", 0)) or None
except (TimeoutError, ConnectionError):
delay = None
if attempt == max_attempts - 1:
raise RuntimeError("retries exhausted")
# full jitter: random between 0 and the exponential cap
time.sleep(delay or random.uniform(0, min(cap, base * 2 ** attempt)))
async function withRetry<T>(fn: () => Promise<T>, attempts = 5, base = 100, cap = 5000): Promise<T> {
for (let i = 0; ; i++) {
try {
return await fn();
} catch (err) {
if (i === attempts - 1 || !isRetryable(err)) throw err;
const delay = Math.random() * Math.min(cap, base * 2 ** i); // full jitter
await new Promise((r) => setTimeout(r, delay));
}
}
}
Rules
- Retry only idempotent operations (or ones with idempotency keys).
- Retry only transient errors: timeouts, connection resets, 429, 502/503/504. Never 400/401/403/404/422.
- Exponential backoff + jitter, a max attempt count, and a total deadline.
- Respect
Retry-After. - Retry at one layer and use retry budgets to avoid multiplicative amplification.
Timeouts and deadlines
- Every network call gets a connect timeout and a request timeout.
- Derive timeouts from the dependency's latency (≈ p99.9) and from the caller's remaining budget.
- Propagate deadlines (gRPC does this natively; otherwise pass
X-Request-Deadline). - Cancel work when the caller has given up.
Circuit breakers
import time
class CircuitBreaker:
def __init__(self, threshold=5, cooldown=30):
self.threshold, self.cooldown = threshold, cooldown
self.failures, self.opened_at, self.state = 0, 0.0, "closed"
def call(self, fn, fallback=None):
if self.state == "open":
if time.monotonic() - self.opened_at < self.cooldown:
if fallback: return fallback()
raise RuntimeError("circuit open")
self.state = "half_open"
try:
result = fn()
except Exception:
self.failures += 1
if self.state == "half_open" or self.failures >= self.threshold:
self.state, self.opened_at = "open", time.monotonic()
raise
self.failures, self.state = 0, "closed"
return result
(Production breakers use failure rates over sliding windows and slow-call thresholds — e.g. Resilience4j.)
Bulkheads, fallbacks and graceful degradation
| Pattern | Example |
|---|---|
| Bulkhead | separate connection pools per dependency; per-tenant queues |
| Fallback | show cached recommendations when the recommender is down |
| Graceful degradation | disable non-essential features under load (feature flags / brownout) |
| Load shedding | reject low-priority requests early with 503 when queues exceed limits |
| Hedged requests | send a duplicate read to another replica if the first is slow (idempotent reads only) |
| Request coalescing | collapse identical concurrent requests into one upstream call |
Delivery semantics vocabulary
| Semantics | Meaning | How |
|---|---|---|
| At most once | may lose, never duplicates | no retries |
| At least once | never loses, may duplicate | retries + acks |
| "Exactly once" (effectively) | each effect happens once | at-least-once + idempotent processing (dedupe by key) |
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.