Redis FundamentalsLesson 1.4
Redis key expiry and TTL: how to set and check expiration
EXPIRE, EXPIREAT, TTL, PERSIST, key eviction, expiry use cases, EX option on SET
Why expiry matters
Redis lives in RAM. You must control memory by expiring keys you no longer need — especially cached data and session tokens.
Setting expiry
# Set a key and expire it in 60 seconds
SET session:abc123 "user:42"
EXPIRE session:abc123 60
# Shorthand: set and expire in one command
SET session:abc123 "user:42" EX 60
# Expire at a specific Unix timestamp
EXPIREAT session:abc123 1735689600Checking remaining TTL
TTL session:abc123 # → 47 (seconds remaining)
# → -1 (no expiry set)
# → -2 (key does not exist)Removing expiry
PERSIST session:abc123 # removes expiry, key lives foreverHow Redis deletes expired keys
Redis uses two strategies. Lazy expiry: a key is checked and deleted when you next access it. Active expiry: Redis periodically samples random keys with TTLs and deletes the expired ones. This means a key may survive a few milliseconds past its TTL under low access — design your application to tolerate this.
For caching, always set an EX value. A cache entry with no expiry is a memory leak.
