You give a key a TTL (time to live) with EXPIRE or PEXPIRE. You can also set the value and TTL in one step with SET key value EX 60. TTL shows the seconds left, and PERSIST removes the expiry. For each key, Redis stores an absolute expiry timestamp.
Redis removes expired keys in two ways:
- Passive expiry: when a client reads a key, Redis checks the timestamp. If the key has expired, Redis deletes it. So clients never see expired data.
- Active expiry: a background cycle runs many times per second. It takes a sample of keys that have a TTL and deletes the expired ones. When it finds many expired keys, it repeats quickly. This catches keys that nobody reads again.
So an expired key can use memory for a short time, but Redis never returns it.
On replicas, the primary controls expiry. When a key expires, the primary sends a DEL command to the replicas.
- Use
EXPIRE,SET ... EX,TTLandPERSISTto manage expiry. - Passive expiry deletes an expired key when someone accesses it.
- Active expiry samples keys with a TTL in the background and deletes expired ones.
- Expired keys may stay in memory briefly, but Redis never returns them.
- Replicas rely on the primary's
DELcommands for expiry.
Read more