How Redis keys expire
You set a key to expire in ten seconds. Redis does not start a timer, and at second ten nothing happens. The key goes later, in one of two ways. And when memory runs out, a third mechanism picks keys to throw away even though they have not expired. Here are all three, drawn and then measured on Redis 8.
01 A TTL is a deadline, not a timer
A timer per key would cost memory and work for every key with a TTL, and a cache can hold millions of them. Instead Redis stores a deadline: an absolute time in milliseconds since 1970. TTL and PTTL work out how much is left by subtracting the current time; EXPIRETIME (Redis 7.0 and later) shows the stored deadline itself.
-1 means the key exists but has no TTL, and -2 means there is no such key. These replies are from a real Redis 8.4 server; the EXPIRETIME value depends on when you run it. Deadlines live in a separate expires table, so a key without a TTL costs nothing extra.
| Command | TTL afterwards |
|---|---|
| SET key value | removed: a plain SET makes a key with no TTL |
| SET key value KEEPTTL | kept (Redis 6.0 and later) |
| INCR, APPEND, HSET, LPUSH | kept: changing the value does not touch the deadline |
| RENAME key other | moves with the key |
| PERSIST key | removed |
| EXPIRE key -1 | the key is deleted at once |
02 Lazy expiry: checked when you read
The first way an expired key goes is on access. Every command that looks up a key first checks the expires table. If the deadline has passed, Redis deletes the key right then and carries on as if it was never there.
- just stored
- deadline checked
- returned
- deleted
An empty Redis at t = 0. It keeps two tables: every key with its value, and a second one holding a deadline for each key that has a TTL.
Lazy expiry alone guarantees correctness: no client can ever read an expired value. What it cannot do is free memory for keys nobody reads again, such as a session whose user closed the tab. Those would stay forever.
03 Active expiry: a sweep in the background
So Redis also cleans up on its own. A cycle runs hz times a second (default 10). It walks the expires table in batches, deletes what has expired, and decides from the batch whether to keep going.
- checked, still live
- expired, deleted
- just deleted
- not reached this cycle
It is t = 10 and nobody has read these keys. Ten times a second (hz 10), Redis runs a cycle that walks the expires table in batches, so expired keys get deleted even if no client asks for them. Our toy batch is 4 keys; the real default is 20.
In Redis 6 and later, with the default active-expire-effort 1, a batch is about 20 keys, and the cycle keeps taking batches while more than about 10% of a batch had expired. A time limit stops each cycle from taking more than a fixed share of the CPU, so a burst of expired keys is cleared over several cycles rather than freezing the server. Older Redis documentation describes random samples and a 25% threshold; the idea is the same.
04 See both on a real server
You can switch the background cycle off and watch expired keys pile up. DEBUG commands are disabled by default since Redis 7, so start a throwaway server that allows them, on a spare port, with no persistence:
With the sweep off, the 1,000 expired keys still count in DBSIZE. Reading temp:1 deleted exactly one of them, lazily. Turning the sweep back on removed the other 999 within two seconds, and expired_keys counts both kinds. This was a real run on Redis 8.4; stop the server with redis-cli -p 6420 SHUTDOWN afterwards.
INFO keyspace shows db0:keys=1001,expires=1000 at the first DBSIZE: keys past their deadline still count until one of the two mechanisms deletes them. Use it, with expired_stale_perc in INFO stats, to see how far behind the sweep is.
05 When memory runs out: eviction
Expiry is about time. Eviction is about space: when maxmemory is set and a write would go over it, Redis deletes keys that have not expired to make room. Which keys depends on maxmemory-policy. The default is noeviction, which deletes nothing and refuses writes:
With an LRU or LFU policy, Redis needs the least used key. Keeping every key in exact order would cost a linked list node per key and work on every read. Instead each key stores a small clock of when it was last used, and Redis samples:
- sampled
- added to the pool
- evicted
- truly the oldest
maxmemory is set, the policy is allkeys-lru, and memory is at the limit. A client sends SET new …. Before running it, Redis must free memory. It does not keep the keys in exact LRU order; each key only records when it was last used.
Redis keeps a pool of 16 candidates between rounds, so good candidates found earlier are not forgotten, and it repeats the round until memory is under the limit. Raise maxmemory-samples to 10 and the choice gets very close to true LRU, for a little more CPU per eviction. On the real server, with maxmemory 3mb and allkeys-lru, 10,000 more writes all succeeded and evicted_keys counted 10,539.
06 How expiry and eviction meet
The policy name says which keys eviction may take. allkeys-* may evict any key. volatile-* may evict only keys that have a TTL, which lets you keep permanent keys and a cache in one server.
| Policy | May evict | Picks |
|---|---|---|
| noeviction | nothing | refuses writes with OOM |
| allkeys-lru / allkeys-lfu | any key | least recently / least frequently used, sampled |
| allkeys-random | any key | a random one |
| volatile-lru / volatile-lfu | keys with a TTL | least recently / least frequently used, sampled |
| volatile-random | keys with a TTL | a random one |
| volatile-ttl | keys with a TTL | the one with the nearest deadline |
A volatile-* policy on keys that have no TTL has nothing to evict, and behaves like noeviction. On the test server, switching to volatile-lru with only plain keys made 4,872 of 5,000 writes fail with OOM.
The two counters in INFO stats tell you which mechanism is doing the deleting: expired_keys for TTLs and evicted_keys for memory pressure. A steadily rising evicted_keys means the cache is too small for its working set, or its TTLs are too long.
07 When it bites
SET session:9 bobA plain SET wipes the TTLOverwriting a key with SET makes it permanent. Pass EX, PX or KEEPTTL every time, or the key outlives its purpose.EX 3600 on 1,000,000 keys, all at onceEverything expires in the same secondKeys written together expire together. The sweep has a burst to clear and your database a burst of misses. Add a few percent of random jitter to each TTL.GET on a replicaReplicas do not expire on their ownA replica waits for the primary to send a DEL for each expired key, so expired keys can use replica memory a little longer. Since Redis 3.2, a read on a replica still returns nothing for a key past its deadline.maxmemory-policy volatile-lruA volatile policy with no TTLsIf keys are written without a TTL, there is nothing to evict and writes fail with OOM, as the callout above showed.EXPIRE cart:7 600 -- meant one fieldA TTL covers the whole keyEXPIRE acts on the key, not on one field of a hash. Redis 7.4 added HEXPIRE for hash fields; before that, put the field in its own key.