Learn Labs
Expiration & Memory

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

SET cache:x v EX 300TTL at creation (PX for milliseconds)EXPIRE cache:x 600set or replace a TTL on an existing keyEXPIRE cache:x 600 NXonly if it has no TTL yet (also XX, GT, LT)PEXPIREAT cache:x 1791800000000expire at an absolute Unix time (ms)TTL cache:xseconds left; -1 = no TTL; -2 = key doesn't existPTTL cache:xmilliseconds leftEXPIRETIME cache:xabsolute Unix time it will expirePERSIST cache:xremove the TTL; the key now lives forever

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 budget

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)

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__:expired

Because 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

  1. SET cache:t hello EX 10, then TTL cache:t a few times.
  2. INCR rate:t then EXPIRE rate:t 30, then INCR rate:t again. Check the TTL survived the increment.
  3. SET rate:t 5 and check TTL rate:t again: -1.
  4. Create 10,000 keys with a 5-second TTL from the shell, then watch INFO keyspace and expired_keys over 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

On this page