Load Balancing, Multi-Tier Caching, and Idempotent APIs

Easy · System Design · Software Engineer · Technical Screen

Prompt

Architect a horizontally scaled backend service running as a fleet of stateless server processes behind load-balancing infrastructure. Your service handles both read-heavy user queries and state-changing operations such as charging a payment method or placing an order. Walk through your design across three core areas:

  1. Traffic Distribution (Load Balancing)

    • Explain the core role of a load balancer in a multi-instance service architecture.
    • Contrast major request-routing strategies and their trade-offs: round-robin (including weighted variants), least-connections / least-requests, consistent hashing, latency- or health-weighted selection, and session affinity (sticky sessions).
    • Compare transport-layer (Layer 4) and application-layer (Layer 7) load balancers, specifying where each belongs in the stack.
  2. Multi-Tier Caching

    • Identify every tier where responses or state can be cached, from client devices and CDNs/edge nodes through reverse proxies, application memory/clusters, and storage engines.
    • Compare standard read/write cache topologies: cache-aside, read-through, write-through, and write-back (write-behind).
    • Detail your strategy for expiration policies (TTLs), cache invalidation on writes, and bounding stale reads.
    • Show how your architecture prevents hot-key cache stampedes (thundering-herd database spikes) when popular entries expire.
  3. Idempotent Write APIs

    • Define request idempotency and explain why retry-safe mutation endpoints are critical for operations like billing charges or order submission.
    • Specify how idempotency tokens are generated, scoped, transmitted, and expired.
    • Show the persistence schema and lookup protocol used to record and verify execution state.
    • Walk through race conditions when identical tokens arrive concurrently, client network retries, and partial mid-flight crashes across external dependencies.
    • Explain how stateless load balancing and multi-node deployments shape your idempotency architecture.

Scope & Expectations

  • Anchor your trade-offs in a realistic service workload (read/write mix, latency targets, and failure assumptions) rather than listing textbook definitions in isolation.
  • Connect the three pillars into one coherent architecture showing how requests traverse edge proxies, application instances, distributed caches, and transactional storage.
  • Address subtle distributed-systems failure modes—including HTTP/2 connection pinning, stale cache overwrites, simultaneous duplicate requests, and crashes midway through external side effects.

Step-by-step walkthrough

  1. Clarify requirements and anchor on a concrete service

    The prompt covers three foundational pillars—load balancing, multi-layer caching, and idempotent APIs. Grounding all three in one concrete service gives every trade-off a sharp engineering reason: let's design the backend of a consumer mobile banking app (serving account balances, transaction feeds, and money-moving payment/order endpoints) deployed across dozens of stateless server instances in 3 Availability Zones (AZs) (physically separate data centers with independent power and networking inside one cloud region).

    Key architectural rules we establish up front:

    • Stateless application servers: Any server instance can handle any user's request; no user state lives exclusively in a single instance's RAM.
    • Unreliable networks and eager retries: Mobile apps lose Wi-Fi mid-request, reverse proxies retry dropped connections, and impatient users tap "Pay $45" twice.
    • Display staleness vs. financial truth: Showing an account summary that is 3 seconds old on a home screen is acceptable; deciding whether an account has enough money to send $45 must always read and lock the primary database, never a cache.

    Functional & non-functional targets: - Reads: GET account summary and paginated transaction history under 200 ms p99. - Writes: POST payment transfer (calling an external card/ACH processor) and order placement under 1 s p99 (excluding external network time), with strictly zero double charges and zero lost acknowledged writes. - Availability: Survive single-instance crashes and full single-AZ outages seamlessly.

  2. Back-of-the-envelope capacity math

    Let's translate user activity into concrete fleet sizes, cache memory, and database write rates:

    1. Traffic profile
       6M Daily Active Users * 36 API calls/day = 216M calls/day ≈ 2,500 RPS average
       Peak multiplier ~6x (morning payday direct-deposit rush) -> ~15,000 RPS peak
       Read / Write split (95% reads, 5% writes):
         Peak reads:  ~14,250 RPS
         Peak writes:    ~750 RPS (~125 writes/s average)
    
    2. Stateless application tier
       Assume 1 instance comfortably serves 500 RPS within latency targets (verify via load test):
         Minimum instances for peak = 15,000 / 500 = 30 instances
         Survive losing 1 of 3 AZs  = 15 instances per AZ * 3 AZs = 45 instances total
    
    3. Distributed Redis cache
       Cached payload per active user (summary + page 1 of transactions) ≈ 4 KB
       60-second Time-To-Live (TTL) bounds active keys to users active in the last minute:
         Upper bound: <= 800k active keys * 4 KB ≈ 3.2 GB RAM (even all 6M DAU = 24 GB)
       Deploy a 3-shard Redis Cluster (1 replica per shard across AZs) for high QPS & failover.
       At a 90% read hit rate, Postgres read load drops 10x: 14,250 RPS -> ~1,425 RPS!
    
    4. Idempotency storage
       125 writes/s avg * 86,400 s/day ≈ 10.8M keys/day * ~1 KB (request hash + JSON response)
       ≈ 10.8 GB/day -> 72-hour retention window ≈ 32 GB of live table data in Postgres.
    

    Three design lessons emerge immediately from the math: 1. 45 stateless servers are easy to run, so load balancing is really about health isolation, tail latency, and safe deploys rather than exotic scale. 2. A 90% cache hit rate means a total cache outage multiplies database reads by 10x—we must design stampede and fallback protections. 3. 32 GB of idempotency records easily fits inside our primary Postgres database, letting us commit idempotency state and payment rows atomically in one SQL transaction.

  3. API contract and idempotency headers

    1. Read Endpoints (naturally idempotent HTTP GET)
       GET /v1/accounts/{account_id}/summary
       GET /v1/accounts/{account_id}/transactions?cursor=tx_410&limit=25
         Response Headers:
           Cache-Control: private, no-cache   // forbids CDN/shared caching; client revalidates
           ETag: "v18-4c2a"                   // client sends If-None-Match -> fast 304 Not Modified
    
    2. Write Endpoints (non-idempotent HTTP POST made idempotent via header)
       POST /v1/payments
         Headers:
           Authorization: Bearer <jwt>
           Idempotency-Key: 8c4e1a90-3f2b-4d71-9a15-6e0b8d2f4c19   // client-generated UUID v4
         Body:
           { "account_id": "acct_42", "amount_cents": 4500, "currency": "USD", "payee_id": "merch_18" }
    
         Responses:
           201 Created:  { "payment_id": "pay_710", "status": "succeeded", "amount_cents": 4500 }
           202 Accepted: { "payment_id": "pay_710", "status": "pending" }  // processor timed out
           409 Conflict: { "error": "request_in_progress" } + Header: Retry-After: 1
           422 Unprocessable: { "error": "idempotency_key_reused_with_different_payload" }
           400 Bad Request:   { "error": "missing_idempotency_key" }
           (Replayed responses include header: Idempotent-Replayed: true)
    

    Notice two critical details: money is passed in integer cents (4500, never 45.00 floats that suffer binary rounding), and an upstream payment-processor timeout returns 202 Accepted (pending) rather than a fake 500 or failed—telling a user their payment "failed" when we do not actually know tempts them to create a brand-new payment with a fresh key and get charged twice.

  4. Data model and cache key layout

    Postgres Primary (with synchronous cross-AZ standby + async read replicas):
    
    1. idempotency_keys
       - caller_id         TEXT          // authenticated user_id or merchant_client_id
       - idem_key          UUID          // client-supplied Idempotency-Key
       - endpoint          TEXT          // e.g., "POST /v1/payments"
       - request_hash      BYTEA         // SHA-256(method + path + canonical JSON body)
       - status            TEXT          // 'in_progress' | 'completed'
       - recovery_point    TEXT          // 'started' | 'payment_created' | 'completed'
       - resource_id       UUID          // payment_id once reserved
       - lease_owner       TEXT          // app instance ID currently executing this key
       - lease_expires_at  TIMESTAMPTZ   // current time + 30s
       - lease_version     BIGINT        // monotonic fencing token incremented on takeover
       - response_code     INT           // frozen HTTP status (e.g., 201, 422 business decline)
       - response_body     JSONB         // frozen JSON body returned on every future replay
       - created_at        TIMESTAMPTZ
       - expires_at        TIMESTAMPTZ   // created_at + 72 hours (indexed for batch cleanup)
       PRIMARY KEY (caller_id, idem_key)
    
    2. accounts
       - account_id PK, available_cents BIGINT, row_version BIGINT, updated_at TIMESTAMPTZ
    
    3. payments
       - payment_id UUID PK, account_id, amount_cents, currency, status, processor_ref,
         idem_key UUID, created_at
       - UNIQUE (account_id, idem_key)   // permanent duplicate guard even after 72h key purge!
    
    4. ledger_entries (append-only double-entry debit/credit rows)
    5. outbox_events  (event_id PK, aggregate_id, payload, created_at -> streamed via CDC)
    
    Redis Cache Keys (store JSON + row_version; jittered TTLs):
       - acct:{account_id}:summary     -> TTL 60s +/- 10% random jitter
       - acct:{account_id}:txns:first  -> TTL 30s +/- 10% random jitter
       - global:fee_schedule           -> logical TTL 10m, physical TTL 30m (stale-while-revalidate)
    

    Why scope the primary key by (caller_id, idem_key)? So User A can never accidentally (or maliciously) collide with User B's UUID and read User B's cached payment receipt. And if we ever partition idempotency_keys, we hash-partition by caller_id, never range-partition by created_at date—in Postgres, unique indexes must include the partition key, so daily partitions would allow a retry across midnight to bypass uniqueness!

  5. High-level architecture

      Mobile Apps & Partner Servers
                   |
                   v
      +-------------------------+
      |   CDN / Edge Network    |  Caches static JS/images & public marketing/fee pages ONLY
      +------------+------------+
                   |
                   v
      +-------------------------+
      | L4 Network Load Balancer|  Anycast/static IPs across 3 AZs; fast TCP pass-through
      +------------+------------+
                   |
                   v
      +-------------------------+
      | L7 Reverse Proxies      |  TLS termination, JWT pre-check, rate limiting,
      | (Envoy, 2+ per AZ)      |  Least-Request (Power of 2 Choices), safe retry policy
      +------------+------------+
                   |
                   v
      +-------------------------------------------------------------------+
      | Stateless App Servers (45 instances across 3 AZs)                 |
      |  - Tiny in-process LRU cache (feature flags, fee config: 5s TTL)  |
      |  - Per-instance Singleflight coalescing for concurrent hot reads  |
      +--------+--------------------------+--------------------------+----+
               |                          |                          |
               v                          v                          v
      +-----------------+    +--------------------------+   +---------------------+
      |  Redis Cluster  |    | Postgres Primary         |   | External Payment    |
      | (3 shards x 2)  |    | + Sync Standby (AZ 2)    |   | Processor (Stripe / |
      | Cache-aside for |    | + Read Replicas          |   | Card Network)       |
      | user reads      |    | Accounts, Payments,      |   | Receives payment_id |
      +-----------------+    | Idempotency Keys, Outbox |   | as downstream key!  |
               ^             +------------+-------------+   +---------------------+
               |                          |
               |   Delete stale keys      v
               +----------------- [Outbox / CDC Relay] ---> Async Event Consumers
    
  6. Deep dive 1: Load balancing policies, L4 vs. L7, and health checks

    Role of the load-balancing tier: A load balancer sits behind one stable public IP/DNS address and distributes incoming traffic across a pool of backend servers. It provides four essentials: horizontal throughput scaling, automatic fault isolation via health checks, connection draining (letting in-flight requests finish cleanly while deploying new code), and centralized security/TLS management.

    Evaluating traffic-selection algorithms:

    Policy How it selects a server Best use case Key weakness
    Round-robin / Weighted round-robin Cycles through servers in order (or proportional to static capacity weights) Homogeneous servers serving fast, uniform queries; canary rollouts (e.g., 5% weight to v2) Blind to actual server load—a server stuck in garbage collection still gets full traffic
    Least connections / Least requests Picks the server with the fewest active requests Mixed fast/slow endpoints (like 15 ms reads + 800 ms payment writes) Across multiple load balancers, a freshly started server has 0 connections, causing every proxy to herd onto it at once
    Power of Two Choices (P2C) Picks 2 random healthy servers and routes to whichever has fewer active requests Multi-proxy L7 fleets (default in Envoy) Nearly optimal load spread while completely avoiding empty-node herding
    Consistent hashing Hashes a request key (e.g., cache shard key) onto a 360-degree ring; routes to next node clockwise Sharded caches (Redis) or stateful coordinators—adding/removing 1 of N nodes moves only 1/N of keys A single celebrity/hot key hammers one server unless paired with bounded loads (spilling above 1.25x avg load)
    Latency / Health-based (EWMA) Tracks Exponentially Weighted Moving Average (EWMA) (a rolling latency average giving more weight to recent milliseconds) and favors fast nodes Defending against "gray failures" like noisy cloud neighbors or slow disks Can oscillate if weights swing too aggressively without damping
    Sticky sessions (session affinity) Pins a user (via cookie or IP) to one specific server Legacy apps storing login sessions in local RAM, or stateful WebSockets Uneven hot spots, difficult deploys, and lost user state whenever that server crashes

    Our choice: L7 proxies use Least-Request with Power of Two Choices (weighted during canary deploys) and no sticky sessions—authentication uses stateless signed tokens, and shared state lives in Redis and Postgres.

    Transport (L4) vs. Application (L7) proxies: - Layer 4 (Transport layer): Inspects only IP addresses and TCP/UDP ports, forwarding packets without decrypting TLS (Transport Layer Security encryption). It handles millions of connections per second with microseconds of overhead, but it balances connections, not requests—if a partner server opens one multiplexed HTTP/2 or gRPC connection sending 5,000 RPS, L4 pins all 5,000 RPS onto a single backend! - Layer 7 (Application layer): Terminates TLS and parses HTTP headers, paths, methods, and gRPC frames. It costs more CPU, but balances individual HTTP/2 requests evenly, routes /v1/payments vs. /static, enforces rate limits, and understands headers like Idempotency-Key. - Combining both tiers: Put L4 at the cloud network edge for ultra-fast, multi-AZ static IP ingress and DDoS absorption, feeding a horizontally scaled L7 proxy tier that handles per-request routing.

    Health checks that don't cause cascading outages: Combine shallow active checks (GET /healthz every 5 s checking only that the app event loop responds—never pinging Postgres inside /healthz, or a 2-second database hiccup causes the load balancer to mark all 45 app servers dead simultaneously!) with passive outlier detection (temporarily ejecting any server returning 5 consecutive 5xx errors, capped at 50% of the pool).

  7. Deep dive 2: Multi-layer caching, read/write patterns, invalidation, and stampedes

    1. Where to cache across the stack: - Client (Mobile App): Cache immutable JS/image bundles for 1 year via content-hashed filenames; store ETags on transaction lists so unchanged refreshes return an empty 304 Not Modified. - CDN / Edge: Serve static assets and public fee tables from edge POPs close to users. Never cache private user balances at the CDN (Cache-Control: private, no-store). - Reverse Proxy (L7): Micro-cache public unauthenticated GET endpoints for 1–5 seconds. - In-process Application LRU: Cache tiny, globally hot read-only configs (feature flags, fee schedules) for 5 seconds in server RAM so Redis isn't hit 15,000 times/s for the same key. - Distributed Cache (Redis): Store per-user account summaries and recent transaction pages. - Database internal caches: Rely on Postgres's RAM buffer pool (shared_buffers) and read replicas for cache misses.

    2. Read and write caching topologies:

    Cache-Aside (our choice for user data):   Write-Through:
      Read:  App -> Redis (miss) -> DB          Write: App -> DB AND Redis synchronously
                 -> App populates Redis         Pros:  Cache always warm after writes
      Write: App -> DB -> delete Redis key      Cons:  Higher write latency; caches unread data
    
    Read-Through:                             Write-Back (Write-Behind):
      Read:  App -> Cache library -> DB         Write: App -> Redis (ack!) -> async batch to DB
      (Same lazy behavior as cache-aside,       Pros:  Fastest write throughput
       encapsulated inside a wrapper)           Cons:  Redis crash = LOST MONEY (never use here!)
    

    3. Eviction on write, expiration bounds, and consistency: - Delete on write, never overwrite in place: If two concurrent payments try to SET the cached balance directly, network reordering can leave the older balance in Redis forever. Deleting acct:{id}:summary forces the next read to load clean truth from Postgres. - Drive deletes via the transactional Outbox: Writing an invalidation event into outbox_events in the same Postgres commit as the payment guarantees that even if the app crashes 1 ms after committing, the CDC relay still deletes the stale Redis key within milliseconds. - Prevent the stale-reader race with row versions: Suppose Reader R misses Redis and reads row_version = 10, then Writer W commits row_version = 11 and deletes the Redis key, and finally slow Reader R writes row_version = 10 into Redis! Storing row_version inside the cached JSON and using a tiny Redis Lua script that only writes if incoming_version > cached_version eliminates stale overwrites, while a 30–60 s TTL acts as a guaranteed upper bound on any bug. - Financial checks bypass cache completely: Spending $45 uses an atomic Postgres statement: UPDATE accounts SET available_cents = available_cents - 4500, row_version = row_version + 1 WHERE account_id = :id AND available_cents >= 4500; (0 updated rows = insufficient funds).

    4. Mitigating hot-key miss storms: If a globally hot key expires while 15,000 RPS are arriving and the database query takes 200 ms, 15,000 * 0.2 = 3,000 concurrent queries slam Postgres at once. We layer four defenses: - Jittered TTLs (60s +/- 6s random offset) so batch-populated keys never expire at the same second. - In-process Singleflight on each app instance (collapsing 3,000 queries down to at most 45—one per server) plus a short Redis mutex lock (SET lock:key owner NX PX 2000) so only 1 server queries Postgres. - Stale-while-revalidate (serving slightly expired config values for a few seconds while 1 background worker refreshes) and negative caching (caching "not_found" for 15 s so lookups for nonexistent IDs don't hammer Postgres). - Probabilistic early refresh (XFetch): Before a hot key actually expires, each reader rolls a weighted random die that becomes more likely to trigger a single early refresh as expiration approaches:

    import math
    import random
    import time
    
    
    def should_refresh_early(
        expires_at_sec: float, recompute_duration_sec: float, beta: float = 1.0
    ) -> bool:
        """XFetch algorithm: triggers an early background refresh just before TTL expiry."""
        # 1.0 - random.random() stays strictly in (0.0, 1.0], avoiding log(0) errors
        random_draw = 1.0 - random.random()
        # Exponentially distributed lookahead window proportional to recompute cost
        early_window = -recompute_duration_sec * beta * math.log(random_draw)
        return (time.time() + early_window) >= expires_at_sec
    
  8. Deep dive 3: Idempotent APIs under concurrency, crashes, and load balancers

    Core guarantee of idempotent mutations: An operation is idempotent if executing it once or executing it ten times produces the exact same system state and returns the exact same response. When a mobile client sends POST /v1/payments and its LTE connection drops before reading the HTTP response, the client cannot tell whether the $45 charge succeeded or never reached our servers—its only safe recovery is retrying with the exact same Idempotency-Key.

    Key generation and lifetime: The client generates a fresh UUID v4 the moment the user taps "Pay $45", persists that UUID to local phone storage before opening the network socket, and reuses it on every retry of that payment attempt (only generating a new UUID if the user intentionally starts a second payment). Keys live for 72 hours in idempotency_keys to cover offline mobile retry queues, while UNIQUE (account_id, idem_key) on payments blocks duplicate charges forever.

    Step 1 — Atomic claim in Postgres (before touching balances or external APIs): After validating syntax, the app server executes a single atomic INSERT:

    INSERT INTO idempotency_keys (
      caller_id, idem_key, endpoint, request_hash, status, recovery_point,
      lease_owner, lease_expires_at, lease_version, created_at, expires_at
    ) VALUES (
      :caller_id, :idem_key, 'POST /v1/payments', :req_hash, 'in_progress', 'started',
      :instance_id, now() + interval '30 seconds', 1, now(), now() + interval '72 hours'
    )
    ON CONFLICT (caller_id, idem_key) DO NOTHING
    RETURNING lease_version;
    

    If 0 rows are returned, another request already claimed this key! We SELECT the existing row: - request_hash differs: Client accidentally reused an old key for a different amount/payee -> return 422 Unprocessable Entity. - status = 'completed': Immediately replay response_code and response_body with Idempotent-Replayed: true. - status = 'in_progress' and lease_expires_at > now(): A concurrent duplicate (double-tap) is actively running right now! Poll for up to ~500 ms in case it finishes immediately; otherwise return 409 Conflict with Retry-After: 1 so our worker threads stay free. - status = 'in_progress' and lease_expires_at <= now(): The previous server crashed mid-request! Atomically steal the lease and increment lease_version (our fencing token):

    UPDATE idempotency_keys
    SET lease_owner = :instance_id,
        lease_expires_at = now() + interval '30 seconds',
        lease_version = lease_version + 1
    WHERE caller_id = :caller_id AND idem_key = :idem_key
      AND status = 'in_progress' AND lease_expires_at <= now()
    RETURNING lease_version, recovery_point, resource_id;
    

    Step 2 — Three-phase execution to survive partial failures: Never hold a Postgres database transaction open across a slow external network call to a payment processor (that exhausts database connections and locks rows for seconds). Instead, split execution into three checkpointed phases:

    Phase A (Local Postgres Transaction — skipped on retry if recovery_point = 'payment_created'):
      1. Verify fencing token: UPDATE idempotency_keys SET recovery_point = 'payment_created',
         resource_id = :new_payment_id WHERE caller_id=:c AND idem_key=:k AND lease_version=:v.
         (0 rows -> a newer worker took over; abort!)
      2. Reserve funds atomically: UPDATE accounts SET available_cents = available_cents - :amt
         WHERE account_id=:acc AND available_cents >= :amt.
         (If 0 rows -> mark idempotency_keys 'completed' with 422 "insufficient_funds", commit & return!)
      3. INSERT INTO payments (payment_id, status='created', idem_key=:k, ...). Commit!
    
    Phase B (External Network Call — NO open DB transaction):
      Call processor.charge(amount=:amt, idempotency_key = payment_id).
      -> Crucial: passing our deterministic `payment_id` as the processor's own idempotency key
         ensures that even if our server crashes right after the card is charged, the next retry
         sends the EXACT same `payment_id` and the processor safely returns the original charge!
    
    Phase C (Local Postgres Transaction):
      1. Verify fencing token: UPDATE idempotency_keys SET status = 'completed',
         recovery_point = 'completed', response_code = 201, response_body = :json
         WHERE caller_id=:c AND idem_key=:k AND lease_version=:v. (0 rows -> abort!)
      2. UPDATE payments SET status = 'succeeded' | 'failed', processor_ref = :ref.
         - If succeeded: INSERT double-entry rows into ledger_entries.
         - If failed:    refund the reserved hold back to accounts.available_cents.
      3. INSERT invalidation & notification event into outbox_events. Commit!
    

    Note too what we never mark completed: transient 5xx errors, rate-limit 429s, or network timeouts leave the row recoverable (or move payments.status to unknown returning 202 Accepted while a background sweeper reconciles expired in_progress leases older than 60 seconds).

    Operating idempotent endpoints across a load-balanced fleet: - Any retry can hit any of the 45 servers, which is why idempotency state lives in shared Postgres, never local server memory (sticky sessions fail whenever the sticky server itself crashes). - Safe L7 proxy retries: Configure Envoy to auto-retry GETs and POSTs that carry an Idempotency-Key, while forbidding automatic proxy retries on keyless POSTs. - Ordered timeout cascade: Set Processor call (5s) < App handler (8s) < L7 Proxy (9s) < Mobile Client (10s) < DB Lease (30s) so inner tiers abort cleanly before outer tiers retry, and a live handler never outlives its 30-second lease. - Multi-region rule: Assign each user account a single home region for writes (or synchronously replicate across zones before acknowledging), because asynchronous multi-master databases could let two regions claim the same idem_key simultaneously during a split-brain partition.

  9. Scaling, failure handling, and trade-off summary

    Scaling and operational resilience: - Postgres write scaling: 750 writes/s peak x 3 short transactions (claim, Phase A, Phase C) = ~2,250 tiny sub-millisecond SQL commits/s, well within a single modern primary. Beyond ~10,000 writes/s, horizontally shard Postgres by caller_id / account_id—because idempotency_keys, accounts, and payments share that shard key, Phase A and Phase C stay single-shard local transactions! Batch-delete expired idempotency_keys (expires_at < now()) in LIMIT 1000 loops to keep Postgres autovacuum healthy. - Synchronous standby database: Replicate Postgres synchronously to at least one standby in a second AZ. If asynchronous replication lost an acknowledged Phase A commit during primary failover, a retry would generate a brand-new payment_id and charge the card processor a second time! - Redis outage survival: If the entire Redis cluster fails, cache-aside degrades gracefully to Postgres read replicas; an automatic circuit breaker skips dead Redis sockets immediately, the in-process LRU shields global config keys, and non-critical reads (deep historical transaction pages) shed load first so payment writes stay 100% healthy.

    Core trade-offs recap: - L4 + L7 load balancing with P2C vs. simple round-robin: Adds an L7 proxy hop and TLS CPU cost in exchange for even HTTP/2 request distribution, shallow/passive health isolation, and safe header-aware retries. - Cache-aside + Outbox delete vs. Write-through / Write-back: Accepts a brief sub-second display staleness window to guarantee caches never hold uncommitted money and cache crashes never lose writes. - Postgres-backed idempotency + 3-phase checkpoints vs. Redis SET NX: Trades 1–2 ms of extra SQL write latency for rock-solid transactional atomicity with payments, lease fencing against zombie servers, and zero double charges across failovers.

Intuition & how it works

Picture our multi-instance backend like a busy modern bank branch: 1. The Load Balancer is the lobby greeter at the front door. Customers walk up to one address, and the greeter sends each person to whichever open teller has the shortest line (least-request routing), immediately ropes off any teller booth whose computer freezes (health checks), and lets a teller finish helping their current customer before going on break (connection draining). 2. Multi-Layer Caching works like posting standard fee charts on the lobby wall and handing customers a timestamped mini-statement. Checking your balance 5 times in 10 seconds reads a fast memory copy in Redis instead of unlocking the main bank vault (cache-aside), while actually moving money ignores the printout and checks the real vault ledger. 3. Idempotent APIs work like numbered claim tickets stapled to every withdrawal slip. Before tapping "Pay $45", your phone prints a unique ticket number (Idempotency-Key). If store Wi-Fi drops and your phone submits that exact same ticket number a second time—even to a completely different teller behind the load balancer—the bank looks up the ticket in its central ledger, sees the $45 transfer already succeeded, and reprints your original receipt instead of taking a second $45 from your account.

Why do naive setups fail? Using simple round-robin load balancing keeps sending requests to a degraded server, while Layer-4 connection balancing pins thousands of multiplexed HTTP/2 requests onto a single unlucky instance. Caching private balances at a public CDN leaks financial data across users, overwriting cache keys during writes suffers race conditions where slow readers overwrite newer balances, and expiring hot keys all at once triggers a cache stampede (thousands of simultaneous misses overwhelming the database). Finally, tracking idempotency keys in local server RAM fails the moment a load balancer routes a retry to another server, and using standalone Redis without database transactions risks double charges if a server crashes between charging the card network and recording the key.

Let's trace a $45 payment (Idempotency-Key: idem-8c4e) across retries, concurrency, and caching:

1. t = 0 ms:  Phone sends POST /v1/payments (Idempotency-Key: idem-8c4e, amount_cents: 4500).
   - L4 -> L7 proxy picks Server #6 via Power-of-Two-Choices least-request.
   - Server #6 atomically inserts (acct_42, idem-8c4e, status='in_progress', lease_version=1)
     in Postgres, reserves 4500 cents in Phase A (payment_id = pay_710), and calls the
     card processor passing `pay_710` as the downstream idempotency key (Phase B).

2. t = 300 ms: User impatiently double-taps! Duplicate POST (idem-8c4e) lands on Server #22.
   - Server #22 tries INSERT -> hits UNIQUE conflict -> sees status='in_progress' with
     an active lease -> returns `409 Conflict (Retry-After: 1)` without touching money!

3. t = 650 ms: Card processor succeeds, BUT mobile LTE drops before Phone hears the reply!
   - Server #6 finishes Phase C in Postgres: marks idem-8c4e 'completed' with frozen 201 JSON,
     records ledger entries, and writes an Outbox event that deletes `acct:acct_42:summary`
     from Redis so the user's next home-screen refresh loads the updated balance.

4. t = 2,000 ms: Phone reconnects and retries POST (idem-8c4e) -> lands on Server #38.
   - Server #38 hits UNIQUE conflict -> sees status='completed' and matching request_hash ->
     returns the exact stored `201 Created (pay_710)` receipt in 3 ms. One charge total!

Key trade-offs

  • Load-aware routing (Power of Two Choices) vs. Round-Robin vs. Consistent Hashing: Round-robin requires zero state and works for uniform, tiny requests, while naive least-connections causes multiple load balancers to herd onto any freshly booted server with 0 active requests. Power of Two Choices (sampling two random healthy backends and picking the less loaded one) prevents herding while adapting to slow servers, whereas consistent hashing (mapping keys onto a circular hash ring so adding/removing 1 of N nodes moves only 1/N of keys) is reserved for sharded caches where data locality matters.
  • Layer 4 (Transport) vs. Layer 7 (Application) load balancing: L4 load balancers forward raw TCP/UDP packets using only IP and port, delivering massive throughput and ultra-low latency, but cannot split multiplexed HTTP/2 or gRPC requests sharing one TCP connection. L7 load balancers terminate TLS (Transport Layer Security encryption) and inspect HTTP paths, headers, and status codes—costing extra CPU and ~1 ms of latency in exchange for per-request balancing, path routing, outlier ejection, and header-aware retry rules. Layering L4 at the edge in front of L7 proxies captures both strengths.
  • Stateless servers vs. Sticky sessions (session affinity): Sticky sessions pin a user via cookie or IP to one server so local RAM state works, but create hot spots, complicate rolling deployments, and lose user sessions on server crashes. Keeping servers stateless and storing shared state in Redis/Postgres adds a ~1 ms network hop per lookup while making horizontal scaling and failover effortless.
  • Cache-aside + delete-on-write vs. Write-through / Write-back: Cache-aside (app checks cache, queries DB on miss, deletes cache key after writes) keeps the cache resilient—a Redis outage only slows reads rather than blocking writes. Write-through updates DB and cache synchronously (slower writes, pollutes cache with unread rows), while write-back acknowledges writes in RAM before flushing to disk asynchronously—fast for view counters, but unacceptable for financial data where a cache crash loses committed money.
  • Transactional Postgres idempotency vs. standalone Redis SET NX: Checking keys in Postgres costs ~2 ms instead of ~0.5 ms in Redis, but allows committing the idempotency_keys receipt, payments row, and outbox_events atomically in one ACID transaction backed by synchronous cross-zone replication. Standalone Redis uses asynchronous replication and memory eviction, which can drop recently written keys on failover and cause double charges.
  • Checkpointed phases with lease fencing vs. holding one long DB transaction: Holding a database transaction open during a 1-second external payment API call starves the Postgres connection pool and locks rows. Splitting into Phase A (reserve) -> Phase B (external call with payment_id) -> Phase C (finalize) protected by a fencing token (lease_version, a monotonic counter that blocks delayed zombie workers from overwriting a newer retry) requires explicit recovery states in exchange for high concurrency and crash safety.

Common mistakes

  • Putting database pings inside /healthz load-balancer checks: If Postgres has a brief 2-second latency spike, every app instance fails its health check at once and the load balancer removes 100% of your servers from rotation; keep /healthz shallow and handle dependency outages with circuit breakers.
  • Using L4-only load balancing for internal gRPC or HTTP/2 traffic: Because HTTP/2 multiplexes hundreds of concurrent requests over a single persistent TCP connection, L4 balances connections rather than requests, leaving new pods idle while older pods melt.
  • Caching authenticated user balances at the CDN or reading cached balances for spend checks: Missing Cache-Control: private, no-store risks serving one user's financial data to another, and checking cached balances before a payment lets concurrent requests spend the same $45 twice.
  • Updating cache values in place on write instead of deleting via an Outbox: Concurrent writers updating Redis directly can finish out of order and leave stale values cached until TTL expiry, and deleting directly from app code without a transactional outbox (an events table committed alongside business rows and relayed asynchronously) leaves stale cache data whenever an app server crashes right after COMMIT.
  • Ignoring cache stampedes and synchronized TTL expirations: Giving 100,000 batch-loaded keys an exact 60s TTL without random jitter or singleflight (coalescing identical in-flight misses on a server into one DB query) creates periodic traffic spikes against the database.
  • Storing idempotency state in local instance memory or checking via SELECT before INSERT: Local memory fails across load-balanced servers, and doing a non-atomic SELECT followed by INSERT lets two simultaneous requests both see "not found" and execute twice.
  • Failing to hash and compare the request payload: If a buggy client reuses Idempotency-Key: idem-8c4e for a $500 transfer after a $45 transfer, silently returning the $45 receipt hides a severe client bug; always verify request_hash and return 422 on mismatch.
  • Caching transient 5xx or network timeout errors as final idempotent responses: Freezing a temporary database timeout inside idempotency_keys permanently breaks every subsequent client retry for that key; only freeze terminal outcomes (201 success or deterministic 422 business declines like insufficient funds).

Follow-up questions

  • Why is a standalone Redis SET NX lock insufficient as the sole source of truth for financial idempotency keys? While SET ... NX atomically arbitrates two simultaneous arrivals on a single healthy Redis primary, Redis replication to replicas is asynchronous: if the Redis primary crashes 5 ms after acknowledging SET NX, the promoted replica may not have that key, allowing a client retry to charge the customer a second time. Furthermore, Redis cannot join a single ACID transaction with your Postgres payments table, leaving a crash window between writing Postgres and updating Redis. You can optionally put Redis in front of Postgres as a read-through fast cache for already-completed responses, but Postgres (with a synchronous standby) must remain the authoritative lock and record.

  • How do you enforce idempotency across asynchronous message consumers triggered after the HTTP write commits? Because our transactional outbox relay and message brokers (like Kafka or SQS) guarantee at-least-once delivery (re-sending messages whenever an acknowledgment is lost), consumers will occasionally receive the same event_id twice. Each consumer creates a processed_events (consumer_name, event_id PRIMARY KEY) table in its own database and executes INSERT INTO processed_events VALUES ('notifier', :event_id) ON CONFLICT DO NOTHING inside the exact same local transaction as its state update—if 0 rows insert, it safely skips the duplicate! When calling an external push/email provider that has no database transaction, pass event_id as the provider's deduplication key.

  • Why does consistent hashing reduce cache misses during cluster resizing, and how do you stop a single viral key from saturating one cache node? Standard modular hashing (hash(key) % N) remaps nearly (N - 1) / N (~90%+) of all keys whenever N changes, triggering a massive cache-miss storm; consistent hashing places both servers (using hundreds of virtual nodes per physical host for even spacing) and keys onto a fixed 0..2^32-1 ring (or 16,384 fixed hash slots in Redis Cluster) so adding or removing 1 of N shards moves only 1/N of cached keys. However, all reads for one viral or global key (global:fee_schedule) still hash to the same shard; you protect against hot-key overload by caching globally read-heavy keys in a 5-second in-process LRU cache inside each of the 45 app servers, or by using bounded-load consistent hashing / read replicas that spill reads once a shard exceeds 1.25x average QPS.

Follow-up questions

Similar questions

More Chime interview questions

All 18 Chime questions →