Reading — step 1 of 3
Lazy Deletion
~1 min readKey Expiry
Passive Expiry — Lazy Deletion
When a key expires, Redis doesn't immediately delete it. Instead, it uses passive (lazy) expiry: the key is deleted when someone tries to access it.
How It Works
Before processing any command that accesses a key:
- Check if the key has an expiry time
- If
current_time >= expiry_time, delete the key silently - Then process the command as if the key never existed
What This Means
SET temp hello
EXPIRE temp 5
WAIT 6000 → (6 seconds pass)
GET temp → $-1 (expired, returns null)
EXISTS temp → :0
TTL temp → :-2
DBSIZE → doesn't count expired keys
Why Lazy?
Eagerly scanning all keys for expiry is expensive. Lazy deletion is O(1) per access. Real Redis also does active expiry (randomly sampling keys periodically), but passive expiry is the foundation.
Implementation
Add a check_expiry(key) function that runs before every key access. If expired, delete from all stores (strings, lists, hashes, etc.) and remove the expiry entry.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…