Caching Strategies & In-Memory Optimization Questions
Designing cache layers to cut redundant work and speed up reads, and the correctness costs that come with them. Covers cache placement across client, CDN, application, and in-memory store tiers, including platform-specific caching on mobile (in-memory and disk caches on iOS and Android, secure on-device token storage) and in the browser (localStorage, IndexedDB, Service Workers). Covers eviction policies, TTLs, write-through vs write-back, warming, and invalidation, plus cache stampede and thundering-herd mitigation when a hot key expires under load. Also covers using an in-memory store like Redis directly rather than only as a cache: distributed locks, counters, rate limiters, and leaderboards. Includes distributed and sharded cache architecture (replication, failover, sizing, migration) and the operational side of running one: health monitoring, alerting, and incident runbooks, plus the security and privacy risks caching introduces, such as cache poisoning and caching PII across shared tenants. Emphasizes hit-rate reasoning and the staleness/consistency trade-offs caching introduces.
Given a workload where object access frequencies follow a Zipf distribution (skew), explain how LRU and TTL-based eviction policies will affect steady-state cache hit ratio. Given: 1M unique objects, cache capacity 100k items, Zipf parameter s=0.8. Describe how to approximate hit ratio, and discuss how increasing skew changes tuning decisions.
Sample Answer
Setup
A Zipf distribution is a common model for real-world access skew: a small number of items get a disproportionate share of traffic, and popularity falls off as roughly 1/rank^s, where s (the skew parameter) controls how sharp that falloff is. Higher s means MORE skew (traffic concentrates on fewer hot items); s near 0 means access is closer to uniform across all items. With 1 million unique objects and a cache that can only hold 100,000 (10% of the catalog), the question is what steady-state hit ratio LRU and TTL-based eviction actually achieve, and why.
How LRU behaves under a stationary Zipf distribution
Under LRU (least recently used) eviction with a STATIC (non-shifting) Zipf popularity distribution, the cache converges toward holding approximately the top-K most popular items, because popular items are, by construction, accessed frequently enough that they're re-touched (and thus kept "recently used") long before their turn to be evicted comes up, while unpopular items go long stretches without a touch and get evicted quickly after their rare accesses. This means the steady-state LRU hit ratio for a stationary Zipf workload is well approximated by the IDEAL "cache holds exactly the top-K most popular items" bound:
hit_ratio(K) = sum_{i=1}^{K} i^-s / sum_{i=1}^{N} i^-s
Intuition: the numerator is the total popularity mass of the K most popular items (if the cache held exactly those, this is the fraction of all requests it would serve); the denominator normalizes across the full catalog of N items so the result is a fraction between 0 and 1.
A small hand-traceable check first (N=10 objects, K=3, s=0.8), before trusting the million-object numbers below: i^-0.8 for i=1..10 gives 1.0000, 0.5743, 0.4152, 0.3299, 0.2759, 0.2385, 0.2108, 0.1895, 0.1724, 0.1585. Summing the first 3 terms: 1.0000 + 0.5743 + 0.4152 = 1.9896, and the full sum of all 10 terms is 3.5651, so hit_ratio(3) = 1.9896 / 3.5651 = 55.8%: with a 3-item cache out of 10 objects (30% of the catalog) under this skew, about 56% of requests hit. The million-object numbers below are the exact same summation, just carried out to N=1,000,000 and K=100,000 by computer instead of by hand.
Computed values (N=1,000,000, K=100,000, so the cache holds the top 10% of the catalog by rank):
s=0.6 -> hit ratio ~ 39.6%
s=0.8 -> hit ratio ~ 60.9%
s=1.0 -> hit ratio ~ 84.0%
s=1.2 -> hit ratio ~ 96.5%
(computed directly by summing i^-s for i=1..K and i=1..N and taking the ratio; this is the theoretical LRU-approximation ceiling, not a fabricated constant, and it moves a lot with s, which is the point).
For the stated s=0.8, roughly 61% of requests hit the cache at steady state, an order-of-magnitude better than the naive expectation that a 10%-sized cache should give roughly a 10% hit ratio; that naive expectation is exactly what you'd get under a UNIFORM access distribution (s=0), and it's wrong here specifically because of the skew.
How TTL-based eviction differs from LRU here
TTL eviction removes an item after a fixed time regardless of popularity, so a TTL policy on its own doesn't preferentially retain popular items the way LRU's recency-based eviction naturally does. A short TTL evicts popular and unpopular items alike on the same schedule, which means a TTL-only policy achieves a LOWER hit ratio than LRU for the same effective cache occupancy under a skewed distribution, because it wastes cache space re-fetching popular items that LRU would have simply kept resident. TTL is solving a different problem (bounding staleness) than LRU is (maximizing hit ratio under a capacity constraint), and the two are often combined: TTL as a staleness ceiling, LRU (or an LFU-like policy, LFU meaning least-frequently-used, evicting whichever item has been accessed the fewest times rather than least recently) as the eviction mechanism that decides what to keep resident within that ceiling. Plain LFU has its own failure mode though: an item that was popular once and racked up a huge access count stays hard to evict long after it's gone cold, because its count only ever goes up. A decay mechanism (periodically halving, or otherwise aging down, every item's frequency count) fixes that by letting old popularity fade, so a currently-hot item can outrank a formerly-hot one within a bounded number of decay cycles instead of never catching up; this is why production LFU implementations are almost always decay-based rather than plain cumulative-count LFU. Pure TTL-only eviction with no capacity-driven LRU/LFU component behaves close to the uniform-access baseline for hit-ratio purposes, since it isn't popularity-aware at all.
How increasing skew changes tuning decisions
- Higher skew (larger s): a small cache captures most of the useful hit ratio (
s=1.2above already reaches 96.5% with only 10% of the catalog resident), so there's little benefit to over-provisioning cache capacity beyond the point where the hit-ratio curve has clearly flattened; the marginal item added to the cache at that point is barely ever requested. - Lower skew (smaller s, more uniform access): hit ratio scales closer to linearly with cache size relative to catalog size (
s=0.6giving only 39.6% for a 10%-sized cache, well below thes=1.2case), so capacity decisions matter much more, and a fixed-size cache that felt generous for a skewed workload can feel badly undersized if the workload's skew decreases (e.g. a catalog broadening, or a promotion driving traffic to previously-unpopular long-tail items). - Practically: measure the ACTUAL empirical
sfor your workload (don't assume it), because tuning decisions (cache size, whether LFU is worth the complexity over LRU, how much headroom to provision) are highly sensitive to it, and a workload's skew can drift over time as the catalog and user base change.
Trade-offs
The formula above assumes a stationary distribution and enough traffic volume for LRU to actually converge to the top-K approximation; a rapidly shifting popularity distribution (breaking news, a viral item) makes LRU (and this formula) less accurate, since LRU takes some time to "learn" the new popularity ranking after a shift, during which the achieved hit ratio is temporarily worse than the steady-state formula predicts.
Describe distributed cache invalidation patterns for backend caches when many services and regions hold cached copies of objects. Propose an implementation using Redis Pub/Sub or Kafka to broadcast invalidations, and explain how a mobile client could rely on that mechanism (directly or via push) to keep its cache consistent. Discuss fanout limitations and mitigations.
Sample Answer
Framing
Distributed cache invalidation means keeping many independent caches, one per service instance, one per region, consistent when the underlying data changes, without a central lock on every read.
Invalidation patterns
TTL-only is the simplest: no coordination, bounded staleness, but a write can be visible late by up to the full TTL. Event-driven invalidation publishes a change event on write and subscribers purge locally, near real time but dependent on delivery. Versioned or tagged keys embed a version in the key itself (user:123:v7), so an old entry simply becomes orphaned rather than needing an active delete, this sidesteps the "who deletes what" fanout problem entirely, at the cost of key churn.
Broadcasting invalidations across services and regions
Redis Pub/Sub is low latency but fire-and-forget: a subscriber that is disconnected when the message publishes, a whole region during a deploy, a service recovering from an outage, never receives it. That makes Pub/Sub unsuitable alone for correctness-critical cross-region invalidation. Kafka (a durable, partitioned, replayable log) closes exactly that gap: invalidation events are retained, each consumer tracks its own offset, and a service that was offline can replay from where it left off and catch up on everything it missed. Recommended shape: publish invalidation events to a Kafka topic keyed by entity id so all events for one entity stay ordered on one partition; each region's invalidation consumer applies them locally. Use Redis Pub/Sub only as a same-region low-latency fast path layered on top of the durable Kafka log, not as a replacement for it.
How a mobile client relies on this
A mobile device cannot hold a Kafka consumer, so it participates indirectly. Either the backend converts a qualifying invalidation event into a silent push notification (a data-only APNs/FCM message telling the client "resource X is stale, refetch on next foreground"), or, more robust to lost pushes, the client simply uses a modest TTL plus a conditional fetch (ETag/If-None-Match) on foreground. Push delivery is not guaranteed, so it should be a latency optimization, not the sole correctness mechanism, for a client the backend does not fully control.
Fanout limitations and mitigations
A hot entity's update can trigger an invalidation burst to thousands of subscriber caches at once, and if that burst also triggers a synchronous stampede of refetches, the load spike compounds. Mitigate with: batching or debouncing invalidation events for a burst of writes to the same entity within a short window; version-key invalidation, which needs no fanout callback at all since old versions simply age out; and rate-limiting or backpressure on the invalidation consumer so a burst does not overwhelm downstream cache-clear calls.
Write pattern choice as part of the coherence strategy
Cache-aside with event-driven invalidation is the common default, good developer ergonomics, but exposed to exactly the missed-delivery risk above. Write-through keeps the writing region's own cache correct at write time, so only propagation TO OTHER regions remains a distributed problem. Write-behind is the riskiest to pair with distributed invalidation, because the backing store the invalidation events describe changes to is intentionally behind the cache, so a naive subscriber reading straight from that store during the write-behind lag can propagate a stale value. Default to write-through or cache-aside for anything that feeds this invalidation pipeline; reserve write-behind for cache tiers, like ephemeral metrics, that are not part of it.
Given observed traffic (QPS), object-size distribution (mean and variance), expected working set distribution (for example Zipf with parameter s), and an acceptable miss-latency budget, derive a method to calculate required cache memory to achieve a target hit rate. Show formulas, explain assumptions, and describe conservative buffers to account for TTL and growth.
Sample Answer
Setup
Given the traffic rate, the object-size distribution, the shape of the popularity distribution (Zipf with parameter s, a skewed distribution where a small share of objects accounts for a disproportionate share of traffic, and higher s means more skew), and a target hit rate, the question is how much memory to provision. The method: find the smallest number of distinct objects, K, that need to be resident to achieve the target hit rate under the assumed popularity distribution, then convert K into bytes using the object-size distribution, then add a safety buffer.
Step 1: relate hit rate to catalog coverage under Zipf
For a Zipf(s) popularity distribution over N total distinct objects, the fraction of traffic served by caching exactly the K most popular objects is:
coverage(K) = sum_{i=1}^{K} i^-s / sum_{i=1}^{N} i^-s
This is the same relationship used for estimating hit ratio from a given cache size; here we invert it, searching for the smallest K such that coverage(K) >= target_hit_rate. This is a monotonically increasing function of K, so a straightforward search (linear scan, or binary search for large N) finds the minimal K quickly.
Step 2: convert K into a memory budget
raw_bytes = K * (avg_object_size + per_entry_overhead)
avg_object_size comes from the observed object-size distribution (use the actual mean of the objects likely to BE in the top-K, not the mean over the whole catalog, if size and popularity are correlated in either direction; for a first-pass estimate, the overall mean is a reasonable starting assumption, refine if size and popularity turn out to correlate). per_entry_overhead accounts for the cache's own bookkeeping per key (the key string itself, hash-table/skip-list node pointers, TTL (time to live) metadata, an object header), which is easy to forget and can matter a lot for small objects (a 50-byte cached value with 120 bytes of overhead is mostly overhead, not payload).
Step 3: conservative buffer
Add headroom for:
- Catalog growth: N will grow over the cache's operational lifetime; provisioning for today's N with zero margin means a re-provisioning conversation the day traffic grows.
- TTL-driven duplication: if the cache uses TTL-based expiry (not purely a capacity-bound LRU/LFU, least-recently-used / least-frequently-used, eviction), there can be a period where both an about-to-expire entry and its freshly-refreshed replacement are briefly resident, or where TTL jitter (a good practice to avoid synchronized mass-expiry) means the ACTUAL resident count at any instant can exceed the theoretical minimum K somewhat.
- QPS (queries per second) isn't directly in the formula above but validates the assumption: the coverage(K) relationship assumes enough traffic volume for the popularity ranking to be reliably sampled and for LRU/LFU eviction to actually converge toward keeping the top-K resident; at very low QPS relative to catalog size, achieved hit rate can undershoot this theoretical estimate simply because there hasn't been enough traffic to establish which items are actually popular yet.
Worked example (computed directly, not assumed)
N=1,000,000 objects, Zipf s=0.8, target hit rate=80%, average object size 4 KiB (4,096 bytes), per-entry overhead 120 bytes, 30% growth/TTL buffer:
Searching for the smallest K with coverage(K) >= 80% (a monotonic scan, or binary search over this large an N) converges like this:
K=50,000 coverage=52.25%
K=100,000 coverage=60.91%
K=200,000 coverage=70.85%
K=300,000 coverage=77.33%
K=350,000 coverage=79.94%
K=351,268 coverage=80.00% <- smallest K clearing the 80% target
minimum resident objects K needed = 351,268 (35.1% of the catalog)
raw memory = 351,268 * (4,096 B + 120 B) = 1.38 GiB
with 30% buffer -> provision 1.79 GiB
Note how much larger K needs to be here (35.1% of the catalog) than a 10%-of-catalog cache gives for this same skew parameter: from the search trace above, K=100,000 (10% of the catalog) only reaches 60.91% hit rate, well short of the 80% target here, and pushing from 61% to an 80% target requires a meaningfully larger fraction of the catalog resident, because the marginal, less-popular objects contribute less and less hit-rate benefit per object added (this is the diminishing-returns shape of the coverage curve, steep near the head of the popularity ranking and flat in the tail).
Assumptions to state explicitly when presenting this estimate
- The popularity distribution is actually well-modeled by Zipf with the assumed s; validate this against real access logs rather than assuming it, since the required K is highly sensitive to s: holding K fixed at the 351,268 computed above, coverage comes out to 65.7% at s=0.6, 80.0% at s=0.8, and 92.7% at s=1.0, so a misjudged skew parameter alone can swing the achieved hit rate by tens of percentage points at the same provisioned memory.
- The eviction policy actually approximates "keep the top-K most popular objects" (true for LRU/LFU under a reasonably stationary workload with enough traffic, not true for a naive TTL-only or random-eviction policy, which would need a different, generally larger K to hit the same target).
- Object sizes and popularity aren't strongly correlated in a way that breaks the average-size assumption (if, say, the most popular objects are also disproportionately the largest, the memory estimate understates the true requirement and should use a popularity-weighted average size instead of the flat catalog average).
Trade-offs
This estimate gives a defensible starting provisioning number, not a guarantee; treat it as the input to a monitored rollout (provision to this estimate, then watch the ACTUAL measured hit rate in production and adjust) rather than a one-time calculation trusted forever, since real traffic patterns drift and the Zipf-s assumption is itself an approximation of reality, not reality.
You're sizing a Redis cluster for a service that expects 50k RPS of short reads and occasional writes. Each cached value averages 2KB, and you want 2x headroom and replication for durability. Sketch the calculation to estimate memory per node, number of shards, and approximate network/connection requirements.
Sample Answer
Direct answer
Requests per second (RPS) and average value size directly give you network bandwidth, that part needs no assumptions. Memory sizing needs one more input the question doesn't give you directly: how many distinct keys are actually resident (the working set), so state that assumption explicitly and derive from it. Shard count is then the larger of what memory needs and what throughput needs.
Structured elaboration
Network/bandwidth (fully derivable from the given numbers, no assumption needed):
bandwidth=RPS×value_sizeThe intuition: every request moves roughly one value's worth of bytes, so total bandwidth is just how many requests per second times how big each one is.
Memory (requires one stated assumption: the size of the working set, since RPS alone tells you request rate, not how many distinct keys exist):
memory≈keys×(value_size+overhead)×headroom×(1+replicas)The intuition: total memory is the raw data size, inflated by Redis's own per-key bookkeeping overhead, then inflated again by however much spare headroom you want, then doubled (or more) for however many full replica copies you keep for durability.
Shards (the larger of a memory-driven count and a throughput-driven count):
shards=⌈ops_ceiling_per_shardtarget_RPS⌉The intuition: if the workload needs more requests per second than a single shard can sustain, you need enough shards, in parallel, to cover the total.
Worked example
Given (from the question):
RPS = 50,000
value_size = 2 KB = 2048 bytes
headroom = 2x
replicas = 1 (durability)
Bandwidth (no assumption needed):
bandwidth = 50,000 * 2048 = 102,400,000 bytes/s = 102.4 MB/s
with 2x headroom target: 204.8 MB/s
Memory (stated assumptions: 5,000,000 distinct keys in the working set,
100 bytes per-key overhead for the key string, TTL metadata, and hash entry):
raw = 5,000,000 * (2048 + 100) = 10,740,000,000 bytes ≈ 10.00 GiB
with 2x headroom: 20.00 GiB (primary capacity to provision)
with 1 replica: 20.00 * 2 = 40.00 GiB total cluster memory
Shards (stated assumptions: a 25 GiB usable node, and a conservative
30,000 ops/sec ceiling per primary for ~2KB values):
target_RPS (with 2x headroom) = 50,000 * 2 = 100,000
memory-driven: ceil(20.00 / 25) = 1 shard
throughput-driven: ceil(100,000 / 30,000) = 4 shards
provision: 4 shards (the larger of the two), x2 nodes each with a replica
= 8 nodes total
The throughput requirement, not memory, is what actually drives shard count here, a common pattern for caches holding small-to-medium values at high request rates: you run out of per-node request capacity long before you run out of per-node memory.
Trade-offs and pitfalls
The working-set size and the per-shard ops ceiling are both stated assumptions, not measured facts, in a real sizing exercise pull the working-set size from actual key-count telemetry and the ops ceiling from a load test against your real value size and network setup, since both vary meaningfully with payload size, pipelining, and whether TLS is in use. Connection count matters too: total client connections scale with (number of app instances) times (connection pool size per instance) times (shard count), keep that comfortably under each shard's configured connection limit, and prefer connection pooling and multiplexing over one connection per request to avoid connection storms during a traffic spike.
Design a session caching approach using Redis for a SaaS product serving 50 million monthly active users. Discuss memory estimation, TTL strategy, stickiness vs stateless sessions, clustering, eviction policies, and how you would handle global distribution and failover.
Sample Answer
Direct answer
Store sessions as small key-value entries in a sharded, replicated Redis cluster, keyed by session ID, with a sliding time-to-live (TTL) renewed on activity. Keep the application tier stateless (any server can serve any request) rather than sticky, size the cluster from a concurrency estimate rather than the full monthly active user (MAU, users active at least once in a month) count, and plan failover explicitly rather than assuming a single region or a single primary never goes down.
Structured elaboration
Memory estimation: monthly active users (MAU) is the wrong number to size memory against directly, most of those 50 million users aren't concurrently logged in at any given moment. Size against a concurrency assumption instead.
memory≈concurrent_sessions×(session_size+per_key_overhead)×(1+replicas)The intuition: total memory is just "how many sessions are alive at once" times "how big each one is, plus Redis's own bookkeeping," doubled if every shard has a replica holding a full second copy for failover.
TTL strategy: use a sliding TTL, refreshed on each authenticated request, so an active user's session never expires mid-use, paired with an absolute maximum session lifetime (say, requiring re-authentication after some fixed number of hours regardless of activity) as a security backstop against a session living forever on a device that's always active.
Stickiness vs. stateless: prefer a stateless application tier, every request carries a session ID, any app server looks it up in Redis, no server holds session state in its own memory. This is what lets you autoscale the application tier and fail an app server over instantly, without needing sticky load-balancer routing that ties a user to one specific server. Only consider stickiness if the Redis round-trip latency itself becomes the bottleneck, which is rare for a well-sized cluster.
Clustering: shard by hashing the session ID across primary nodes (Redis Cluster's hash-slot model, or a managed equivalent), each primary paired with at least one replica for durability and fast failover.
Global distribution and failover: run a regional cluster per major user region behind geo-routing, so most users hit a nearby cluster. Be explicit and honest about the trade-off rather than implying transparent global consistency from a single cluster: a regional failure either fails over to a same-region replica (fast, transparent to the user) or, for a full regional outage, may require the affected users to re-authenticate against another region rather than seamlessly carrying a session across regions, that's a real limitation worth stating up front rather than glossing over.
Worked example
MAU = 50,000,000
peak_concurrency_pct = 0.05 # assumption: 5% of MAU concurrently active at peak
concurrent_sessions = 50,000,000 * 0.05 = 2,500,000
session_bytes = 2 * 1024 # assumption: ~2KB per session payload
overhead_bytes = 100 # assumption: per-key overhead (key string, TTL metadata, hash entry)
raw_bytes = 2,500,000 * (2048 + 100) = 5,370,000,000 bytes ≈ 5.00 GiB
with_replica = 5.00 GiB * 2 = 10.00 GiB total cluster memory
That 10 GiB is small enough to fit comfortably on a handful of modestly sized managed Redis nodes; the real constraint at this scale is more often connection count and command throughput across the app tier's many stateless instances than raw memory.
flowchart LR
A[App tier, stateless] --> R[Router: hash session_id]
R --> S1[Shard 1 primary]
R --> S2[Shard 2 primary]
S1 --> S1R[Shard 1 replica]
S2 --> S2R[Shard 2 replica]
S1 -. fails .-> F1[Automated failover promotes S1R]
F1 --> S1
Trade-offs and pitfalls
The 5% concurrency assumption is exactly that, an assumption, verify it against real analytics (concurrent-session telemetry, not MAU) before provisioning, a product with long average session durations or a strong daily peak will have a very different real concurrency fraction. Cross-region session replication adds real complexity and latency for a benefit (seamless cross-region failover) many products don't actually need, be explicit with stakeholders about which failure mode you're accepting rather than silently under-designing it. A sliding TTL renewed on every request adds a small write on every request, at this scale that's a meaningful fraction of total cluster command volume, worth confirming the cluster is sized for that write rate, not just the memory footprint.
Unlock Full Question Bank
Get access to all Caching Strategies & In-Memory Optimization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.