Last Updated: May 1, 2025
Cache Patterns
| Pattern | Read Path | Write Path |
|---|---|---|
| Cache-Aside | Check cache → miss → DB → populate | Invalidate after DB write |
| Read-Through | Cache handles DB reads | N/A (writes direct to DB) |
| Write-Through | Cache always fresh | Write cache → cache writes DB |
| Write-Behind | Same as cache-aside | Write cache → async DB write |
Eviction Policies
| Policy | How It Works | Best For |
|---|---|---|
| LRU | Evict least recently used | General purpose — great default |
| LFU | Evict least frequently used | Hot items that stay hot |
| TTL | Evict after fixed time | Sessions, rate limits, OTPs |
| FIFO | Evict oldest by insertion | Simple, bounded memory |
Redis Caching Commands
SET key value EX 3600Set key with 1-hour TTL
GET keyRetrieve value by key
DEL keyDelete a key (manual invalidation)
EXPIRE key 300Set/update TTL to 5 minutes
MGET key1 key2Get multiple keys in one round trip
INCR keyAtomic increment — counters, rate limits
Cache Invalidation
| Item | Description |
|---|---|
TTL-Based | Simplest — data expires after fixed time |
Write Invalidation | Delete cache entry after DB write |
Event-Driven | Publish change events → cache subscribers invalidate |
Versioned Keys | Append 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.