Cache eviction policies: LRU, LFU, and TTL explained
LRU eviction, LFU eviction, TTL-based expiry, cache size limits, eviction vs expiration, Redis maxmemory-policy, choosing the right policy
Cache eviction policies: LRU, LFU, and TTL explained
Why Eviction Exists
Caches have finite memory. When full, the cache must remove something to make room. The policy you choose determines which items get evicted and directly impacts your hit ratio.
LRU: Least Recently Used
Evicts the item that has not been accessed for the longest time. The assumption: recently accessed data is more likely to be accessed again. Works well for most general workloads.
# Redis: set eviction policy in redis.conf
maxmemory 256mb
maxmemory-policy allkeys-lruLFU: Least Frequently Used
Evicts the item accessed the fewest total times. Better for workloads where some items are accessed constantly over long periods. Redis supports allkeys-lfu. Downside: a new item starts with frequency zero and gets evicted immediately under memory pressure, even if it will be heavily accessed going forward.
TTL: Time-To-Live
Expiration by age, not usage. You set a TTL when writing to the cache. After it expires, the entry is deleted. TTL is not an eviction policy — it is expiration. The two work together: Redis evicts unexpired items under memory pressure using LRU or LFU, while TTL handles staleness. Use LRU for most cases, switch to LFU for a small hot dataset inside a large cache, and always set TTLs on every key to prevent unbounded memory growth.
