How does key expiration (TTL) work in Redis and what are the eviction policies?
Keys can have a Time-To-Live (`EXPIRE`, `SETEX`). Redis removes expired keys via two mechanisms: 1. Passive Eviction: When a client attempts to access an expired key, Redis detects it and deletes it before responding with `nil`. 2. Active Eviction: Background routine periodically samples random keys and deletes expired entries.
When memory hits `maxmemory`, eviction policies take effect: • `allkeys-lru` / `volatile-lru`: Evicts least-recently-used keys. • `allkeys-lfu`: Evicts least-frequently-used keys. • `noeviction`: Returns errors on writes when memory is full.
# Set a verification code with a 5-minute TTL
SET verify:user_88 "492019" EX 300
# Check remaining time to live in seconds
TTL verify:user_88
# Output: (integer) 284After 300 seconds, the key automatically expires. Using Redis for ephemeral tokens avoids accumulating temporary records in your primary relational database.
Ready for Redis as a Session Store?
Take a quick test to evaluate yourself, or move straight to the next module.