Caching Strategies Cheat Sheet

Cache patterns and eviction policies — cache-aside, read-through, write-through, write-behind, Redis, Memcached, and CDN caching.

Last Updated: May 1, 2025

Cache Patterns

PatternRead PathWrite Path
Cache-AsideCheck cache → miss → DB → populateInvalidate after DB write
Read-ThroughCache handles DB readsN/A (writes direct to DB)
Write-ThroughCache always freshWrite cache → cache writes DB
Write-BehindSame as cache-asideWrite cache → async DB write

Eviction Policies

PolicyHow It WorksBest For
LRUEvict least recently usedGeneral purpose — great default
LFUEvict least frequently usedHot items that stay hot
TTLEvict after fixed timeSessions, rate limits, OTPs
FIFOEvict oldest by insertionSimple, bounded memory

Redis Caching Commands

SET key value EX 3600
Set key with 1-hour TTL
GET key
Retrieve value by key
DEL key
Delete a key (manual invalidation)
EXPIRE key 300
Set/update TTL to 5 minutes
MGET key1 key2
Get multiple keys in one round trip
INCR key
Atomic increment — counters, rate limits

Cache Invalidation

ItemDescription
TTL-BasedSimplest — data expires after fixed time
Write InvalidationDelete cache entry after DB write
Event-DrivenPublish change events → cache subscribers invalidate
Versioned KeysAppend version: user:123:v2 — no invalidation needed
Pro Tip: There are only two hard things in Computer Science: cache invalidation and naming things. Always define a TTL and invalidation strategy before adding a cache.