Scalability Patterns and Techniques Questions
Scaling a system to handle growth in traffic and data: horizontal versus vertical scaling, statelessness, sharding and partitioning strategies, read replicas, and connection pooling. Covers capacity estimation, identifying bottlenecks, and the tradeoffs each scaling axis introduces. The general toolkit for taking a design from thousands to millions of users.
Design a caching layer for a product-details API that must sustain 10,000 requests per second with a P95 latency target of 50ms. Cover your cache topology (edge CDN, application-level, distributed cache), eviction policy, TTL strategy, how you'd guard against cache stampede, cold-start handling, and the instrumentation you'd add to measure effectiveness.
Sample Answer
Direct answer
Layer the cache so most of the 10,000 requests per second (RPS) never reach the database at all: an edge content delivery network (CDN) for public, cacheable responses, a regional distributed cache (Redis or Memcached) as the authoritative read cache per region, an optional small local in-process cache for the very hottest keys, and database read replicas underneath everything as the last line of defense for the reads that still get through. The 95th-percentile (P95) latency target of 50 milliseconds is achievable because each layer above the database answers in single-digit milliseconds; the design work is mostly about which layer owns which slice of the traffic, how eviction and time-to-live (TTL) are set per data shape, and how the system behaves when a cache entry expires or a whole region briefly loses its cache.
Topology
flowchart LR
U[Client] --> CDN[Edge CDN]
CDN -->|miss| Regional[Regional Redis cluster x3 regions]
Regional -->|miss| App[App server: local hot-key cache]
App -->|miss, singleflight| DB[(Primary DB)]
App -->|read-heavy fallback| Replica[(Read replicas)]
DB --> Regional
Regional --> CDN
A 3-region topology, one regional Redis cluster per region, is the natural shape once traffic is global: each region's application servers read from their own regional Redis cluster first, so a cross-region round trip only happens on a true miss. Cache-warming keeps this useful even right after a deploy or a regional failover: instead of a cold Redis cluster taking the full brunt of traffic, a warm-up job pre-populates the known hot key set from a snapshot or from the surviving region before that region takes production traffic. The failover mechanics themselves (how a region is declared unhealthy, how traffic is rerouted, what replication mode feeds the standby) belong to the availability and disaster-recovery side of the system; what matters here is only that cache-warming is the piece that keeps a freshly-promoted region from serving a wall of cache misses.
Database read replicas sit at the bottom of the hierarchy, not because they are unimportant, but because by design most traffic should never reach them: they exist to absorb the read load that the cache layers above did not catch, keeping the primary database free for writes.
Sizing the read/write mix and the key-popularity shape
The exact read/write ratio depends on the dataset, and it changes both the TTL strategy and the stampede-protection budget:
- An inventory-style catalog might run close to 10,000 reads/s against 100 writes/s, a roughly 99:1 read-heavy mix, where staleness is cheap because writes are rare.
- A more write-active product catalog might run closer to a 95/5 read/write split, where the TTL-length trade-off is tighter: a long TTL serves more reads from cache, but a 5% write rate means more of what's cached is out of date at any moment, so the acceptable TTL shrinks compared to the 99:1 case.
Traffic is also rarely uniform across the catalog. With 10 million products, a Zipfian distribution where roughly 95% of requests hit the top 10% of products is typical for product-detail pages: this is the number that justifies keeping a small, aggressively-warmed hot-key set (the top 10%) rather than trying to cache the long tail with the same priority.
Eviction and TTL strategy
- Use least-recently-used (LRU) eviction in the regional cache with a memory cap, since it is a reasonable default when access patterns are Zipfian: the hot 10% naturally stays resident.
- Tier TTLs by how often data actually changes: a product whose price or stock updates roughly per-minute needs a TTL well under a minute, or event-driven invalidation on write, rather than sitting on a multi-minute TTL that would show stale stock counts. Slower-changing fields (description, images) can carry a much longer TTL.
- Pair short-TTL data with a background cache-priming job for the known hot set, so the top 10% of products refresh proactively instead of every expiration turning into a cold miss during peak traffic.
Cache stampede protection
When a hot key expires, do not let every one of its concurrent readers hit the database at once. Use request coalescing (a "singleflight" pattern): the first request after a miss acquires a per-key lock and performs the real fetch, while concurrent requests for the same key wait for that result instead of issuing their own database queries. Combine this with serving the previous, slightly stale value while the refresh happens in the background rather than making every waiter block, which is what keeps the P95 latency target intact even during a miss.
Masking a slow downstream dependency
Suppose part of the product-detail response depends on a personalization or pricing microservice with 200-500ms of latency, far too slow to hit on every request at a 50ms P95 target. Caching absorbs this by storing that dependency's response keyed by product, so only the first request (or the background refresh) pays the 200-500ms cost. Cache-key design has to account for authenticated versus anonymous traffic here: an anonymous (logged-out) request can share one cache entry per product, but an authenticated request that gets a personalized result cannot be keyed by raw user ID without effectively defeating the cache (one entry per user, near-zero reuse). A workable middle ground is keying authenticated responses by product plus a coarse user segment (for example, a pricing tier or locale) rather than by individual user identity, which keeps the cache's hit rate high while still respecting personalization.
Fragment caching for personalized pages
A product page usually mixes shared page components, images, description, review counts, that are identical for everyone, with personalized widgets, like "recommended for you", that are not. Caching the whole page as one unit forces a choice between caching nothing (because of the personalized part) or caching stale personalization (because of the shared part). Fragment (partial) caching avoids that trade-off: cache the shared shell as one fragment with a longer TTL, and render or fetch the personalized widgets separately with their own short-TTL or no-cache treatment, so the expensive-to-personalize slice does not force the whole page out of the cache.
Instrumentation
Track, per layer (CDN, regional, application): hit ratio, origin request rate, P95 and P99 (99th-percentile) latency, count of stampede/lock-contention events, and TTL distribution against actual data-change frequency. Alert on a sudden hit-ratio drop or an origin request-rate spike, since both are early warning signs that a cache layer stopped doing its job, whether from a bad deploy, an expired warm-up job, or a traffic shape shift away from the assumed Zipfian pattern.
Trade-offs and pitfalls
Serving a stale value during a background refresh trades a small amount of freshness for a large amount of latency and database protection, which is almost always the right trade at this scale, but it has to be a deliberate choice with a bounded staleness window, not an accident of a missing invalidation path. The most common design mistake is applying one TTL policy to the whole product object instead of splitting it by field volatility (price and stock versus description and images), which either stales the fast-moving fields or needlessly re-fetches the slow-moving ones. A second common mistake is keying personalized cache entries by raw user identity, which looks correct in a demo with few users and quietly collapses the cache hit rate once real traffic and real personalization variety show up.
Design connection-pool management for a microservice that serves 500 concurrent request handlers and makes both database and upstream HTTP calls. How would you size the DB connection pool versus the HTTP client pool, choose timeouts and max lifetimes, integrate with circuit breakers, and test pool behavior under a simulated production spike?
Sample Answer
Direct answer
Size each pool from the request rate implied by the concurrency, not from the concurrency number itself: work out how many requests per second actually need a database connection or an outbound HTTP connection at steady state, multiply by how long each connection is held (Little's Law), then add an explicit safety margin. Timeouts must be shorter than the end-to-end service level objective (SLO), and connections need a maximum lifetime shorter than any upstream infrastructure's idle-connection timeout so sockets get rotated before they are silently dropped. A circuit breaker sits in front of each pool so a failing dependency fails fast instead of exhausting the pool while everyone queues for a resource that will not respond.
Sizing the pools
Step 1: convert concurrency to throughput. 500 concurrent handlers is a snapshot of how many requests are in flight, not a rate. Little's Law relates them: concurrency equals arrival rate times average time in system (L=λW). If the average end-to-end request latency is known (or targeted), the implied arrival rate falls out directly.
Step 2: split by dependency. Not every request touches the database, and not every request calls the same upstream. Measure (from application performance monitoring, not guesswork) what fraction of requests hit each dependency and how long that call takes, then apply Little's Law again, this time scoped to that dependency, to get the concurrent connections it needs.
Step 3: timeouts and lifetimes.
- Connect timeout: short, on the order of a few hundred milliseconds for calls inside the same network, since a connection that cannot even establish is not going to succeed on retry within budget.
- Request/read deadline: a slice of the overall SLO, sized so that even if this call takes its full budget, the caller still has time left to respond.
- Idle timeout: closes unused connections after they've sat idle for a while, freeing capacity for other requests.
- Max connection lifetime: rotates connections periodically so no single socket outlives an upstream load balancer's or NAT device's own idle-reap window, which would otherwise cause requests to fail against a connection that looks alive locally but was already dropped upstream.
- Pool checkout timeout: kept short. If a caller cannot get a connection quickly, failing fast and shedding load beats piling requests into an ever-growing queue.
Step 4: circuit breakers and bulkheads. Wrap each pool (or each upstream host) with its own breaker: once the failure rate or consecutive-failure count crosses a threshold, the breaker opens and callers get an immediate fallback or error instead of waiting out a timeout against a resource that is already failing. A bulkhead means giving a critical dependency its own pool, separate from a non-critical one, so a slow or saturated non-critical dependency cannot starve connections a critical path needs. The state-machine mechanics of breakers (closed / open / half-open, backoff between probes, how they interact with retries and cascading failure) are a deeper topic in their own right; what matters here is that the pool and the breaker are wired to the same dependency boundary, so a breaker trip and a pool-exhaustion alert are talking about the same failure.
Step 5: test it. Load test by ramping to the target concurrency and then spiking beyond it, watching pool wait time and saturation rather than just end-to-end latency. Separately, inject faults (added latency, forced errors) on the database and the upstream to confirm the breaker actually trips and the fallback path is exercised, not just that it exists in code. Run a soak test long enough to exercise the max-lifetime rotation at least once, to catch connection leaks that a short test would miss.
Worked example
Assumptions used below (explicitly stated, not measured facts):
- Concurrency L=500 handlers (given).
- Target average end-to-end latency W=200ms (an illustrative SLO target, not a measured value).
- 30% of requests make a database call, averaging 20 ms per call (illustrative).
- 50% of requests call an upstream HTTP service across 5 upstream hosts, averaging 50 ms per call (illustrative).
- Safety factor of 2x on the computed steady-state connection counts (illustrative, tune from observed variance).
Database pool:
DB call rate=0.3×2500=750 calls/s DB connections needed=750×0.02s=15With the 2x safety factor, target pool size = 30, capped at whatever the database server's own connection limit allows (if the DB caps total connections lower than 30 times the number of service instances, add a proxy/pooler in front of the database rather than growing the per-instance pool further).
HTTP client pool:
HTTP call rate=0.5×2500=1250 calls/s HTTP connections needed=1250×0.05s=62.5→63Spread across 5 upstream hosts: 63/5≈12.6→13 per host minimum, times the 2x safety factor = 26 per host target. (For HTTP/2 upstreams that multiplex many logical requests over one connection, this per-connection count would be far smaller; the formula is the same, only the effective "one connection handles many concurrent calls" changes the divisor.)
flowchart LR
C[Request handlers x500] --> CB1{Circuit breaker: DB}
C --> CB2{Circuit breaker: upstream HTTP}
CB1 -->|closed| DBPool[DB connection pool target 30]
CB1 -->|open| FailFast1[Fail fast / fallback]
DBPool --> DB[(Database)]
CB2 -->|closed| HTTPPool[HTTP client pool per host 26]
CB2 -->|open| FailFast2[Fail fast / fallback]
HTTPPool --> Upstream[Upstream service]
Trade-offs and pitfalls
Over-provisioning a database pool is not free: every open connection costs the database server memory and, for some engines, a background process, so "just make the pool bigger" is not a safe default. Under-provisioning causes callers to queue for a checkout instead of failing fast, which turns a capacity problem into a latency-cascade problem for every caller of the service, not just the ones touching the saturated dependency. A common ordering mistake is setting an inner call's timeout longer than the budget the outer caller has left, which wastes the outer request's remaining time waiting on a call that can no longer help it finish in budget; timeouts should shrink, not grow, as you move deeper into a call chain. Finally, a load test that only ramps to the steady-state target and never spikes past it will not catch pool exhaustion, since the whole point of a pool is that it behaves fine until it doesn't.
A product expects 1,000,000 active users per day, with the average session generating 20 API requests. Estimate the expected peak requests-per-second, assuming 10% of daily traffic occurs in the busiest hour. Show your calculations, state your assumptions about traffic shape, and explain how a different busiest-hour fraction would change the result.
Sample Answer
Direct answer
With 1,000,000 daily users generating 20 API requests each and 10% of that traffic landing in the busiest hour, the expected peak load is approximately 556 requests per second (RPS). That number is entirely a function of one stated assumption (the 10% busiest-hour share), so the first thing a strong candidate does is name that assumption out loud, not hide it inside the arithmetic.
Structured elaboration
Back-of-envelope RPS estimates follow the same three-step conversion every time:
- Total volume for the period. Multiply the population count by the per-entity activity rate to get a total (here: daily active users times requests per session).
- Concentrate to the busiest window. Apply the stated (or measured) peak-hour share to get requests in that one hour.
- Convert to a rate. Divide by the number of seconds in that window.
Peak RPS=3600U×r×f
where U is daily active users, r is requests per user-session, and f is the fraction of daily traffic in the busiest hour (3600 seconds).
The one hidden assumption in this formula is that traffic is roughly uniform within that busiest hour. That is a simplification, not a fact, and it is the piece a candidate should flag rather than silently bake in.
Worked example
Given: U=1,000,000, r=20, f=0.10.
Total daily requests=1,000,000×20=20,000,000
Busiest-hour requests=0.10×20,000,000=2,000,000
Peak RPS=36002,000,000≈555.6⇒≈556 RPS
Sensitivity to the busiest-hour fraction. Because the formula is linear in f, changing the assumption rescales the answer directly:
f=0.05⇒36000.05×20,000,000≈278 RPS
f=0.20⇒36000.20×20,000,000≈1,111 RPS
Extending peak RPS to concurrency (Little's Law). Once you have a request rate, you can estimate how many requests are in flight at once if you also assume an average per-request processing time, using Little's Law: L=λ×W, where L is the average number of concurrent requests, λ is the arrival rate (RPS), and W is the average time a request spends in the system. Assume, as an illustrative input (not derived from the question), an average processing time of 150 ms:
Lavg=556×0.15≈83 concurrent requests
That average understates what you should actually provision for. If the service has a P99 latency target (the response time under which 99% of requests must complete) of, say, 500 ms rather than the 150 ms average, the concurrency implied at that tail is higher:
Lp99=556×0.5≈278 concurrent requests
Provisioning a connection pool or thread pool (a fixed, pre-allocated set of database connections or worker threads that requests share rather than each opening its own, sized to how many can be in flight at once) for the 83-request average leaves no room for the tail: any workload approaching its P99 latency target will need roughly 3x the average-case concurrency headroom in this example, purely from the average-versus-tail latency gap.
Trade-offs & pitfalls
- The 10% figure is an assumption, not a measurement. In a real system, replace it with actual traffic-shape data (hourly histograms) as soon as it exists; shipping capacity on an unvalidated guess is the most common mistake here.
- Uniform-within-the-hour is optimistic. Real traffic often has sub-minute bursts well above the hourly average; sizing to the hourly peak RPS without additional headroom under-provisions for the true instantaneous peak.
- Average latency and P99 latency imply very different concurrency needs. Using average latency alone to size a connection or thread pool is a common under-provisioning mistake once tail latency is the real constraint.
- Do not confuse this system-load estimate with a load-balancing or failover concern. This is purely about how much aggregate capacity to provision; how traffic is routed to individual servers is a separate problem.
Your service is stateful and stores per-user ephemeral session data in memory. Walk through three practical approaches to scale it horizontally without breaking correctness: sticky sessions, active-active replication, and externalizing the state. For each, describe the operational complexity, failure modes, and performance characteristics.
Sample Answer
Direct answer
There are three practical ways to scale a stateful service that keeps per-user ephemeral data in memory: keep the state local and pin each user to one instance (sticky sessions), replicate the state across instances so any of them can serve a user (active-active replication), or move the state out of the instances entirely into a shared store (externalization). Sticky sessions are the cheapest to build but the most fragile; externalization is the most operationally mature and is the default recommendation for anything beyond a small fleet; active-active replication is the highest-complexity option, justified mainly when you need both local-memory latency and multi-node resilience together.
Structured elaboration
1. Sticky sessions (session affinity at the load balancer)
- How it works: the load balancer hashes a stable client identifier and routes all of that client's requests to the same instance, which keeps the session in local memory. The routing mechanism itself (which hashing scheme, which health checks) is load-balancer territory; what matters for scaling the service is the consequence: correctness now depends on that one instance staying up.
- Operational complexity: low to moderate. Configure affinity on the load balancer, size instance capacity for peak per-node session count, add health checks and connection draining so deploys don't silently drop sessions.
- Failure modes: an instance failing loses every session pinned to it unless you add a fallback (short-time-to-live (TTL) backup write, or accept the loss and force re-authentication). Autoscaling and rolling deploys cause rebalancing, which cold-starts sessions on whichever instance a client lands on next. Hot users concentrated on one instance cause uneven load that autoscaling on aggregate metrics won't catch.
- Performance: the best case for latency, since reads and writes never leave process memory. Effective capacity is limited by the least-loaded-instance problem: total fleet capacity is high, but any single hot instance can be saturated while others are idle.
2. Active-active replication
- How it works: session state is synchronously or asynchronously replicated across a set of instances (via a gossip protocol, where nodes periodically exchange state with random peers; a consensus protocol, where nodes vote to agree on a value before it counts as committed; or conflict-free replicated data types, data structures built to merge concurrent updates without conflicts) so more than one node holds a current copy and can serve a read or accept a write.
- Operational complexity: high. You are now running a small distributed system inside your application tier: membership management, conflict resolution for concurrent writes to the same session, and monitoring for replication health.
- Failure modes: network partitions are the central risk. Without a consensus mechanism enforcing a single writer or a quorum, a partition produces split-brain, where two nodes both believe they hold the authoritative copy of a session and diverge. Even without a partition, replication lag means a read on one node can be stale relative to a very recent write on another.
- Performance: write latency goes up (synchronous replication waits on other nodes; asynchronous replication is fast but reintroduces the staleness problem it was meant to avoid). Read latency can stay low if reads are served from local replicas. Write throughput is bounded by replication and, if used, consensus overhead.
3. Externalizing state (shared cache or durable store)
- How it works: instances stop holding session state at all. Every request reads from and writes to a shared store (Redis, Memcached, or a durable database), which makes every instance interchangeable.
- Operational complexity: moderate. You now operate one more piece of infrastructure (a cache or database cluster: sizing, eviction policy if it's a cache, persistence if it needs to be durable) and the application changes to fetch and save state instead of holding it.
- Failure modes: the store itself becomes the thing that must not go down, so it needs its own high availability, replicas, and a defined fallback if it's briefly unreachable. Cache-invalidation bugs (serving stale state after a write, or evicting state that should have survived) are the main correctness risk. Network dependency between every app request and the store adds a new failure surface that didn't exist with local memory.
- Performance: a network hop per read/write adds latency relative to local memory, but it is predictable and independent of which instance serves the request, so it scales cleanly with the store's own capacity. A local read-through cache in front of the store recovers most of the latency for repeat reads.
Worked example
Consider a live-chat product where each open chat session tracks typing indicators, unread counts, and the last 20 messages in a rolling buffer, all ephemeral and rebuilt from durable message history if lost. The team starts with sticky sessions during the MVP: single-digit instance count, acceptable risk of a lost typing-indicator state on deploy. At 30 instances and daily autoscaling swings, rebalancing during scale-events starts dropping a visible fraction of active typing indicators on every scale-up, and hot users (large group chats) overload single instances that aggregate metrics don't flag as unhealthy. The team considers active-active replication to keep the local-memory latency but rejects it: the correctness bar for typing indicators is low (occasional staleness is invisible to users), so the complexity of consensus or CRDTs isn't earning its keep. They externalize instead: session state moves to a Redis cluster, keyed by chat id, with a short TTL so abandoned sessions clean up automatically. Every instance becomes interchangeable, rebalancing no longer drops state, and the added latency (one Redis round trip per message event) is well under the product's tolerance for a chat UI.
Trade-offs & pitfalls
- Choosing active-active replication for its latency profile without a real need for both local-memory speed and multi-node write availability at once is the most common overreach; most services that reach for it would be better served by externalization plus a local read-through cache.
- Assuming sticky sessions "just work" at scale and only discovering the rebalancing-churn problem after autoscaling is already live is a frequent operational surprise; load-test the rebalance path, not just steady-state.
- With externalized state, forgetting that the store is now a dependency of every request (not an optional side-system) leads to under-provisioning its availability relative to the application tier it's supposed to be simplifying.
- With active-active replication, treating eventual consistency as "good enough" without checking whether the specific session data has a correctness requirement (e.g., a shopping cart total versus a typing indicator) can silently introduce bugs that only show up under network partition, which is exactly when they're hardest to debug.
A hot cache entry is about to expire, or a backend service is recovering from an outage, and you expect a flood of simultaneous requests to hit the same key or the same origin at once. Design a comprehensive strategy to prevent this 'thundering herd' across a globally distributed cache and service fleet, covering both techniques that stop the herd from forming in the first place and techniques that contain it once it starts. What would you monitor and alert on to confirm the mitigation is working, and what trade-off would you make between complexity and protection?
Sample Answer
Direct answer
A thundering herd happens when a large number of concurrent requests converge on the same cache key or origin at the same instant, whether that is one hot key expiring, a cache flush after a deploy, or a backend service coming back online after an outage. The strategy has two halves: prevent the herd from forming in the first place (spread out when things expire and who has to pay for a miss), and contain it once it starts (make sure only a small, bounded number of requests actually reach the origin while everyone else waits on or reuses that result). The right mix of techniques is a complexity-versus-protection trade-off: cheap local techniques handle the common case, and the more expensive coordinated techniques get added only where the blast radius or the cost of getting it wrong justifies them.
The simplest version, as a baseline
Two inexpensive techniques already cover a large fraction of real thundering-herd cases: adding random jitter to time-to-live (TTL) values (so a batch of keys set at the same moment do not all expire at the same moment) combined with request coalescing, sometimes called singleflight (so that when a key does expire, only one of the many concurrent requests for it actually fetches from origin, and the rest wait for that one result). Everything below either extends this baseline for a bigger blast radius or handles a different trigger for the same underlying problem.
sequenceDiagram
participant R1 as Request 1..N
participant Svc as Service
participant Lock as Singleflight lock
participant Origin as Origin / DB
R1->>Svc: request for expired key
Svc->>Lock: acquire per-key lock
alt lock acquired
Lock->>Origin: single fetch
Origin-->>Lock: fresh value
Lock-->>Svc: value + refresh cache
else lock held by another request
Lock-->>Svc: wait, then reuse result
end
Svc-->>R1: response (fresh or briefly stale)
Preventative techniques (stop the herd from forming)
- Jittered TTLs: instead of a flat TTL, add randomness (for example, base TTL plus or minus 5-20%) so a set of keys populated together do not expire together.
- Staggered renewals: refresh keys on a schedule spread out over time rather than all at once, particularly for keys that were all warmed at the same moment (after a deploy, a region failover, or a bulk cache-priming job).
- Background refreshers: proactively refresh a known hot key before it expires, so readers never actually observe a miss for that key under normal conditions.
Reactive techniques (contain the herd once it starts)
- Request coalescing / singleflight: on a miss, one request fetches from origin while concurrent requests for the same key wait on that result instead of issuing their own origin calls.
- Leader-based warmers: elect one instance (via a lease, not a permanent role) to be responsible for refreshing a given hot key or key range, so refresh work itself does not become another source of duplicate origin load.
- Per-key locks: a more granular form of coalescing, useful when singleflight is implemented per-process and needs a cross-process equivalent (a short-lived distributed lock) to coordinate across many service instances.
- Circuit breakers: once the origin's error rate or latency crosses a threshold, stop sending it more traffic and serve a fallback (often the stale cached value) instead of piling more failing requests onto an already-struggling origin. In plain terms, a breaker has three states: closed, where traffic flows normally while the breaker just watches the error/latency rate; open, where it stops sending calls to the origin entirely once that rate crosses its threshold, serving the fallback instead; and half-open, where it periodically lets one trial request through to check whether the origin has recovered before fully closing again. The full mechanics of breaker states and how they interact with retries go deeper than that summary; here, the breaker's job is specifically to stop a cache-miss storm from becoming an origin-overload storm.
- Rate limits: cap the request rate a single key or a single origin dependency can absorb, as a hard backstop under the other techniques.
- Grace caches serving stale-while-revalidating: keep serving the last known-good value past its nominal expiration while a refresh happens in the background, rather than making every reader wait on that refresh.
- Queuing / coordinator patterns: for the largest blast-radius cases, put the refresh work behind a queue with a single (or small, bounded) set of workers pulling from it, so origin load during a mass-invalidation event is capped by queue-consumer concurrency rather than by however many callers happened to miss at once.
Thundering herd is not only a cache problem
The same failure shape hits connection pools: a backend service recovering from an outage can see every client that was queued or retrying suddenly reconnect and check out a database or HTTP connection at once, exhausting the pool the same way a cache stampede exhausts an origin. The mitigations are the same family of ideas applied to a different resource: jittered reconnect/retry backoff instead of jittered TTL, and a bounded admission queue at the pool instead of request coalescing at the cache.
Worked incident case study: a stale-price outage
A pricing update was pushed, but the cache continued serving stale cached prices for several minutes, an invalidation gap, not a stampede, but the kind of incident that motivates having both invalidation correctness and stampede protection in the same design: a fix that improves one without the other still leaves revenue exposure on the table. The response has three time horizons:
- Immediate: force-invalidate the specific affected keys (or, if scope is unclear, accept a short blanket TTL reduction) to stop the bleeding, while watching origin load closely since a mass invalidation of price keys is itself a thundering-herd trigger, so this step should go out with jittered expiration or through the coordinator pattern above, not as one giant simultaneous purge.
- Short-term: add an event-driven invalidation path (publish an invalidation message on price update) so the next price change does not depend on a TTL window at all.
- Long-term: add a monitoring check that compares cached price against source-of-truth price on a sample basis, so a future invalidation gap is caught by an alert instead of by a customer or an audit.
Worked scenario: a flash sale
A flash sale that invalidates millions of product keys at once is a deliberately engineered thundering herd, not an accidental one, so it needs a pre-sale runbook rather than relying on steady-state defenses alone:
- Days before: identify the key set that will be invalidated and pre-warm replacement values (new prices, new stock) into a shadow key space.
- Hours before: switch traffic to read from the shadow key space via a fast pointer/alias flip rather than invalidating the live keys directly, avoiding a simultaneous mass-miss entirely.
- At sale start: keep circuit breakers and rate limits armed on the origin regardless, as a backstop for any key the pre-warm missed.
- Post-sale: retire the old key space and confirm hit ratios and origin load returned to baseline.
Concrete trigger: one hot key expiring
The narrowest version of this problem, a single popular key expiring and producing a flood of simultaneous requests that overloads the database, is mitigated specifically by a read-through warmer: a background process that refreshes that specific key proactively, on a schedule tied to its own TTL, so normal readers never observe the miss that would otherwise trigger the flood.
Shipping the mitigation itself safely
Rolling out a stampede fix is its own small project, not a one-shot deploy: use a staged rollout strategy (enable coalescing or jitter for one key namespace or one region first) rather than flipping it on globally, since a bug in the mitigation's own locking logic can create a new outage rather than preventing one. Pair the rollout with validation experiments, a controlled comparison of origin load and P95 (95th-percentile) latency with the mitigation on versus off for equivalent traffic, so the team has evidence the change worked rather than an assumption that it did.
Monitoring and alerting
Track cache miss rate per key (a sudden spike for one key is the earliest signal of a forming herd), waiter/queue depth at the coalescing layer, origin error rate and latency, connection-pool saturation, and circuit-breaker state transitions. Alert on a sharp rise in per-key miss rate or waiter count before it turns into an origin-side incident, not after.
Trade-offs and pitfalls
Local, per-process singleflight combined with TTL jitter is cheap and covers most real traffic patterns; it is the right default. Cross-process coordination (distributed locks, leader election for warmers, a queue-based coordinator) adds real protection for large blast-radius events like a flash sale, but it adds operational complexity, another thing that can itself fail, and some latency overhead from the coordination itself. The main pitfall is reaching for the expensive coordinated techniques everywhere out of caution: that adds failure surface without adding proportionate protection for keys that were never going to produce a large herd in the first place. The second pitfall is validating a mitigation with a synthetic load test but never with a real fault-injection or game-day exercise: a load test proves the happy path holds up under volume, not that the coalescing and breaker logic actually engage correctly the moment a real dependency starts failing.
Unlock Full Question Bank
Get access to all Scalability Patterns and Techniques interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.