How does Redis handle key expiration and TTL?
Learn how Redis TTL works: set expiry with EXPIRE and SET EX, read TTL/PTTL, and how lazy plus active expiration reclaim memory automatically.
Expected Interview Answer
Redis lets you attach a time-to-live (TTL) to any key with commands like EXPIRE or SET ... EX, after which the key is automatically deleted; expired keys are removed lazily on access and proactively by a periodic background sampler.
You set expiration in seconds or milliseconds (EXPIRE, PEXPIRE, EXPIREAT, or options on SET), and TTL/PTTL report the remaining time. Redis uses two mechanisms: lazy expiration deletes a key when it is next accessed and found expired, and active expiration periodically samples a batch of keys with TTLs and evicts the expired ones. This keeps memory bounded without scanning every key. Expiration is distinct from the maxmemory eviction policy, which drops keys under memory pressure even if they have no TTL.
- Automatic cleanup of stale data without application code
- Fine-grained control in seconds or milliseconds
- Lazy plus active expiration bounds memory efficiently
- TTL/PTTL let you inspect remaining lifetime
- Ideal for caches, sessions, rate limiters and locks
AI Mentor Explanation
A TTL is like a substitute fielder allowed on the field for a fixed number of overs. The umpire does not stare at a stopwatch constantly; the moment that fielder next touches the ball the officials check and send them off if the window has passed, and periodic checks also catch any lingering substitutes.
Step-by-Step Explanation
Step 1
Set a TTL
Use EXPIRE key 60, PEXPIRE for milliseconds, EXPIREAT for a Unix timestamp, or SET key val EX 60.
Step 2
Inspect remaining time
Call TTL key (seconds) or PTTL key (milliseconds); -1 means no expiry, -2 means the key is gone.
Step 3
Lazy expiration
When a client accesses a key, Redis checks its TTL and deletes it on the spot if it has expired.
Step 4
Active expiration
A background cycle samples keys with TTLs several times per second and evicts the expired ones.
Step 5
Persist or reset
Use PERSIST to remove a TTL, or re-run EXPIRE to extend or reset the countdown.
What Interviewer Expects
- Knowledge of EXPIRE, PEXPIRE, TTL and PTTL commands
- Explanation of lazy versus active expiration
- Understanding that TTL -1 means no expiry and -2 means missing
- Distinction between expiration and maxmemory eviction
- Awareness that write commands can clear or preserve a TTL
Common Mistakes
- Believing keys are deleted at the exact millisecond they expire
- Confusing key expiration with the maxmemory eviction policy
- Forgetting that SET without KEEPTTL removes an existing TTL
- Thinking TTL returns -2 for keys that simply have no expiry
- Assuming active expiration scans every key rather than sampling
Best Answer (HR Friendly)
“Redis lets you give a key an expiry timer so it deletes itself after a set time, which is perfect for caches and login sessions. It cleans up expired keys both when they are next touched and through a regular background sweep, so old data does not linger.”
Code Example
# Set a key that expires in 60 seconds
SET session:42 "user-data" EX 60
# Add expiry to an existing key
EXPIRE cart:9 120
# Check remaining time to live
TTL session:42 # -> 57 (seconds left)
PTTL session:42 # -> 57000 (milliseconds)
TTL missing:key # -> -2 (key does not exist)
TTL forever:key # -> -1 (no expiry set)
# Remove the expiry, keep the key
PERSIST session:42Follow-up Questions
- What is the difference between lazy and active expiration?
- Does SET without KEEPTTL clear an existing TTL?
- How does key expiration differ from the maxmemory eviction policy?
- What do TTL values of -1 and -2 mean?
- How are expirations propagated to replicas?
MCQ Practice
1. What does TTL on a key that exists but has no expiry return?
TTL returns -1 for a key that exists with no associated expiration, and -2 when the key does not exist.
2. Which best describes Redis active expiration?
Active expiration periodically samples a batch of keys that have TTLs and removes the expired ones, avoiding a full scan.
3. Which command removes a TTL while keeping the key?
PERSIST removes the expiration from a key so it lives indefinitely, without deleting the key itself.
Flash Cards
Command to set a 60s expiry? — EXPIRE key 60, or SET key val EX 60.
What does TTL -2 mean? — The key does not exist.
What does TTL -1 mean? — The key exists but has no expiration set.
Two expiration mechanisms? — Lazy (on access) and active (periodic sampling of keys with TTLs).
How to remove a TTL but keep the key? — Use PERSIST.
Continue Learning
Related Interview Questions
What is the difference between Redis persistence with RDB and AOF?
medium
What is the difference between Redis as a cache and as a primary datastore?
medium
How does Redis handle memory management and the maxmemory setting?
hard
What is Redis and what makes it different from a traditional relational database?
easy