Back to results for “SQL/Sequelize)”
Node.js › Caching

What is Redis's EXPIRE and how do TTL-based keys interact with Redis's own memory eviction policies under memory pressure?

Advanced

Answer

EXPIRE (or the EX option on SET) sets a time-to-live on a Redis key, after which Redis automatically removes it -- but under memory pressure Redis can also proactively evict keys earlier than expiration according a configured eviction policy (like allkeys-lru, evicting the least recently used key regardless of TTL, or volatile-lru, only evicting keys with a TTL set), which matters because caching data with no TTL under an allkeys policy could have any key evicted at any time.
await redis.set('session:abc123', sessionData, { EX: 3600 });

# redis.conf: only evict keys that have a TTL set, oldest-accessed first
# maxmemory-policy volatile-lru
# maxmemory 2gb
Real-world example A team configures their Redis instance with maxmemory-policy set to volatile-lru specifically because they store both cache data (with TTLs, safe to evict) and durable session data (without TTLs) in the same instance, ensuring memory pressure only ever evicts the cache entries.

Common follow-ups: What's the difference between 'noeviction' and 'allkeys-lru' policies, and what happens to write operations once Redis hits maxmemory under 'noeviction'?;Why might mixing cache data and durable data in the same Redis instance be considered risky regardless of eviction policy?