Mercury SkillsMercury Skills
v1.0.0 cosmicstack-labs

Caching Strategies

CDN, Redis, in-memory cache, cache invalidation, and distributed caching patterns

View source0 downloads
cachingperformancerediscdndistributed-systems

Caching Strategies#

Cache effectively to improve performance and reduce load.

Cache Layers#

LayerLatencyStorageExamples
BrowserLocalSmalllocalStorage, HTTP cache
CDNRegionalLargeCloudFront, CloudFlare, Fastly
ApplicationIn-processSmallL1 cache (heap)
DistributedNetworkLargeRedis, Memcached
DatabaseSame hostVery largeBuffer pool, query cache

Caching Patterns#

Cache-Aside (Lazy Loading)#

1. Check cache → miss
2. Query database
3. Store in cache
4. Return

Best for: Read-heavy, general purpose.

Write-Through#

1. Write to cache
2. Cache writes to DB (sync)
3. Return

Best for: Consistency critical, write-heavy.

Write-Behind#

1. Write to cache
2. Return immediately
3. Cache writes to DB (async)

Best for: High throughput writes, eventual consistency OK.

Refresh-Ahead#

  • Cache proactively refreshes before expiry
  • Reduces latency spikes on cache miss
  • Requires predictive logic or scheduled refresh

Cache Invalidation#

Two hard things: naming, cache invalidation, off-by-one errors.

StrategyHowRisk
TTLExpire after X secondsStale data during TTL
Event-basedInvalidate on data changeMissed events
Version keysuser_42_v3Unused old keys accumulate
Write-throughUpdate cache on writeWrite amplification

Redis Patterns#

  • Use EXPIRE on every SET
  • Use SCAN not KEYS in production
  • Distributing: Redis Cluster for sharding
  • Backup: RDB (snapshot) + AOF (append-only log)
  • Monitor: hit rate, memory, evictions, latency

More in Backend

View all →