Redis from First Principles, Part 5: a TTL isn't a scheduled deletion
5 Aug 2026 · 3 min read · first published on LinkedIn
You set a key to expire in 60 seconds.
60 seconds pass. Nobody touches it.
Is the key actually gone?
Last post ended with a question:
What happens when Redis runs out of memory?
My first instinct was to jump straight into eviction policies.
But before Redis can make that decision, there's a simpler question.
What about the keys that were already supposed to disappear?
The obvious mental model
My first mental model was obvious.
Every key with a TTL gets its own timer.
When the timer reaches zero: delete the key.
Then I imagined a Redis instance with millions of expiring keys.
Millions of timers.
On a single-threaded server.
Suddenly that mental model stopped making sense.
Redis doesn't do that
It does something much simpler.
When you set a TTL, Redis simply stores when the key should expire.
That's it.
No timer starts.
Nothing is counting down.
The next time someone accesses that key, Redis checks:
"Has this key already expired?"
If yes, it deletes the key right there and behaves as if it never existed.
Which creates an interesting problem.
What if nobody ever reads that key again?
By this logic, the expired key would sit in memory forever.
Logically dead.
Physically still consuming memory.
So Redis adds a second mechanism
A few times every second, it randomly samples a small set of keys that have TTLs.
If some of them have expired...
It deletes them.
If many of them have expired...
It immediately samples another batch.
If most are still alive...
It stops.
Redis only works harder when there's actually more cleanup to do.

That was the biggest mental shift for me.
A TTL isn't a scheduled deletion.
It's permission to delete after a certain point in time.
Sometimes Redis notices because your application accesses the key.
Sometimes Redis notices during its background sampling.
Either way, the key eventually disappears without maintaining millions of individual timers.
Takeaway
The pattern here is much bigger than Redis.
Instead of doing expensive cleanup the moment something becomes eligible for deletion...
- Mark it.
- Clean it up lazily when it's accessed.
- Sweep the leftovers in the background.
But all of this assumes the key asked to expire.
What happens when memory fills up and Redis has to remove keys that never had a TTL?
Now Redis isn't honoring a request.
It's making a decision.
And every decision needs a policy.
That's what I'll explore in the next post.
Comments and corrections are open on the original post.