Expiration
TTLs, how Redis actually deletes expired keys, and TTL design
Most data in Redis should not live forever. A TTL (time to live) makes a key delete itself after a duration, which is how caches stay fresh, sessions end, and rate-limit windows reset, with no cleanup jobs.
Setting and reading TTLs
What keeps a TTL: INCR, HSET, LPUSH, SADD, APPEND, and other
commands that modify the value in place. What clears it: SET
without EX/KEEPTTL, GETSET, and anything that replaces the whole
key. RENAME carries the TTL to the new name.
How expiry actually happens
Redis doesn't run a timer per key. It uses two mechanisms together:
Lazy expiry. Every time a key is accessed, Redis checks its expiry time first. If it has passed, the key is deleted and the command acts as if it never existed. This is why an expired key is never returned.
Active expiry. Lazy expiry alone would leave expired keys nobody
reads sitting in memory forever. So, hz times a second (10 by
default), Redis samples keys from the set of keys with a TTL and deletes
the expired ones. If more than ~10% of a sample was expired, it repeats
immediately, bounded to a small slice of CPU time, so it can't block the
server. active-expire-effort (1-10) trades CPU for memory reclaimed
faster.
INFO keyspace
db0:keys=19,expires=3,avg_ttl=287000,subexpiry=0
INFO stats | grep expired
expired_keys:1532 # deleted because their TTL passed
expired_stale_perc:0.00 # estimated share of keys that are expired but not yet deleted
expired_time_cap_reached_count:0 # times active expiry hit its CPU budgetReplicas don't expire keys on their own. The primary sends an
explicit DEL to replicas (and to the AOF) when a key expires, which
keeps everyone consistent. A replica will still refuse to return a
logically expired key to a reader, but it won't free the memory until
the primary's DEL arrives.
Expiry and big keys
Expiring a key with a million elements frees a million allocations.
With lazyfree-lazy-expire yes (set in this repo's redis.conf), that
work happens in a background thread instead of blocking the event loop.
The same applies to evictions and DEL with the other lazyfree-*
settings.
TTL design
Every cache key gets a TTL. No exceptions. Without one, a cache only ever grows, and stale data is never refreshed.
Add jitter. If 10,000 keys are written at the same moment with the same TTL, they all expire at the same moment, and 10,000 requests hit the database together. Randomise by ±10%:
def ttl_with_jitter(base: int = 300) -> int:
return int(base * random.uniform(0.9, 1.1))Match the TTL to how stale the data may be. A product price shown for 5 minutes after a change may be fine; a user's permissions cached for an hour after revocation probably isn't. TTLs are a staleness budget.
Sliding expiration for sessions: reset the TTL on every access, so active users stay logged in and idle ones are logged out:
GETEX session:abc EX 1800 # for a string session
HGETALL session:abc + EXPIRE session:abc 1800 # for a hash session (pipeline them)EXPIRE with a relative duration on every read can keep a hot key
alive forever, even if it should be refreshed from the database. For
caches, prefer a fixed TTL set at write time (stale data eventually
goes), and sliding TTLs only for things like sessions where "idle time"
is the point.
Keyspace notifications
Redis can publish an event when keys expire (or change), which is useful for reacting to session timeouts:
CONFIG SET notify-keyspace-events Ex # E = keyevent channel, x = expired events
SUBSCRIBE __keyevent@0__:expiredBecause of lazy and active expiry, the event fires when Redis deletes the key, which can be some time after the TTL passed if nobody accesses it. Don't use it for anything time-critical.
Lab
SET cache:t hello EX 10, thenTTL cache:ta few times.INCR rate:tthenEXPIRE rate:t 30, thenINCR rate:tagain. Check the TTL survived the increment.SET rate:t 5and checkTTL rate:tagain: -1.- Create 10,000 keys with a 5-second TTL from the shell, then watch
INFO keyspaceandexpired_keysover the next 20 seconds without reading any of them. Active expiry removes them.
for i in $(seq 1 10000); do echo "SET cache:bulk:$i x EX 5"; done | \
docker exec -i redis redis-cli --user app --pass app123 > /dev/null