Cache eviction strategies (TTL, LRU)

When the cache is full or an entry is stale, something must be removed — that’s eviction. Common strategies: TTL (time-to-live): remove after a fixed time; LRU (least recently used): remove the item that hasn’t been used for the longest time.

TTL: time-based expiry

flowchart LR Set[Set key, TTL=60s] --> Store[Store + expiry time] Store --> Check{Read request} Check -->|Now < expiry| Hit[Cache hit] Check -->|Now >= expiry| Miss[Evict, cache miss]

LRU: evict least recently used

flowchart TB subgraph LRU["LRU list (order = last access)"] A[Most recent] --> B --> C --> D[Least recent] end Full[Cache full] --> Evict[Evict D] Evict --> New[Add new entry at head]
StrategyWhen evictUse case
TTLAfter fixed durationStale-safe data (e.g. 5 min for profile)
LRUWhen full; drop least recently usedBounded memory; keep “hot” data
LFUWhen full; drop least frequently usedKeep most popular items
FIFOWhen full; drop oldest insertedSimple, no access tracking

Combine TTL (so data doesn’t stay forever wrong) with LRU (so under memory pressure you drop the coldest entries). Many caches (e.g. Redis) support both.