Interview Study Guide

Guide / System design Fundamentals

2. Caching

Caching from the browser to the database: where caches live, read/write strategies, keys and TTLs, invalidation and its races, stampede/penetration/avalanche/hot-key fixes, eviction, Redis, consistency and measurement.

Created · Updated · 19 min read

A cache trades freshness for speed and load reduction. Every cache answer in an interview must state five things: what is cached, the key, the TTL, how it is invalidated, and what happens on a miss or when the cache is down.

Order in this page: Fundamentals → Most asked questions → Senior-level questions → Quiz with answers. Related: REST API design (HTTP caching headers), Scaling patterns, Replication and sharding.

Fundamentals#

2.1 Why caching works and what it buys#

Caching works because access is skewed (a small set of items gets most reads: the 80/20 rule) and because memory is 100–1000× faster than disk or network.

Average latency = hit_ratio × cache_time + (1 − hit_ratio) × origin_time.

Hit ratioCache 1 ms, DB 50 msDB load vs no cache
50%25.5 ms50%
90%5.9 ms10%
99%1.5 ms1%

Going from 90% to 99% cuts DB traffic 10× but needs a much larger cache and better invalidation. A cache is worth it when: reads ≫ writes, the same data is read repeatedly, computing or fetching it is expensive, and slight staleness is acceptable. It is not worth it for write-heavy or low-reuse data, or when every read must be perfectly fresh.

2.2 Where caches live (from the user to the disk)#

LayerWhat it cachesControlled byNotes
Browser / appStatic files, API GETsCache-Control, ETagFree, per user, hard to invalidate (use versioned URLs)
CDN / edgeStatic assets, public API responses, images, video segmentsCache-Control, CDN rulesOffloads origin and cuts latency; shared by many users
API gateway / reverse proxyWhole responsesRules and TTLVarnish, NGINX proxy_cache
Application in-processHot objects, config, parsed data (LRU map, Caffeine, Guava)Your codeFastest (nanoseconds), not shared between instances → inconsistent, duplicated memory
Distributed cacheObjects, sessions, query results, countersYour codeRedis, Memcached; shared, network hop of ~0.5 ms
DatabaseBuffer pool / page cache, query cache, materialised viewsDBWarm cache after restarts matters; OS page cache is a cache too
CPUL1/L2/L3HardwareWhy data layout and locality matter in hot paths

Multi-level caching: a small local L1 (seconds of TTL) in front of Redis L2 cuts Redis load for the hottest keys but multiplies staleness (each instance can be stale independently).

HTTP caching in one paragraph: Cache-Control: public, max-age=3600 (anyone may store for an hour); private (browser only: personalised); no-store (never store: tokens, balances); no-cache (store but revalidate before use); s-maxage (CDN-specific TTL); stale-while-revalidate=60 (serve stale for a minute while refreshing); ETag + If-None-Match → 304 Not Modified; Vary: Accept-Encoding tells caches which request headers change the response. Cache versioned static assets for a year, API responses for seconds to minutes, never personalised data in shared caches.

2.3 Read and write strategies#

StrategyHow it worksProsCons / when not
Cache-aside (lazy loading)App reads cache; on a miss reads the DB and fills the cacheSimple; only caches what is used; survives a cache outage (falls back to DB)First request is slow; stale until TTL or invalidation; app owns the logic
Read-throughThe cache library loads from the DB on a missCleaner app codeNeeds provider support
Write-throughWrite to cache and DB synchronouslyCache always freshHigher write latency; caches data that is never read
Write-behind (write-back)Write to cache, flush to the DB asynchronouslyVery fast writes, batching, coalescingData loss if the cache dies before the flush; never for money
Write-aroundWrite to the DB only; cache is filled on readDoes not pollute the cache with write-once dataThe next read is a miss
Refresh-aheadRefresh hot keys before they expireNo miss latency for hot keysWasted refreshes when prediction is wrong

Default answer: cache-aside + TTL + delete-on-write.

def get_product(pid):
    key = f"product:{pid}:v3"                  # v3 = schema/version namespace
    cached = redis.get(key)
    if cached is not None:
        return None if cached == NULL_MARKER else decode(cached)

    row = db.query("SELECT * FROM products WHERE id = %s", pid)   # miss: go to the source
    if row is None:
        redis.set(key, NULL_MARKER, ex=60)                         # negative caching (short TTL)
        return None
    redis.set(key, encode(row), ex=ttl_with_jitter(600))           # 10 min ± 10%
    return row

def update_product(pid, fields):
    db.execute("UPDATE products SET ... WHERE id = %s", pid)       # 1) DB first (source of truth)
    redis.delete(f"product:{pid}:v3")                              # 2) then delete, don't overwrite

2.4 Keys, TTLs and what to store#

Key design

  • Pattern entity:id:version or service:entity:id:variant, e.g. catalog:product:123:en-IN:v3. Include everything the value depends on (locale, currency, tenant) or users see each other’s data.
  • Add a schema version to keys so a deploy that changes the serialised shape does not read old, incompatible values.
  • Keep keys short and consistent, avoid unbounded cardinality (per-request keys are useless).
  • Use hash tags {user:1}:cart in Redis Cluster so related keys land in one slot.

TTL choice

DataTypical TTL
Static assets with hashed names1 year
Reference data (countries, categories)Hours to days
Product pages, catalogue1–15 min
User profile5–60 min with delete-on-write
Search results, feeds10–60 s
Rate-limit countersWindow length
SessionsSession timeout (sliding)
Negative results (not found)30–60 s

TTL jitter: TTL × (0.9–1.1) random, so keys populated together do not all expire together.

What to store: the smallest thing that answers the query: IDs for lists (then multi-get objects), serialised objects (JSON, MessagePack, protobuf) for entities, precomputed aggregates. Compress values over ~1 KB if CPU allows. Avoid giant values (see big keys below).

2.5 Invalidation (how the cache stays correct)#

“There are only two hard things in computer science: cache invalidation and naming things.” Four tools, usually combined:

  1. TTL expiry: the simplest, bounds staleness. Always set a TTL as a safety net, even if you also invalidate.
  2. Delete on write: after the DB commit, delete the key (do not write the new value). Deleting is idempotent and avoids two racing writers leaving the older value in the cache.
  3. Event-driven invalidation: DB change → CDC (Debezium) or outbox event → consumer deletes keys. Covers writes from any service or migration and decouples writers from caches.
  4. Versioned keys: product:123:v7; bump the version on change, old keys age out. Ideal for CDN assets and computed aggregates; no race.

Others: tag-based purge (CDN surrogate keys: purge everything tagged product-123), write-through updates for tiny hot sets, explicit “cache bust” endpoints guarded by auth.

The classic race (stale value stuck in cache):

 t1  Reader A: cache MISS → reads OLD value from DB
 t2  Writer B: updates DB to NEW
 t3  Writer B: deletes cache key
 t4  Reader A: writes OLD value into the cache   ← stale until TTL

Fixes: a short TTL as a backstop; delayed double delete (delete, then delete again ~500 ms later to clear a late refill); store a version/timestamp with the value and only SET if newer (Lua script / compare-and-set); use leases (Memcached “lease tokens”, Facebook’s approach) so a reader’s stale fill is rejected after an invalidation.

Order matters: commit to the DB first, then delete the cache. Deleting first lets a concurrent reader refill the cache with the old value before the DB write commits.

If the cache delete fails after the DB commit (network blip), the entry stays stale until TTL: retry via an outbox/queue, or rely on the TTL, and monitor failed invalidations.

2.6 Failure patterns and their fixes#

ProblemWhat happensFix
Cache stampede (thundering herd / dog-piling)A hot key expires; thousands of requests miss at once and hit the DBSingle-flight / request coalescing (one request per key rebuilds; the rest wait), a lock (SET key:lock NX PX 5000), serve stale while one refreshes (stale-while-revalidate), early probabilistic refresh, never expire the hottest keys (refresh them with a background job)
Cache penetrationRequests for keys that don’t exist (random IDs, attacks) always miss and hit the DBCache negative results with a short TTL, a Bloom filter of valid IDs, validate input (format, range) before touching cache/DB, rate-limit
Cache avalancheMany keys expire at once, or the cache cluster dies; the DB receives the full loadTTL jitter, multi-level cache, replicas/clustering for the cache, circuit breaker + rate limit towards the DB, gradual warm-up, load-shed
Hot keyOne key (celebrity profile, flash-sale item) overloads one Redis shardLocal in-process cache for it, replicate it as key#1..#N and read a random copy, read replicas, split into parts
Big keyA 10 MB value blocks Redis (single-threaded) and saturates the networkSplit into a hash or chunks, compress, store blobs in S3 and cache a pointer, avoid unbounded collections
Cache pollutionOne-time scans evict useful dataAdmission policy (TinyLFU), LFU, separate caches for scans
Stale reads after failoverAsync replication lost recent writesTreat Redis as a cache, not truth; keep the source of truth in the DB
# single-flight stampede protection (per key) using a short Redis lock
def get_with_lock(key, loader, ttl):
    v = redis.get(key)
    if v is not None:
        return decode(v)
    if redis.set(f"lock:{key}", "1", nx=True, px=5000):        # I won: rebuild
        try:
            v = loader()
            redis.set(key, encode(v), ex=ttl_with_jitter(ttl))
            return v
        finally:
            redis.delete(f"lock:{key}")
    for _ in range(50):                                         # I lost: wait briefly
        time.sleep(0.02)
        v = redis.get(key)
        if v is not None:
            return decode(v)
    return loader()                                             # fallback, bounded

(Within a single process you coalesce with a per-key in-memory future, which is cheaper than a distributed lock.)

2.7 Eviction policies#

When memory is full the cache must evict. Policies: LRU (least recently used; default for most workloads), LFU (least frequently used; better for stable popularity, resists scan pollution), FIFO, TTL-based, random, and TinyLFU/W-TinyLFU (Caffeine’s near-optimal admission + eviction).

Redis maxmemory-policy: allkeys-lru, allkeys-lfu (best for a pure cache), volatile-lru/lfu/ttl (only keys that have a TTL), allkeys-random, noeviction (writes fail when full: right for queues and primary data, wrong for a cache). Redis uses approximate LRU (samples keys) for speed.

Sizing: cache about the hot 20% of the data (or the working set), measure the hit ratio against memory, and watch evictions per second: if hot keys are being evicted, the cache is too small. Leave 20–30% memory headroom for fragmentation, replication buffers and fork copy-on-write during snapshots.

2.8 Redis and Memcached: what interviewers ask#

RedisMemcached
Data typesStrings, hashes, lists, sets, sorted sets, streams, bitmaps, HyperLogLog, geoStrings only
ThreadingSingle-threaded command execution (I/O threads in newer versions) → each command atomicMulti-threaded
PersistenceRDB snapshots and/or AOFNone
Replication / HAReplicas, Sentinel, ClusterClient-side sharding only
ExtrasLua scripts, transactions, pub/sub, TTL per key, atomic countersSimple, very fast, memory-efficient for plain key-value
UseCache + counters + leaderboards + rate limits + locks + queuesPure, simple cache at huge scale

Redis specifics:

  • Every command is atomic; slow commands (KEYS *, huge SMEMBERS, LRANGE 0 -1) block everyone: use SCAN.
  • Persistence: RDB (fast restart, loses recent writes) vs AOF (appendfsync everysec loses up to ~1 s). Redis is not the source of truth for money.
  • Scaling: Redis Cluster shards by 16,384 hash slots; multi-key commands need the same slot ({user:1}:cart). Sentinel provides failover for primary-replica sets.
  • Replication is asynchronous → a failover can lose acknowledged writes; distributed locks need care (Distributed systems).
  • Pipelining batches many commands in one round trip; Lua gives atomic multi-step operations (rate limiters, compare-and-set).
  • Rough capacity: ~100K simple ops/s per node, ~1 ms p99 on a LAN, memory is the cost driver.

2.9 Consistency: what you can promise#

A cache and a database cannot be perfectly consistent without paying the cost of not having a cache. You choose a bounded staleness:

NeedApproach
“A few seconds stale is fine”TTL only
“Users must see their own writes”Delete-on-write + read your own writes from the DB (or write-through for that user) for a few seconds; sticky per-user reads
“Update everywhere quickly”Event-driven invalidation (CDC/outbox) + TTL backstop
“Never stale”Do not cache that read (read from the primary), or use versioned immutable data

Multi-region: each region has its own cache; invalidation messages must cross regions (pub/sub or CDC replication), and the TTL bounds the damage when they are delayed.

2.10 What not to cache#

Data that must be strongly consistent at read time (account balance before a debit, inventory at the last checkout step, anything where a stale read loses money or breaks an invariant), per-user data with a low hit rate, huge rarely-read objects, and secrets without encryption. Read those from the primary DB (or cache only for display, never for decisions).

2.11 Measuring a cache#

  • Hit ratio (hits / (hits + misses)), per cache and per key prefix; target depends on workload (90–99% for hot catalogues).
  • Latency p50/p99 for hits and for misses (miss latency is your DB latency plus fill).
  • Evictions/s and memory usage: evictions with a low hit ratio mean the cache is too small or keys are too varied.
  • Origin load (QPS and CPU on the DB) before and after.
  • Key cardinality, big keys, hot keys (redis-cli --bigkeys, --hotkeys, MEMORY USAGE).
  • Stale-read incidents, failed invalidations, lock contention.
  • Load-test the cold-cache scenario: restart the cache and see if the DB survives.

Most asked questions#

1. What is caching and when should you use it? Keep copies of expensive-to-compute or slow-to-fetch data in a faster store to reduce latency and origin load. Use it for read-heavy, repeated, stale-tolerant data. State the five parameters: what, key, TTL, invalidation, miss/failure behaviour.

2. Which caching strategy would you choose and why? Cache-aside with TTL and delete-on-write: simple, resilient to cache failure, only caches data that is read. Write-through when freshness is critical and the set is small; write-behind only for loss-tolerant write-heavy data (counters, analytics), never for money.

3. How do you keep cache and DB consistent? You can only bound staleness: update the DB first, then delete the key; TTL as a safety net; event-driven invalidation via CDC; version keys; read critical data from the DB. Mention the race (reader fills an old value after a delete) and the fixes (delayed double delete, versioned set).

4. What is a cache stampede and how do you prevent it? A hot key expires and many requests rebuild it simultaneously, overloading the DB. Prevent it with single-flight/locking, serve-stale-while-revalidate, TTL jitter, and background refresh of hot keys.

5. Cache penetration vs avalanche vs stampede? Penetration: requests for non-existent keys bypass the cache. Avalanche: many keys expire together or the cache dies. Stampede: a single hot key’s expiry causes a thundering herd. Fixes: negative caching + Bloom filter; jitter + HA + circuit breaker; single-flight + stale serving.

6. LRU vs LFU? LRU evicts the least recently used: good general default, but a scan can flush hot data. LFU evicts the least frequently used: better for stable popularity and resists scans, but adapts slowly to change (needs decay). Modern caches use W-TinyLFU.

7. What if Redis goes down? The system should degrade, not fail: fall back to the DB with a circuit breaker and rate limits (the DB must survive the cold-cache load or you need a replica/warm standby), serve stale from the local L1, shed non-critical traffic, and use Redis HA (replicas, Sentinel/Cluster) so a node loss is not a cache loss.

8. How would you cache a user’s shopping cart or session? Session: Redis with sliding TTL, signed session ID. Cart: usually the primary store is a DB or Redis with persistence (it is user data, not a pure cache), with TTL for abandonment; do not treat a volatile cache as the only copy of money-relevant data.

9. Where do you cache in a typical web architecture? Browser and CDN for static and public content, application-level local cache for tiny hot config, Redis for shared objects and sessions, DB buffer pool. The closer to the user, the cheaper and harder to invalidate.

10. How would you design a distributed cache? Consistent hashing with virtual nodes for sharding, replication for availability, LRU/LFU eviction, TTLs, client library or proxy routing, hot key handling, a metrics and warm-up story.

Senior-level questions#

1. “Your hit ratio is 99% but the DB is still overloaded. How?” The 1% misses are expensive (heavy queries) or correlated (stampedes on expiry, a deploy that flushed the cache, or a cold node after failover); the hit ratio hides a hot-miss pattern. Check miss rate in absolute terms (1% of 100K QPS is 1K QPS), per-key misses, query cost of the miss path, and add coalescing, stale serving and pre-warming.

2. “A product’s price changed but some users still see the old price for 10 minutes after we ‘invalidate’ the cache.” Possible causes: the old value was refilled after the delete (race: fix with delayed delete or versioned set), another cache layer exists (CDN, local L1, browser) that was not invalidated, replica lag (the refill read from a lagging replica: read from the primary on invalidation-triggered refills), the invalidation event was lost or delayed, or a different key variant (locale, currency) was not invalidated. And price at checkout must always come from the source of truth.

3. “Design caching for a 100M-user social profile service where celebrities get 1M reads/s.” Layered: CDN for public profile content, local in-process L1 with short TTL for the hottest keys, Redis cluster with replicas, replicated hot keys (profile:{id}#0..#15) read at random, request coalescing, stale-while-revalidate, pushing invalidation events to local caches via pub/sub, big values split (counts in separate keys updated asynchronously), and monitoring of hot keys with automatic promotion into the replicated tier.

4. “How do you cache personalised data safely behind a CDN?” Do not cache personalised responses in shared caches (Cache-Control: private), or key them by the dimension that defines them (Vary, or an explicit segment like country or plan, never user ID at the CDN). Serve a cacheable shell and fetch personal fragments separately, or use edge compute with signed cookies. Always test with two users to catch cross-user leakage; leaks are a security incident.

5. “Write-behind caching: when is it acceptable and how do you reduce risk?” For high-rate, loss-tolerant writes (view counters, telemetry, “last seen”). Reduce risk with durable write-behind (the cache writes to a queue/log first), replication before ack, flushing on shutdown, idempotent apply to the DB, and monitoring of unflushed backlog. Never for payments, inventory or orders.

6. “How do you warm a cache after a deploy or failover without hammering the DB?” Pre-warm hot keys from a list (top N by access logs), replay recent traffic, throttle the warm-up, shift traffic gradually (slow start), keep replicas that already hold data, use stale-serving, and protect the DB with a connection limit and rate limit during the warm phase.

7. “Redis memory is full and latency spikes at 3 a.m. What do you check?” Eviction churn and policy (noeviction makes writes fail), big keys, a slow command (KEYS, huge SMEMBERS), fork for RDB/AOF rewrite stalling (copy-on-write memory spike, transparent huge pages), swap, network saturation from large values, a hot shard, client connection storms, expired-key bursts (many keys with the same TTL), and replication buffers. Use SLOWLOG, INFO, MEMORY DOCTOR, --bigkeys.

8. “Is Redis a good system of record?” Rarely. With AOF always it can be durable but is slower; replication is asynchronous (failover loses writes); the dataset must fit in memory. Use it for derived, reconstructible, or loss-tolerant data. For primary data, use a durable database and cache on top.

9. “How do you invalidate a cache across services and regions reliably?” Make the database change the source of events (CDC or transactional outbox → Kafka), have each cache owner subscribe and delete or update its keys, make deletes idempotent, add TTLs as a backstop, monitor invalidation lag, and design for out-of-order events with versions.

10. “Cache invalidation vs recompute: when is it better to not cache?” When the data changes faster than it is read (low reuse), when the staleness risk (money, security, inventory) outweighs the speed gain, when the origin is already fast, or when cache complexity exceeds the savings. A well-indexed, replica-served query at 5 ms may not justify a cache at all.

Quiz#

1. Hit ratio 95%, cache latency 1 ms, DB latency 40 ms: average latency?

0.95 × 1 + 0.05 × 40 = 0.95 + 2.0 = 2.95 ms.

2. Why delete the cache entry after a write instead of updating it?

Deleting is idempotent and cannot leave an older value if two writers race; the next read loads the newest value from the DB. Updating risks writing a stale value out of order.

3. Should you update the DB first or the cache first, and why?

DB first, then delete the cache. If you delete first, a concurrent reader can refill the cache with the old value before the DB commit.

4. Describe the race that leaves a stale value in the cache after a delete, and one fix.

Reader A misses and reads the old value; writer B updates the DB and deletes the key; A then writes the old value into the cache. Fix: delayed double delete, version check on set, leases, or a short TTL.

5. What is cache penetration and how do you stop it?

Repeated requests for keys that do not exist always miss and hit the DB (often malicious). Use negative caching with a short TTL, a Bloom filter of valid keys, input validation and rate limits.

6. Name three ways to prevent a stampede on a hot key.

Single-flight/lock so one request rebuilds, serve stale while refreshing (stale-while-revalidate), and proactive background refresh or never-expire hot keys; plus TTL jitter to avoid synchronised expiry.

7. Why add jitter to TTLs?

To stop many keys that were created together from expiring simultaneously (avalanche), which would send a burst of misses to the DB.

8. One Redis key receives 500K reads/s and its shard is saturated. What do you do?

Add an in-process local cache with a short TTL, replicate the key under N suffixed names and read randomly, or use read replicas for that shard; keep the value small.

9. Which Redis eviction policy for a pure cache and which for a queue?

allkeys-lru or allkeys-lfu for a cache; noeviction for queues or primary data so nothing is silently dropped.

10. What should never be cached (or only cached for display)?

Data needed for strongly consistent decisions: balances before debit, inventory at final checkout, authorisation decisions without expiry; also personalised data in shared caches.

11. Cache-Control: public, max-age=3600, stale-while-revalidate=60. What does it mean?

Any cache may store the response and serve it for an hour; after that, it may serve the stale copy for up to 60 more seconds while fetching a fresh one in the background.

12. How do versioned keys or filenames help invalidate a CDN?

The URL changes whenever the content changes (app.3f2a.js), so no purge is needed: new clients request a new URL, old URLs expire naturally, and caches can keep assets for a year.

13. Why is write-behind unsuitable for payments?

Acknowledged writes can be lost if the cache dies before flushing, and ordering and atomicity are weaker; money requires durability before acknowledgement.

14. What metrics tell you a cache is too small?

A falling hit ratio together with a high eviction rate and hot keys being evicted; memory at the limit; DB load rising without traffic growth.

Finished this page?Mark it done to track your progress across the guide.
Pritam Ghosh · System design & AI engineering study notes