ayushsalampuriya.xyzRevise

HLD · Performance

Caching Strategies

Store frequently accessed data closer to the consumer to cut latency and database load.

1. Basics: cache hit vs miss

Cache hit: Data found in cache → fast response (e.g., 1ms from Redis).

Cache miss: Data not in cache → fetch from source (DB, 50ms), store in cache, return.

Example: Product page for iPhone case — 10k views/min, same JSON. First request hits DB; next 9,999 hit Redis.

2. Where to cache (layers)

3. Cache-aside (lazy loading) — most common

read(key): val = cache.get(key) if val: return val val = db.get(key) cache.set(key, val, TTL=5min) return val

App owns cache logic. On write: update DB, then invalidate or update cache.

Pros: Only hot data cached; cache failure doesn't break reads (falls back to DB).

Cons: First request always slow; stampede risk on expiry (see below).

4. Write-through vs write-back

PatternWrite pathUse when
Write-throughWrite cache + DB togetherStrong consistency between cache and DB
Write-backWrite cache first; DB updated asyncWrite-heavy, can tolerate brief loss on crash
Write-aroundWrite DB only; invalidate cacheInfrequent writes, avoid polluting cache

5. Eviction policies

6. Cache problems (must know)

Cache stampede / thundering herd

Popular key expires; 1000 requests simultaneously miss and hammer DB.

Fixes: Probabilistic early expiry, request coalescing (single flight), mutex per key, stale-while-revalidate.

Stale data

User sees old price after update. Fix: Invalidate on write; short TTL for volatile data; version keys.

Hot key

One key (celebrity profile) overloads single Redis shard. Fix: Replicate hot key across shards, local in-process copy, read replicas.

7. Redis vs Memcached (interview)

RedisMemcached
Data structuresStrings, lists, sets, sorted sets, hashesStrings only
PersistenceOptional (RDB/AOF)None (pure cache)
Best forSessions, leaderboards, pub/sub, complex cachingSimple key-value blob cache

8. Example: caching user profile

Key: user:12345:profile, TTL 10 min. On profile update API: DEL user:12345:profile. On login burst: warm cache from DB once.

Quick revision

  • Cache-aside: Read cache → miss → DB → populate. Invalidate on write.
  • Layers: Browser → CDN → app → Redis → DB.
  • Eviction: TTL + LRU when memory bound.
  • Pitfalls: Stampede, stale data, hot keys.
  • Redis: Rich types + persistence; Memcached: simple & fast.
  • Don't cache: Highly personalized, strongly consistent financial balances without careful invalidation.