Load Balancing, Caching, and Idempotent API Design
System DesignModel answerLast updated
Design a multi-instance backend service covering routing policies, multi-layer caching strategies, and idempotent API support for non-repeatable operations like payments.
Scenario
Your team is rolling out a backend service that handles both read-heavy endpoints (e.g., fetching account data) and write endpoints where correctness is critical (e.g., initiating a payment or creating an order). The service runs on 10–20 stateless instances spread across multiple availability zones, sitting behind a load balancer, and is expected to handle roughly 5k RPS at steady state with 20k RPS peaks.
Answer all three sections below. For each one, go beyond definitions — explain when and why you'd make each design choice, and call out the failure modes.
Part 1: Routing Traffic Across Instances
- What role does a load balancer play in this architecture?
- Compare these routing strategies and describe the conditions under which each is the right choice:
- Round-robin and weighted round-robin
- Least connections
- Consistent hashing
- Latency- or health-aware routing
- Sticky sessions (session affinity)
- What is the difference between L4 and L7 load balancing? When would you use one versus the other, and is it ever useful to use both?
Part 2: Caching Strategy
- Identify the layers at which caching can be applied (from the client all the way to the database) and describe what belongs at each layer.
- Walk through the four main cache read/write patterns — cache-aside, read-through, write-through, and write-back — including when each is appropriate and where each can go wrong.
- How do you handle cache invalidation, TTL selection, and tolerable staleness?
- What is a cache stampede, and what techniques prevent or reduce one?
Part 3: Idempotent API Design
Design a system that makes a sensitive write endpoint (e.g., POST /charges) safe to retry without side effects.
- Define idempotency and explain why it matters specifically for retry-prone distributed systems.
- Describe where the idempotency key comes from, how it is scoped, and how long it should be retained.
- Propose a data model and walk through the full request lifecycle — including what happens on the first call, on a clean retry, and on a retry that arrives while the first request is still in progress.
- Explain how concurrent requests with the same key are handled, and how partial failures (e.g., charge succeeded but the response was never delivered) are recovered.
- Describe how idempotency interacts with a distributed deployment: do all retries need to hit the same instance?
You are expected to discuss trade-offs, pick concrete approaches, and explain what breaks if a given choice is made incorrectly.
Hints
Hint 1
For routing, think about what information each strategy requires to make a decision — round-robin needs nothing, least-connections needs live state, consistent hashing needs a stable key. That constraint tells you the cost and the failure mode of each.
Hint 2
For caching writes, the order of operations matters more than it seems. Ask yourself: if two writers race, which pattern leaves the cache in a consistent state and which one leaves stale data behind?
Hint 3
For idempotency, the hard case isn't the happy path — it's when the first request is still in flight when the retry arrives. Think about what a status flag in the database buys you, and what a distributed lock adds on top of that.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing the Problem First
Before designing anything, establish the operating parameters. At 5k–20k RPS across 10–20 stateless instances in multiple AZs, the infrastructure is squarely in the "standard horizontally scaled service" tier — nothing exotic. The interesting constraints come from correctness requirements: stale balance reads are acceptable for a few seconds, but a charge must never execute twice. That asymmetry should drive where you spend the most care in each section.
Part 1: Load Balancing
A load balancer gives you a single stable ingress point, distributes work to prevent any one instance from becoming a bottleneck, removes unhealthy instances from rotation via health checks, and enables rolling deploys by draining instances gracefully before replacement.
Routing policy comparison:
| Policy | How it decides | Use it when | Watch out for |
|---|---|---|---|
| Round-robin / weighted | Rotates through backends in order; weights reflect instance capacity | Homogeneous instances, short uniform requests | Ignores real-time load; a slow request on one node doesn't affect future assignments |
| Least connections | Routes to the instance with the fewest active connections | Variable request durations, long-lived connections | Needs live connection state at the LB; can mislead with HTTP/2 multiplexing where one TCP connection carries many streams |
| Consistent hashing | Hashes a key (e.g., user ID) onto a ring; remaps only ~1/N of keys when the fleet changes | Preserving cache locality, sharded stateful backends | Hot keys cause uneven load; needs virtual nodes to balance the ring |
| Latency/health-based | Prefers backends with lower observed latency and passing health checks | Multi-region, heterogeneous fleets | Feedback loops: too many requests pile onto the "fast" node, slowing it down. Use power-of-two-choices or latency smoothing to dampen oscillation |
| Sticky sessions | Pins a client to an instance via a cookie or source IP | Truly stateful legacy apps, WebSocket connections | Uneven load distribution; losing an instance loses its pinned sessions. Avoid this by externalizing session state to Redis or encoding it in a signed token |
For stateless services, least-connections or power-of-two-choices with active health checks is a strong default. Avoid sticky sessions — if you need per-user state, store it outside the instance.
L4 vs L7:
L4 load balancers (e.g., AWS NLB) operate at the TCP/UDP layer. They route on IP and port without reading the payload, which makes them extremely fast and protocol-agnostic. Use them when you need raw throughput, gRPC passthrough without inspection, or ultra-low added latency.
L7 load balancers (e.g., AWS ALB, NGINX, Envoy) parse HTTP. That enables path- and header-based routing, TLS termination, retries, rate limiting, canary traffic splits, and routing on application headers like Idempotency-Key. The trade-off is CPU cost and slightly higher latency per request.
A common production pattern is L4 at the edge for throughput, with L7 (an API gateway or service mesh sidecar) handling application-level routing. You get the performance of L4 for the outer hop and the flexibility of L7 for internal routing decisions.
Part 2: Caching
Where caching lives:
- Client/browser: static assets, HTTP-cached public responses via
Cache-Controland ETags. Never cache per-user financial data here. - CDN/edge: public or semi-public content (marketing pages, public rates). Inappropriate for user-specific data.
- Reverse proxy: cached responses for public GETs. Same restrictions apply.
- Application layer: the main lever for this service. In-process LRU (fastest, but per-instance and inconsistent across nodes) or a shared distributed cache like Redis or Memcached.
- Database: read replicas spread query load and act as a cache with some replication lag. The DB buffer pool caches hot pages automatically.
Read/write patterns:
- Cache-aside (lazy loading): on a read, check the cache; on a miss, read the DB and populate the cache. On a write, update the DB, then delete the cache key rather than overwriting it. Deletion is safer: two racing writers can each set an outdated value, but a delete forces the next reader to fetch fresh data. Most common pattern.
- Read-through: same as cache-aside but the cache library handles DB reads on misses. Centralizes the logic; behavior is equivalent.
- Write-through: every write goes to the cache and the DB synchronously. The cache is always warm and consistent, but write latency is higher and rarely-read data gets cached unnecessarily.
- Write-back (write-behind): writes land in the cache and flush to the DB asynchronously. Very low write latency, but data in the cache that hasn't flushed yet is lost if the cache crashes. Acceptable for non-critical counters or analytics aggregations; completely unacceptable for ledgers or payment records.
Invalidation, TTLs, and staleness:
Explicit invalidation on write is the most reliable approach — delete the affected key in the same application flow that performs the write, or use CDC (e.g., Debezium → Kafka → cache invalidator) to cover writes from any path. Always set a TTL as a safety net to catch missed invalidations, sized to the tolerable staleness window (e.g., 30 seconds for a balance display). Add TTL jitter (±10–20%) so a whole class of keys doesn't expire simultaneously. For bulk invalidation, use versioned key prefixes rather than trying to enumerate every key.
One hard rule: never serve authorization or charge eligibility decisions from cache. Always read from the source of truth for decisions with financial consequences.
Cache stampede prevention:
A stampede occurs when a hot key expires and a large number of requests simultaneously miss the cache and hammer the database. Mitigations:
- Single-flight / request coalescing: only one goroutine (or one node, using a short Redis
SET NXlock) recomputes the value; others wait or briefly serve stale data. - Stale-while-revalidate: return the expired value immediately while refreshing in the background.
- Probabilistic early expiration: start refreshing the key before it expires, with a probability that rises as the TTL approaches zero.
- Jittered TTLs and cache warming on deploy prevent the cold-start version of the same problem.
- Circuit breakers on the DB as a last line of defense to prevent a stampede from cascading into a full outage.
Part 3: Idempotent API Design
Why it matters:
An operation is idempotent if executing it multiple times produces the same result as executing it once. HTTP GET and PUT are naturally idempotent. POST /charges is not — retrying it naively creates a duplicate charge. In distributed systems, retries are unavoidable: clients retry on timeouts, load balancers retry on 502s, service meshes retry on connection resets. Without idempotency support, any of these can result in a customer being charged twice.
Key design:
The client generates a UUIDv4 for each logical operation and sends it as an Idempotency-Key header. It reuses the exact same key on every retry of that operation. The key is scoped to an account or merchant: (account_id, idempotency_key) is the uniqueness unit. Store a hash of the request body alongside the key — a reused key with a different payload returns 422 Unprocessable Entity, catching client bugs where two different operations accidentally share a key. Retain keys for 24 hours to 7 days, covering any realistic client retry window, then expire them.
Data model (Postgres):
CREATE TABLE idempotency_keys (
account_id TEXT NOT NULL,
idem_key TEXT NOT NULL,
request_hash TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('IN_PROGRESS','COMPLETED','FAILED_RETRYABLE')),
response_code INT,
response_body JSONB,
resource_id TEXT,
locked_until TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (account_id, idem_key)
);
Request lifecycle:
- Attempt
INSERT INTO idempotency_keys ... (status='IN_PROGRESS'). If the insert succeeds, this is the first request — proceed. - If the insert fails (key already exists), read the existing row:
IN_PROGRESS: another request is in flight. Return409 Conflictwith aRetry-Afterheader, or wait briefly and poll.COMPLETED: return the stored response immediately — no business logic runs again.FAILED_RETRYABLE: clear the lock and allow a fresh attempt.
- Execute the business logic (create the charge) and the DB write in a single transaction that also updates the idempotency row to
COMPLETEDand stores the response. - If the service crashes after the charge commits but before the response is delivered, the next retry hits step 2, finds
COMPLETED, and returns the stored response. The charge is not re-executed.
Concurrency handling:
The INSERT is the natural mutex. Two simultaneous requests with the same key both attempt the insert; exactly one wins, the other reads IN_PROGRESS and backs off. This works as long as the idempotency table is in the same database as the business data, enabling the atomicity of step 3. If they are in separate stores, you need a distributed lock (e.g., Redis SET NX EX) with a TTL, but you lose the atomic guarantee and must handle the case where the lock expires before the charge completes.
Distributed deployment:
Because idempotency state lives in a shared database (not in-process memory), retries do not need to hit the same instance. Any node handles any request — this is the correct interaction with stateless horizontal scaling. The idempotency table is the coordination point, not the instance. This is also why sticky sessions are an anti-pattern for this use case.
Common mistakes to avoid:
- Storing idempotency state in memory or per-instance caches — retries that hit a different node silently bypass the check.
- Committing the charge and the idempotency record in separate transactions — a crash between the two creates unrecoverable duplicates or phantom locks.
- Scoping keys globally instead of per account — a key collision between two different customers would incorrectly return one customer's response to the other.
- Skipping the request body hash — allows a client to silently change the operation while reusing a key.