Video in progress
Does Redis remove a key from memory the moment its TTL runs out?
Not always. Redis removes keys in two ways: when a key is accessed and found expired, it deletes it (lazy), and in the background it periodically checks random keys (active). So a dead key can sit in RAM for a while.
📖 Answer
From the client's point of view everything is correct: if you GET an expired key, you get nil, because Redis deletes it right then and only then answers.
But keys that nobody accesses are left to the background cycle. It samples keys that have a TTL several times per second, deletes the expired ones, and repeats if the sample had a lot of dead keys. This frees RAM gradually, not instantly.
Practical consequences:
DBSIZEandused_memorymay still count expired keys;- if you give millions of keys the same TTL at once, they all "die" at the same moment, the background cleanup eats CPU and latency spikes;
- replicas don't delete a key on their own, they wait for a
DELfrom the master (on reads, though, they still report an expired key as missing).
expired_keys in INFO stats shows how many keys have been removed by expiry.
Sign up to mark studied questions and save your progress.