{}DSA Atlas

Caching

Where caches live (client, CDN, gateway, application, distributed, database), read and write strategies (cache-aside, read-through, write-through, write-behind, write-around, refresh-ahead), eviction policies, TTLs and invalidation, consistency races, stampedes and hot keys, Redis vs Memcached, sizing and metrics.

Intermediate → Advanced6 interview questions

Why cache?

Caching stores the results of expensive work (DB queries, computations, remote calls, rendered pages) in faster storage so repeated requests are served cheaply. Benefits: lower latency, less load on databases and services, higher throughput, sometimes resilience (serve stale when the origin is down). Costs: staleness, complexity, memory, another component to fail.

Where caches live

Clientbrowser/app CDNedge Gatewayresponse cache Appin-process Redisdistributed Databasebuffer pool the closer to the user, the faster and cheaper — and the harder to invalidate
Every layer can cache; each has different scope and invalidation tools.
LayerCachesInvalidation
Browser / mobile appHTTP responses, assets, app stateCache-Control, ETags, versioned URLs
CDNstatic assets, media, public API responses, HTMLTTL, purge by URL/tag, versioned URLs
API gateway / reverse proxyfull responsesTTL, purge
Application (in-process)hot objects, config, computed valuesTTL, pub/sub invalidation; per-instance (inconsistent across instances)
Distributed cache (Redis/Memcached)query results, sessions, objects, countersTTL, explicit delete, CDC
Databasepages (buffer pool), query plans, materialized viewsautomatic / refresh

Read strategies

Cache-aside (lazy loading)

Application Cache Database 1. get 2. miss → query 3. set (TTL) writes:1. update DB2. DELETE cache key
The application owns the logic; the cache is a pure optimisation.
Python
import json, random

def get_user(user_id: str):
    key = f"user:{user_id}:v2"                    # version the key format
    cached = redis.get(key)
    if cached is not None:
        return json.loads(cached)
    user = db.fetch_one("SELECT * FROM users WHERE id = %s", (user_id,))
    if user:
        ttl = 300 + random.randint(0, 60)         # jitter avoids synchronized expiry
        redis.set(key, json.dumps(user), ex=ttl)
    else:
        redis.set(key, "null", ex=30)             # negative caching (bounded)
    return user

def update_user(user_id: str, fields: dict):
    db.update_user(user_id, fields)               # 1. source of truth first
    redis.delete(f"user:{user_id}:v2")            # 2. invalidate (don't set!)

Read-through

The cache library/service itself loads from the DB on a miss (e.g. Caffeine LoadingCache, DAX for DynamoDB, NCache). Simpler application code, same semantics as cache-aside.

Write strategies

StrategyWrite pathRead freshnessRiskBest for
Cache-aside + invalidateDB, then delete keystale until next miss/TTL (small window)race on concurrent read/writegeneral purpose
Write-throughcache and DB synchronouslyfreshslower writes, cache pollutionread-after-write heavy data
Write-back (behind)cache now, DB later (batched)fresh in cachedata loss on cache failurecounters, metrics, high write bursts
Write-aroundDB onlypopulated on readfirst read slowwrite-once, read-rarely data (logs, uploads)
Refresh-aheadbackground refresh before expiryfresh for hot keyswasted refreshespredictable hot keys

Eviction and expiration

PolicyEvictsGood for
LRUleast recently usedgeneral recency workloads
LFU (with aging)least frequently usedstable popularity (catalogs, CDNs)
TTLexpired entriesdata with freshness limits
FIFO / randomoldest / randomsimple, cheap
W-TinyLFU, S3-FIFO, SIEVEmodern, scan-resistanthigh hit ratios on real traces

Implementing LRU (a classic interview task): hash map + doubly linked list → O(1) get/put. See the design problems topic.

Consistency pitfalls

The stale-set race in cache-aside

Reader A Writer B DB / cache 1. cache miss 2. read DB → v1 3. write DB → v2 4. delete cache 5. (slow) set cache = v1 ✗ cache holds v1until TTL expires mitigate: short TTLs, versioned values (set only if newer), leases, CDC-based invalidation
A slow reader can resurrect old data after the writer's invalidation.

Other gotchas

  • Update vs delete on write: concurrent "set" operations can leave the older value last; prefer delete.
  • Dual-write ordering: invalidate after the DB commit, not before.
  • Multi-key consistency: a page assembled from several cached keys may mix versions.
  • Negative caching: cache "not found" briefly to protect against repeated misses (and enumeration attacks), but keep the TTL short.
  • Serialization changes: version your cache keys (user:{id}:v2) when the format changes.

Stampedes and hot keys

Python
import threading

_inflight: dict[str, threading.Event] = {}
_lock = threading.Lock()

def get_with_singleflight(key, loader, ttl=300):
    val = redis.get(key)
    if val is not None:
        return val
    with _lock:
        ev = _inflight.get(key)
        leader = ev is None
        if leader:
            ev = _inflight[key] = threading.Event()
    if not leader:
        ev.wait(timeout=2)                    # followers wait for the leader's result
        return redis.get(key) or loader()     # fallback if the leader failed
    try:
        val = loader()
        redis.set(key, val, ex=ttl)
        return val
    finally:
        with _lock:
            _inflight.pop(key, None)
        ev.set()
ProblemMitigation
Stampede on expirysingle-flight, probabilistic early refresh, stale-while-revalidate, TTL jitter
Cold cache after restart/deploywarm-up jobs, gradual traffic shift, persistent cache (Redis AOF), replicas
Hot keylocal L1 cache, key replication (key#n), read replicas, coalescing
Hot write countersharded counters, in-memory aggregation with periodic flush
Big valuescompress, split, store blobs elsewhere
Cache penetration (requests for keys that never exist)negative caching, Bloom filter of valid keys

Distributed caching

  • Partitioning: consistent hashing (client-side for Memcached) or hash slots (Redis Cluster: 16,384 slots).
  • Replication for availability (Redis primary/replica with Sentinel or Cluster failover); replicas serve reads with possible lag.
  • Multi-level: L1 in-process (Caffeine, microseconds, per instance) + L2 distributed (Redis, sub-ms) + DB.
  • Failure mode: the system must survive cache loss — can the database handle the full load if the cache disappears? If not, the cache is a critical dependency; protect the DB with rate limiting and circuit breakers.

Redis vs Memcached

Redis / ValkeyMemcached
Data typesstrings, hashes, lists, sets, sorted sets, streams, geo, HLL, bitmapsstrings
PersistenceRDB snapshots, AOFnone
Replication / HAyes (Sentinel, Cluster)no (client-side only)
Scripting / atomic opsLua, transactions, many atomic commandsCAS, incr
Threadingsingle-threaded execution (+ I/O threads)multi-threaded
Typical extra usesrate limiting, leaderboards, locks, queues, pub/subpure object cache

Sizing and metrics

  • Hit ratio (target depends; 90%+ for read-heavy caches) and miss latency.
  • Working set: often 20% of objects serve 80% of reads → cache that fraction.
  • Example: 10M daily active users × 2 KB profile × 20% hot ≈ 4 GB → a small Redis cluster with replicas.
  • Watch evictions, memory fragmentation, network bandwidth (big values!), CPU (single-threaded Redis), and connection counts.

Interview questions

0 / 6 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.