Redis key expiration works best when each family of keys gets its own TTL pattern, with a few random seconds of jitter added, so a group of keys scatters instead of expiring together. A TTL, or time-to-live, is the number of seconds after which Redis deletes a key on its own. The mistake that causes outages is putting the same TTL on every key: thousands expire in the same second, and your database absorbs every cache miss at once. Eviction is a separate decision. It is what maxmemory-policy throws away when memory runs out, and some policies only consider keys that have a TTL. Below are four working patterns for an object cache, a session store and a rate limiter, the line between expiry and eviction, and a way to list keys that never expire.
What you’ll accomplish
- Read the expiry mechanism well enough to explain why
used_memorydoes not drop the moment a TTL passes, and whyDBSIZEdisagrees with the number of keys you think are live. - Pick the right TTL pattern per key family — object cache, PHP sessions, rate limiters, queue dedupe — instead of applying one number to everything.
- Separate the TTL decision from the
maxmemory-policydecision, and stop thevolatile-*failure mode where the instance sits at its ceiling refusing writes. - Find every key in the instance that carries no expiry at all, and know whether that is deliberate.
- Alarm on the two numbers that actually move first:
expired_stale_percandevicted_keys.
Prerequisites
- Redis 7.0 or later for the
NX/XX/GT/LTmodifiers onEXPIREand forEXPIRETIME. Redis 6.2 forGETEX. Redis 7.4 for hash-field TTLs (HEXPIRE). Everything else here works back to Redis 5. Valkey behaves identically for all of these commands. - Shell access with
redis-cli, and either the password in~/.redisrc-style tooling orREDISCLI_AUTHexported. Examples below assume a local instance on the default port. - Permission to run
CONFIG SET. Managed Redis services usually block it and expect a parameter-group change plus a restart or an apply window; hardened self-hosted instances sometimes rename it viarename-command. Check before you plan a change window. - On Linux,
date -daccepts relative strings. On macOS and other BSDs it does not — the absolute-deadline example gives both forms.
How it works
Redis keeps a second dictionary per database, the expires table, mapping keys that have a TTL to an absolute millisecond timestamp. Setting a TTL adds an entry there; PERSIST removes it. That table is the reason INFO keyspace can tell you, in one line, how much of your keyspace is actually governed by expiry.
The TTL passing does nothing on its own. Nothing fires, nothing is scheduled. A key leaves memory by one of exactly two paths, shown below.
The lazy path runs when a client touches the key. Redis compares the stored deadline against the clock, deletes the key if it has passed, and answers as though the key were absent. This is free for keys nobody asks for again, and it is why a client never reads stale data even when the memory has not been reclaimed.
The active path is a cycle inside serverCron, which runs hz times per second — 10 by default. Each pass samples a bounded number of keys from the expires table (20 per loop in the reference implementation), deletes the ones that have elapsed, and repeats while more than about a quarter of the sample comes back expired, up to a CPU time budget. active-expire-effort (Redis 6.0+, values 1 to 10) tunes how hard that cycle pushes against the budget.
Both facts follow directly from the sampling. First, memory lags the TTL: a key with an elapsed deadline that nobody touches sits allocated until the sampler happens to draw it, so used_memory falls behind and DBSIZE counts keys that are logically gone. Second, expiry is not synchronous with anything — the guarantee is “not readable after the TTL”, never “removed at the TTL”.
Two more behaviours matter operationally. Replicas do not expire keys on their own; the primary deletes and propagates an explicit DEL or UNLINK, so a replica can hold an expired key in memory until that arrives, while still refusing to serve it. And lazyfree-lazy-expire yes moves the actual free into a background thread, which is worth setting on instances that expire large values.
Step-by-step
-
Count what has no TTL before you change anything. The expires table gives you this for free:
redis-cli INFO keyspace# Keyspace db0:keys=184203,expires=51110,avg_ttl=0That instance has 184,203 keys and only 51,110 with an expiry — 133,093 keys that will never leave on their own.
avg_ttlis frequently 0 and is not worth reading. To see which families they belong to:redis-cli --scan --pattern 'wp:*' | head -5000 | while read -r k; do [ "$(redis-cli TTL "$k")" = "-1" ] && echo "$k" done | awk -F: '{print $1":"$2}' | sort | uniq -c | sort -rn | head2841 wp:posts 903 wp:options 412 wp:transientPersistent object-cache entries with no TTL are a defensible choice. Transients with no TTL are a bug.
-
Use an absolute deadline when the data is tied to a wall-clock boundary. Daily counters, an order tally, anything that resets at midnight:
# Linux redis-cli SET wc:orders:2026-09-05 0 EXAT "$(date -d 'tomorrow 00:00' +%s)" # macOS / BSD redis-cli SET wc:orders:2026-09-05 0 EXAT "$(date -v+1d -v0H -v0M -v0S +%s)"OKEXATonSETand the standaloneEXPIREATboth take an absolute UNIX timestamp, so restarts, retries and re-writes of the same key cannot slide the deadline forward. The cost is that a clock skew between application hosts becomes a correctness problem — set the deadline from one source, not from each worker’s own clock. -
Use a sliding window only where idleness is the thing you are measuring. PHP sessions are the canonical case: the session should die after 30 minutes of inactivity, not 30 minutes after login. Refresh on read, in one round trip:
redis-cli GETEX sess:7f21c9 EX 1800 redis-cli TTL sess:7f21c9"a:2:{s:4:..." (integer) 1800GETEX(Redis 6.2+) reads and re-arms in one command. If you are on the PHPredissession handler, this already happens — PHP sets the TTL fromsession.gc_maxlifetimeon every request. The cost of sliding windows is that a busy key is immortal, so pair one with a hard cap if the data must eventually go. -
Jitter the TTL whenever a cohort of keys is written together. A deploy that warms the WordPress object cache writes thousands of keys inside the same minute. Give them all
EX 3600and they all expire inside the same minute an hour later, and every one of those requests goes to MySQL at once:BASE=3600 TTL=$(( BASE + RANDOM % (BASE / 10) )) redis-cli SET wp:post:1204 rendered EX "$TTL" redis-cli TTL wp:post:1204OK (integer) 3512Ten percent of spread is usually enough to turn a cliff into a slope. In the Redis Object Cache plugin the ceiling is
WP_REDIS_MAXTTLinwp-config.php; jitter has to be applied by whatever writes the key, so for plugin-managed caches the practical move is a shorterWP_REDIS_MAXTTLplus a warmer that does not run all at once. Which cache you are jittering matters too — see Redis vs Memcached for the WordPress object cache. -
Set the value and the TTL in one command, always.
SETwithEXandNXis atomic, and that atomicity is the entire pattern for locks and for queue dedupe:redis-cli SET dedupe:job:9f2a41 1 EX 86400 NX redis-cli SET dedupe:job:9f2a41 1 EX 86400 NXOK (nil)The first caller gets
OKand owns the job; every duplicate gets(nil)and drops it. A rate limiter is the same shape —SET rl:ip:203.0.113.7 0 EX 60 NXto open the window, thenINCRto count inside it. Doing this asSETfollowed byEXPIREleaves a window where a crash between the two commands produces a key with no expiry, which is exactly how instances accumulate the immortal keys you counted in step 1. -
Never let an update silently clear the TTL. A bare
SETon an existing key resets it to no expiry:redis-cli SET sess:7f21c9 newvalue redis-cli TTL sess:7f21c9 redis-cli SET sess:7f21c9 newvalue KEEPTTL redis-cli TTL sess:7f21c9OK (integer) -1 OK (integer) -1Note what the third command cannot do:
KEEPTTLpreserves an existing TTL, it does not restore one you already destroyed. This is a real and quiet bug source — a cache-warming job that rewrites values with a plainSETwill strip the expiry from every key it touches, and nothing in the logs will say so.PERSISTdoes the same thing deliberately; treat it as a command that needs review. -
Decide
maxmemoryandmaxmemory-policyas a separate question. TTLs express how stale a value may become. Eviction is what keeps the instance answering writes when traffic outruns those TTLs. They are independent axes, and one of the four combinations is an outage:The default policy is
noeviction, which refuses writes at the ceiling by design — correct for a job queue, wrong for a cache. Thevolatile-*family only ever considers keys that carry a TTL, so on an instance where most keys have none, it hits the ceiling with an empty candidate set and behaves exactly likenoeviction. For a pure cache:redis-cli CONFIG SET maxmemory 2gb redis-cli CONFIG SET maxmemory-policy allkeys-lru redis-cli CONFIG REWRITEOK OK OKCONFIG REWRITEis the step people skip, and it is why the setting vanishes at the next restart. Sizing the ceiling itself is its own exercise — maxmemory tuning covers the headroom arithmetic. -
Treat expired-key notifications as a hint, not a trigger. They exist and they are useful for cleanup:
redis-cli CONFIG SET notify-keyspace-events Ex redis-cli SUBSCRIBE '__keyevent@0__:expired'1) "message" 2) "__keyevent@0__:expired" 3) "sess:7f21c9"Three caveats, all of which have burned somebody. The event carries the key name and not the value, which is gone by then. It fires when Redis detects the expiry — the lazy touch or the sampler pass — which can be well after the TTL. And delivery is fire-and-forget over pub/sub: a subscriber that is restarting at that moment never learns. If a job must run when something expires, put the job in a queue at write time and let the TTL be a cache concern.
Validate it works
Take a baseline, then re-read the same numbers after your changes have been live through a full traffic cycle.
redis-cli INFO keyspace
redis-cli INFO stats | grep -E 'expired_keys|expired_stale_perc|keyspace_hits|keyspace_misses|evicted_keys'
redis-cli INFO memory | grep -E 'used_memory_human|maxmemory_human|maxmemory_policy'
db0:keys=52380,expires=51902,avg_ttl=0
expired_keys:4812093
expired_stale_perc:1.24
keyspace_hits:88213445
keyspace_misses:2109883
evicted_keys:0
used_memory_human:1.42G
maxmemory_human:2.00G
maxmemory_policy:allkeys-lru
Read it in this order. keys minus expires is now 478 rather than 133,093 — the untagged keys are gone. expired_stale_perc under a few percent means the active cycle is keeping up; consistently above 25% means it is not. evicted_keys at zero with used_memory below the ceiling means TTLs are doing the work and eviction is only the backstop, which is the state you want. evicted_keys climbing steadily means your TTLs are too long for the memory you bought.
Then confirm the failure mode is actually gone by filling the instance rather than trusting the config:
redis-cli --no-raw SET canary:write "$(head -c 1024 /dev/zero | tr '\0' 'x')" EX 60
OK
Under noeviction or a starved volatile-* policy at the ceiling, that same command returns OOM command not allowed when used memory > 'maxmemory'. instead.
For the keys that survive everything, check what they cost:
redis-cli --bigkeys
redis-cli MEMORY USAGE wp:posts:1204
[00.00%] Biggest string found so far '"wp:options:alloptions"' with 1841233 bytes
-------- summary -------
Sampled 52380 keys in the keyspace!
Biggest string found '"wp:options:alloptions"' with 1841233 bytes
(integer) 4128
Under an LFU policy, OBJECT FREQ <key> returns an access-frequency counter that tells you whether a large key is actually earning its space; under LRU, OBJECT IDLETIME <key> gives seconds since last access instead. Both are read-only and safe on a live instance.
Troubleshooting
Writes fail with OOM command not allowed when used memory > 'maxmemory' while evicted_keys stays at 0. This is the failure quadrant. Confirm with redis-cli CONFIG GET maxmemory-policy and INFO keyspace: a volatile-* policy plus an expires count near zero means there is nothing eligible to evict. Switch to allkeys-lru, or give the cache keys TTLs. Do not raise maxmemory first — that buys hours and hides the cause.
used_memory stays flat for minutes after a large batch of keys expires. The sampler has not reached them. Check expired_stale_perc and expired_time_cap_reached_count in INFO stats; if the first is high and the second is climbing, raise active-expire-effort a step at a time, or hz from 10 to 50, and watch CPU. Both trade background CPU for responsiveness, and on a small instance the trade is not always worth it.
Users are logged out early and at random. Something is issuing a plain SET against session keys, dropping the TTL, after which the key becomes immortal and the session store grows until eviction removes it at an arbitrary moment. MONITOR briefly on a quiet instance, or redis-cli TTL a handful of live session keys — a mix of sensible TTLs and -1 on the same key family confirms it. The fix is KEEPTTL or GETEX in the writer.
Origin load spikes on the hour, every hour. Synchronized TTLs. Sample a few dozen keys of one family and look at the spread of TTL values; if they cluster within a few seconds of each other, add jitter at write time. Instances warmed by a single deploy script are the usual suspects.
A cleanup worker subscribed to __keyevent@0__:expired misses events. Expected behaviour, not a fault. Pub/sub has no backlog, so anything published while the subscriber is disconnected is lost, and on a replica the event fires only when the primary’s DEL arrives. Move the work to a durable queue.
When this is the wrong approach
TTLs are not a scheduler. If something must happen at a specific time, a sorted set keyed by timestamp with a poller — or an actual job queue — gives you retries, visibility and a backlog that survives a restart. Expiry gives you none of those.
TTLs are also not a retention policy for data you cannot afford to lose. Redis will drop the key when the deadline passes whether or not anything consumed it, and under an allkeys-* policy it may drop the key well before that. Anything that must exist tomorrow belongs in a datastore with durability semantics you can state out loud.
Per-item expiry inside a collection is mostly unavailable. Hash fields gained their own TTLs in Redis 7.4 with HEXPIRE, but lists, sets and sorted sets still have none — the TTL applies to the whole key. When you need per-member expiry on a sorted set, the usual pattern is to store the deadline as the score and trim with ZREMRANGEBYSCORE on a schedule.
And if the whole instance is one workload with one staleness tolerance, resist the urge to build a TTL taxonomy. One TTL, jittered, plus allkeys-lru, is a complete answer for a large number of caches. The command reference is at redis.io/docs, and the object-cache side of the WordPress story at developer.wordpress.org.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.