πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Caching Strategies

Data SystemsPerformance Optimization🟒 Free Lesson

Advertisement

System Design β€” Data Systems

Caching Strategies

Caching is the single most impactful performance optimization in system design. By storing frequently accessed data in fast storage (memory), you can reduce latency from milliseconds to microseconds and dramatically reduce database load.

  • Cache-Aside β€” Application manages cache explicitly
  • Write-Through β€” Writes go to cache and database simultaneously
  • Redis vs Memcached β€” When to use each caching technology

There are only two hard things in computer science: cache invalidation and naming things. β€” Phil Karlton

What Is Caching?

Where Caches Live

Client LayerBrowser Cache (HTTP headers)Application LayerIn-Process Cache (LRU, TTL-based)Distributed Cache LayerRedis / Memcached / Database Query Cache

Cache Topologies

PropertyLocal CacheDistributed Cache
LatencyNanosecondsMicroseconds-milliseconds
ScopeSingle processAll instances
InvalidationSimpleComplex (broadcast needed)
MemoryLimited by processScales independently
ConsistencyEventualConfigurable

Cache Eviction Policies

When the cache is full, eviction policies determine which entries to remove:

PolicyDescriptionTrade-off
LRULeast Recently UsedGood general-purpose, may evict rarely-used but important items
LFULeast Frequently UsedBetter for skewed distributions, slower to update
FIFOFirst In First OutSimplest, no frequency/recency awareness
TTLTime To LiveExpires after fixed duration, may evict useful data
RandomRandom evictionSurprisingly effective, no tracking overhead

Cache-Aside (Lazy Loading)

The most common caching pattern:

AppCacheDatabase1. Check cache2. MISS β†’ fetch from DB3. Return data, store in cacheCache-Aside: Application explicitly manages cache reads and writes

Flow:

  1. Application checks cache for data
  2. Cache hit: Return data directly from cache
  3. Cache miss: Fetch from database, store in cache, return data
  4. On write: Update database, invalidate cache (don't update cache)

Write-Through

Writes go to both cache and database simultaneously:

AppCacheDatabaseWriteSyncWrite-Through: Write hits cache and database simultaneously

Pros: Cache is always consistent, simple to implement Cons: Write latency is cache + DB, cache may be filled with data never read

Write-Back (Write-Behind)

Writes go to cache first, then asynchronously to database:

AppCacheDatabaseWriteAsyncWrite-Back: Writes to cache, asynchronously flushes to database

Pros: Very fast writes, batched database writes Cons: Data loss risk if cache fails before flush, complex implementation

Redis vs Memcached

FeatureRedisMemcached
Data structuresStrings, lists, sets, hashes, sorted sets, streamsStrings only
PersistenceRDB + AOFNone
ReplicationBuilt-in primary-replicaNone
Cluster modeRedis ClusterClient-side sharding
Memory efficiencyHigher overhead per keyVery memory efficient
Pub/SubBuilt-inNone
Lua scriptingSupportedNot supported
Best forComplex data, persistence, pub/subSimple key-value caching

Cache Patterns in Practice

Cache Stampede Prevention

When a popular cache entry expires, many requests simultaneously try to rebuild it:

Cache Invalidation Strategies

StrategyDescriptionConsistency
TTL-basedExpires after fixed durationEventual
Event-drivenInvalidate on write eventsNear real-time
Version-basedCache key includes versionStrong
Tag-basedGroup related keys for bulk invalidationConfigurable

Practice Exercises

  1. Design: Design a caching strategy for a news website with 10M daily visitors. What would you cache? What TTL would you use? How do you handle breaking news?

  2. Analysis: Compare cache-aside, write-through, and write-back for a banking application. Which pattern is most appropriate and why?

  3. Debugging: A system has a 99% cache hit ratio but still shows high latency at p99. What could cause this? How would you diagnose it?

  4. Architecture: Design a distributed caching layer for a global e-commerce platform. Consider: data locality, consistency, failure handling, and warming the cache.


What to Learn Next

-> Databases SQL vs NoSQL, indexing, replication, and sharding.

-> Load Balancing Algorithms, health checks, and L4 vs L7.

-> Message Queues Kafka, RabbitMQ, event-driven architecture.

-> CAP Theorem Consistency models, availability, and partition tolerance.

-> Microservices Service decomposition, discovery, and API gateways.

-> Scalability Fundamentals Vertical vs horizontal scaling and capacity planning.

Need Expert System Design Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement