{}DSA Atlas

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.

Intermediate → Advanced6 interview questions

The fundamental problem

When a request times out, the client can't know whether the server:

  1. never received it,
  2. processed it but the response was lost, or
  3. is still processing it.
Client Payment API POST /payments ₹500 charged ✓ ✗ response lost timeout… retry? POST /payments ₹500 (again) charged twice ✗
Retries are necessary for reliability and dangerous without idempotency.

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 idempotentNot idempotent
PUT /users/42 {…full state…}POST /payments
DELETE /carts/7/items/3POST /orders
UPDATE … SET status = 'paid' WHERE id = 9UPDATE … SET balance = balance - 100
"set flag", "upsert by natural key""append", "increment", "send email"

Ways to make operations idempotent:

  1. Idempotency keys supplied by the client (general solution).
  2. Natural keys / unique constraints: INSERT … ON CONFLICT DO NOTHING on (order_id); message dedupe by event_id.
  3. Conditional writes: UPDATE … WHERE version = 3 or status = 'pending' (state machines).
  4. Set instead of increment where possible.

Implementing idempotency keys

request + Idempotency-Key INSERT key (unique) new keyexecute, store response exists, completedsame body → replay response exists, in progress409, retry later same key + different body hash → 422 (key misuse) · keys expire after ~24 h
The unique insert is the lock; the stored response is the replay.
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.
client ×3 gateway ×3 service ×3 databaseup to 27 attempts 3 × 3 × 3 = 27× load on the struggling component — retry at one layer, with budgets
Retry storms: each layer's "harmless" retries multiply.

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

CLOSEDcalls flow OPENfail fast / fallback HALF-OPENtrial calls failure rate > threshold cool-down elapsed trials succeed trial fails
Fail fast while a dependency is unhealthy; probe periodically for recovery.
Python
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

PatternExample
Bulkheadseparate connection pools per dependency; per-tenant queues
Fallbackshow cached recommendations when the recommender is down
Graceful degradationdisable non-essential features under load (feature flags / brownout)
Load sheddingreject low-priority requests early with 503 when queues exceed limits
Hedged requestssend a duplicate read to another replica if the first is slow (idempotent reads only)
Request coalescingcollapse identical concurrent requests into one upstream call

Delivery semantics vocabulary

SemanticsMeaningHow
At most oncemay lose, never duplicatesno retries
At least oncenever loses, may duplicateretries + acks
"Exactly once" (effectively)each effect happens onceat-least-once + idempotent processing (dedupe by key)

Interview questions

0 / 6 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.