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.
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.
What monitoring metrics and instrumentation would you put in place to evaluate cache effectiveness across multiple layers (browser, CDN, app cache, Redis)? Include at least five concrete metrics, how you would compute hit ratio, and how to alert when caches are degrading.
Sample Answer
Treat each layer's hit ratio as its own SLI
An SLI (service level indicator, a measured signal of how well a system is doing) and an SLO (service level objective, the target value set for that indicator) are useful here because a miss costs a different amount at each layer: a browser cache miss costs a network round trip, a Redis miss costs a database query. Give each layer its own SLI and its own SLO instead of one blended number.
Five concrete metrics, one per layer plus the layer that catches everything else
- Browser cache hit ratio: from the browser's Resource Timing API, a request with
transferSize == 0(or an encoded 304 Not Modified) counts as a hit. - CDN edge hit ratio: most CDNs expose this directly, or you can derive it from the response header they add (commonly
X-Cache: HIT/MISS/STALE). - Application in-process cache hit ratio: an in-memory map inside the app server itself, instrumented with a simple hit/miss counter.
- Redis hit ratio:
keyspace_hits / (keyspace_hits + keyspace_misses)from Redis'sINFOcommand. - Origin/database load, read as an inverse signal: queries per second reaching the database. This should fall as the upstream layers' hit ratios rise, and a rising DB load with unchanged upstream hit ratios is itself a red flag (something is bypassing the caches).
Computing hit ratio (same formula, different source per layer)
hit ratio=hits+misseshitsA worked funnel example, to see why every layer's ratio compounds
Assume 1,000,000 page views in a day.
- Browser cache absorbs 40% -> 600,000 requests reach the network.
- Of those, the CDN's hit ratio is 90% -> 60,000 reach the application/origin infrastructure.
- Of those, the application's in-process cache absorbs 50% -> 30,000 reach Redis.
- Of those, Redis's hit ratio is 95% -> only 1,500 requests reach the database.
That is 1,500 out of 1,000,000, or 0.15%, actually reaching the database. This is why a small drop at an EARLY layer (browser or CDN) matters more in absolute terms than the same percentage drop at Redis: it changes the volume every downstream layer has to absorb.
Dashboard: a heatmap, not just four separate lines
Lay the four layers as rows and time buckets (e.g., 5-minute buckets across 24 hours) as columns, with hit ratio as color intensity. This surfaces patterns four separate line charts hide: a diagonal streak across layers right after a deploy (cache invalidated, slowly refilling), or one layer staying cold while the others are healthy (that layer's caching logic is broken, not a traffic pattern change).
Alerting when caches are degrading
- Set an SLO per layer (for example: browser >= 30%, CDN >= 85%, app cache >= 40%, Redis >= 95%, since Redis sits closest to the expensive database and a miss there is the most costly). These are illustrative starting points to tune against real traffic, not universal numbers.
- Alert on burn rate (how fast the SLO is being eaten), not just a static threshold: a hit ratio sliding from 95% to 90% over an hour is a slow drift worth a ticket; the same drop in 2 minutes is worth a page.
- Alert louder when TWO OR MORE layers degrade at once. A single layer dipping is often self-healing (a cache warming back up after a deploy); simultaneous multi-layer degradation usually means an upstream dependency actually failed.
For a user profile service that receives frequent updates, explain the trade-offs between write-through caching and write-behind caching. Which would you recommend as a Solutions Architect, what operational safeguards would you require, and how would you mitigate data-loss risks?
Sample Answer
Direct answer
Write-through caching writes to the cache and synchronously writes through to durable storage before acknowledging the caller, trading write latency for strong durability. Write-back (write-behind) caching acknowledges immediately after writing to the cache and flushes to durable storage asynchronously, trading a data-loss window for much lower write latency. For a frequently-updated user profile service, recommend write-through, or write-back only for specific low-value fields, with real operational safeguards around the flush path.
Structured elaboration
Write-through: every write goes to the cache and the durable store together, and the caller only gets an acknowledgment once both have succeeded. Reads are always fast and always consistent with what's durably stored. Writes are exactly as slow as the underlying database write, the cache doesn't speed up writes at all here, only reads.
Write-back: the write lands in the cache, the caller gets an immediate acknowledgment, and the durable write happens later (often batched with other pending writes for efficiency). Writes are fast. The risk: if the cache node holding that unflushed write fails before the flush happens, that write is gone, the database never saw it, even though the caller was already told it succeeded.
Recommendation and reasoning for a user profile service: profile fields (name, email, settings) are exactly the kind of data users notice and complain about if it's silently lost, "I changed my email and it reverted" is a support ticket and a trust problem, not just an inconvenience. That argues for write-through as the default. A hybrid is reasonable: write-through for identity-bearing fields (email, name, security settings), write-back only for high-volume, low-consequence fields like last_active_at where losing a few seconds of precision on a timestamp is genuinely fine.
Operational safeguards to require if any write-back path is used at all:
- Replicate the cache itself (not just the database), so a single cache node failure doesn't lose an unflushed write, the replica can still flush it.
- Monitor the write-back queue depth and flush lag explicitly, and alert before it grows unbounded, a growing queue is an early warning of a downstream database problem, not just a caching detail.
- Cap the maximum unflushed window (flush within seconds, not minutes), the shorter the window, the smaller the blast radius of a node failure.
- Alert on flush failures specifically, a silently failing flush job is the single most dangerous failure mode here, since nothing else signals it until data is already missing.
Worked example
A user updates their email address. With write-through, the request blocks until both the cache and the database confirm the write, roughly the database's own write latency, and the caller only sees "success" once it's genuinely durable. With write-back, the same request would return "success" the instant the cache accepted it, before the database has seen it at all; if that cache node then crashed in the next second, the user's new email is gone from the database even though the app already told them it was saved, exactly the scenario that argues for write-through on this field.
Trade-offs and pitfalls
Write-through's honesty about latency is also its main cost, if the database write path is slow, every profile update feels slow to the user, that's a real product trade-off, not just an implementation detail. A common mistake with write-back is treating the durable store as "eventually written" without actually building the safeguards above, silently accepting data-loss risk that was never explicitly signed off on by the product owner, always make the risk and its mitigation an explicit decision, not a default that crept in because it was faster to build.
SSR vs CSR: For an SEO-sensitive product marketing site with some personalized widgets (e.g., 'Welcome back, <name>'), outline a hybrid server-side rendering strategy that maximizes SEO benefit and edge-caching while preserving personalization and performance. Include headers, CDN configuration, and assembly techniques.
Sample Answer
Direct answer
Server-render one canonical HTML shell per URL that's fully shareable across every visitor (no per-user branching in the cached document), cache that shell aggressively at the edge, and layer personalization on top client-side after the page loads, fetched separately with its own cache rules. That keeps the edge cache hit ratio high for search engines and anonymous visitors while still showing "Welcome back" to a signed-in user.
Structured elaboration
Headers: put a real Cache-Control: public, max-age=<seconds> on the server-rendered HTML document, and avoid Vary: Cookie on that document specifically, varying the cached document by cookie fragments the content delivery network's (CDN's) cache into one copy per distinct cookie value, which for a logged-in-heavy site can mean an effective cache hit ratio of nearly zero. Serve the personalized widget's data from a separate endpoint marked Cache-Control: no-store (or a very short private TTL) so the CDN never attempts to cache it at all.
CDN configuration: cache the HTML by URL at the edge, with purge-on-publish wired into your content pipeline so a content change is reflected immediately rather than waiting out the max-age. Keep the personalization endpoint routed straight to origin, bypassing the shared cache entirely, since by definition its response differs per visitor.
Assembly techniques, roughly in order of how much platform support they need:
- Client-side hydration fetch (simplest, works everywhere): the cached shell ships with a placeholder, then a small client-side call to something like
/api/greetingfills in the name once the page has loaded. - Signed client-side cookie read: if the personalization is something the browser already has (a name in a signed, non-sensitive cookie), render it entirely client-side with no extra network round trip, at the cost of a brief flash of the generic state before hydration runs.
- Edge-side includes or streaming server-side rendering (SSR) with partial hydration, where the platform supports it: the edge assembles the cached shared shell with an uncached personalized fragment at the edge itself, avoiding a second client-side round trip, at the cost of more platform-specific complexity.
flowchart LR
U[Browser request] --> E[Edge or CDN cache]
E -- cache hit, same for all users --> H[Return cached HTML shell]
E -- cache miss --> S[Origin SSR renders shared shell]
S --> E
H --> C[Client hydrates]
C --> P[Fetch personalized widget data, no-store, per user]
P --> W[Render personalized widget client-side]
Worked example
A marketing page is requested by a Google crawler and by a returning signed-in user, at different times, for the same URL. Both get the identical cached HTML shell from the edge (a cache hit either way, since the document never varies on cookie or auth state), including the full SEO-relevant markup and the placeholder greeting. The crawler renders it as-is and moves on. The signed-in user's browser then fires the /api/greeting call, marked no-store, which returns "Welcome back, Priya" and swaps it into the placeholder client-side, a request the edge cache never even sees.
Trade-offs and pitfalls
Client-side hydration means the personalized widget briefly shows a generic or empty state before its own fetch resolves, a small flash that's usually an acceptable trade for a high cache hit ratio; if that flash is unacceptable, you can vary the cached document on a coarse, low-cardinality signal (logged-in vs. anonymous, two cache variants) instead of full personalization, trading a little cache efficiency for zero flash. The most common real mistake is Vary: Cookie (or an equivalent authorization-header-based variance) creeping onto the main document because a framework enables session handling by default, silently collapsing the cache hit ratio to near-zero without an obvious error, always verify the actual cache-key dimensions the CDN is using in production, not just what the config says it should be.
Describe best practices for cache key design in a multi-tenant, multi-region platform. Include naming conventions, versioning, tenant isolation, use of prefixes, handling binary data, and strategies to avoid collisions and unbounded key growth.
Sample Answer
Framing
Cache key design controls three failure modes at once: keys colliding across tenants or regions (a security/correctness bug), keys growing without bound (a memory/cost bug), and keys becoming impossible to invalidate as a group (an operability bug). The fix is to treat the key as structured data, not a free-form string.
Naming convention
Use a fixed, hierarchical, delimited structure, most-specific segment last, and put the segment you will most often need to wildcard-scan on (resource type) directly after tenant, not buried behind region:
{env}:{tenant_id}:{resource_type}:{region}:{resource_id}:{version}
Example: prod:acme-corp:product:us-east-1:sku-48213:v3
Principles
- Tenant isolation: always prefix with the tenant ID, never trust a single shared key space. A bug that forgets the tenant prefix silently leaks data across tenants, which is the worst caching bug class in a multi-tenant system.
- Versioning: embed a schema/content version segment (
v3) so a breaking change to what a key represents cannot collide with an old cached shape. Bump the version instead of trying to migrate every existing key. - Prefixes for grouped invalidation: because
resource_typesits immediately aftertenant_id,prod:acme-corp:product:*is a genuine PREFIX of every product key for that tenant, in every region, so it lets you invalidate "everything for this tenant's catalog" either by scanning and deleting matching keys, or, better, by bumping a per-tenant-and-resource-type version segment instead of scanning (Redis has no native prefix-delete;SCANplusDELis O(n) and can be slow at scale). Verified against a live Redis instance: with the ORIGINAL ordering (regionbeforeresource_type), the same-looking patternprod:acme-corp:product:*matches NOTHING, because the third segment of a real key is a region code likeus-east-1, not the literal stringproduct:KEYS/SCAN MATCHdo plain positional glob matching, they don't know a segment means "region" versus "resource type". Orderingresource_typebeforeregion(as above) is what makes the stated invalidation pattern actually work; to scope invalidation to one region only, extend the same prefix:prod:acme-corp:product:us-east-1:*. - Binary/complex data: if part of the natural key is binary or very long (a file hash, a full URL with query params), hash it (SHA-256, truncated) into a fixed-length segment for readability and to avoid oversized keys.
- Region: still include the region explicitly whenever the same logical resource is cached differently per region (personalized/geo content), rather than relying on physical cache placement to imply it; it is ordered after
resource_typeprecisely so a tenant-and-resource-type prefix scan keeps working across every region. - Avoiding unbounded growth: never let an unbounded, ever-incrementing value alone be the whole key with no TTL and no owning prefix. Pair every key pattern with a TTL and, where possible, a bounded cardinality (cache per page, not per arbitrary filter combination, if the number of combinations is unbounded).
Trade-off
Longer, more structured keys cost a little extra memory per key, a few dozen bytes, and choosing wisely is a real design decision. That cost is trivial compared to a cross-tenant leak or a key space that can never be selectively invalidated.
Unlock Full Question Bank
Get access to all 24 Caching Strategies & In-Memory Optimization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.