6. Expiry (TTL) & Cache Eviction Policies
TTL Mechanics: Passive vs Active Deletion
Managing memory efficiency requires clearing out stale data automatically. Redis provides this control via Time-To-Live (TTL) associations. When a key is created, developers can attach an expiration timer (in seconds or milliseconds). Once the timer runs down, the key becomes ineligible for read requests and is removed from memory. However, to keep performance high, Redis does not maintain active timers for every key. Doing so would consume significant CPU cycles managing timer heaps.
Instead, Redis uses a combination of Passive Deletion and Active Deletion. Passive deletion occurs when a client attempts to read a key. Before returning the value, Redis checks the key's expiration. If the key has expired, it is deleted from the dictionary immediately, and a null response is returned to the client. While memory-efficient, passive deletion alone is insufficient: if a set of expired keys is never queried again, they would sit in memory forever, leaking RAM.
To solve this, Redis runs an active background pruning task. Ten times per second, the active deletion cron randomly selects 20 keys with expirations from the database. It deletes any expired keys found. If more than 25% of the selected keys are expired, the process loops again, repeating up to a maximum duration threshold. This randomized sampling approach prevents expired keys from accumulating while ensuring the background task never blocks the event loop for more than a few milliseconds.
Maxmemory and Out-Of-Memory Eviction Policies
In caching scenarios, it is common for active data volumes to exceed the physical memory available on the server. If memory is full and a client attempts a write, the server will crash or trigger OS pagination unless a limit is configured. The maxmemory configuration parameter instructs Redis to cap its RAM footprint. Once memory consumption crosses this limit, Redis will trigger a configured Eviction Policy to free space before accepting new writes.
Redis supports several eviction algorithms, which determine which keys to delete when memory limits are reached:
- noeviction: Returns Out-Of-Memory (OOM) write errors to clients, protecting cached data at the cost of service availability.
- allkeys-lru: Least Recently Used. Evaluates all keys in the database, evicting keys that haven't been accessed for the longest time.
- volatile-lru: Evaluates only keys that have an expiration (TTL) configured, preserving persistent keys.
- allkeys-lfu: Least Frequently Used. Tracks access frequency counters, keeping popular keys cached even if they haven't been accessed recently.
- volatile-lfu: Applies LFU eviction exclusively to keys configured with a TTL.
To implement LRU and LFU efficiently without memory bloat, Redis does not track exact timestamps. Instead, it uses an approximated algorithm: it samples a random set of keys (e.g., 5 keys) and evicts the best candidate among that sample. Increasing the sample size increases eviction precision but uses slightly more CPU. For standard application caches, allkeys-lru is the default choice, while hybrid storage architectures use volatile-lru.
// Caching with TTL and Out-Of-Memory Error Resilience const Redis = require('ioredis'); const redis = new Redis({ host: '127.0.0.1', port: 6379 }); async function setCacheDataSafely(key, value, ttlSeconds) { try { // Attempt atomic write with TTL await redis.set(key, JSON.stringify(value), 'EX', ttlSeconds); return true; } catch (error) { // Check if error is due to OOM eviction policy rules (noeviction) if (error.message.includes('OOM command not allowed')) { console.warn('Redis memory limit reached! Unable to write cache.', error.message); // Degrade gracefully: proceed without caching, query backing store directly return false; } throw error; } }
Knowledge Check
Ready to test your understanding of 6. Expiry (TTL) & Cache Eviction Policies?