Foundations 2 of 5 · Visual guide

Keys you can find, data that cleans itself up

Six months in, most Redis instances look like the left box: keys nobody can explain, and data nobody deletes. This chapter gets you to the right box.

✗ Without a plan
  • u42what is it?
  • tmpwhose?
  • data_final2still used?
  • https://shop.com/p?id=9no TTL
  • sess_9f2cno TTL
  • otp_731904no TTL
memory · 96% of maxmemory, still growing
✓ After this chapter
  • user:42:profilekeeps
  • session:9f2c29:41
  • otp:4212s
  • cache:v2:product:959:02
  • rl:ip:1.2.3.447s
  • user:43:profilekeeps
memory · 38%, flat over time
1

Name keys like pathsAnyone can read a key and know what it is, and find all its siblings.

2

Give temporary data a TTLSessions, codes and caches delete themselves on time.

Fix 1Name keys like paths

Redis has no tables or folders. The key name is your schema.

Anatomy of a key name The key shop:user:42:cart has four segments separated by colons: namespace, object type, id, and field. shop : user : 42 : cart app / service object type id field / sub-object Read it left to right like a URL. SCAN … MATCH shop:user:* finds every user.
Colons are a convention, not a feature — but every Redis GUI groups keys by them.
Do

user:42:profile · session:9f2c · rl:ip:1.2.3.4
Version caches: cache:v2:… — bump to v3 and every old entry is skipped at once.

Don't

u42, full URLs or JSON as keys, spaces, or raw user input without a prefix.

Listing keys? Use SCAN 0 MATCH user:*. Never KEYS * in production — it can freeze Redis for seconds. See why in chapter 3 →

Fix 2Give temporary data a TTL

A TTL (time to live) is a countdown on a key. When it hits zero, the key is gone.

SET otp:42 731904 EX 300 # value + 5-minute TTL, in one command
TTL → 3737 seconds left
TTL → -1exists, never expires
TTL → -2gone (or never existed)
The #1 TTL bug: a plain SET on an existing key erases its TTL. Your 30-minute session now lives forever. Re-send EX, or add KEEPTTL.
The four commands you need
SET k v EX 60Write + expire, atomically. Your default.
EXPIRE k 60 NXAdd a TTL to an existing key (NX: only if it has none).
TTL kSeconds left (PTTL for ms).
PERSIST kRemove the TTL; keep the key.

What happens when time’s up

Reads: instantly

The moment a TTL passes, GET returns (nil). You never see a stale key.

Memory: moments later

A background sweep, 10× a second, deletes expired keys and frees the RAM.

Go deeper: how Redis finds expired keys (diagram + lab)
Lazy and active expiry Fifteen keys have TTLs; six have passed their time. Lazy expiry deletes a key when a client touches it. Active expiry samples twenty keys ten times a second, deletes the expired ones, and samples again if more than a quarter were expired. keys with a TTL k1 k2 ⌛ k3 k4 k5 ⌛ k6 k7 ⌛ k8 k9 ⌛ k10 k11 k12 ⌛ k13 k14 ⌛ k15 sample: k1–k5, k11, k12 → 3 of 7 expired (43%) 43% > 25% → sample again → k9, k14 deleted all expired keys gone · memory reclaimed Lazy · on access GET k7 → expired? → DEL reply (nil) Active · in the background 10× per second: sample 20 keys delete the expired ones > 25% expired? sample again
  1. Redis keeps a second table: key → expiry time. Only keys with a TTL live there. Six of these have passed their time (⌛) but are still in memory.
  2. Lazy expiry: a client runs GET k7. Redis checks the time, sees it passed, deletes k7, and replies (nil). An expired key is never returned.
  3. But keys nobody reads would sit in RAM forever. So a background job runs 10 times a second…
  4. …it picks 20 random keys that have a TTL (here 7, to fit the picture) and deletes the expired ones: k2, k5, k12.
  5. 3 of 7 were expired — more than 25%. That means many more are probably waiting, so it samples again right away and finds k9 and k14.
  6. Result: reads are always correct, and memory is reclaimed in small, cheap steps instead of one big scan.
Two mechanisms: lazy (on touch) guarantees correctness, active (random sampling) frees memory.

Lab · 60 keys, a sampler, and the 25% rule

Press “Time passes”, then run cycles. Watch how a high expired ratio triggers extra samples.

Expiry is not eviction

Expiry · you decide

You set a TTL. The key goes when it ends, even if memory is empty.

Eviction · Redis decides

Memory hits maxmemory, so Redis drops keys by policy (e.g. allkeys-lru) — or rejects writes.

Quick check

A price change means every cached product is stale. Fastest fix?
Show answer

Bump the version in the key: read and write cache:v3:product:*. Old v2 keys are never read again and expire on their own TTL.

A key expired 2 seconds ago but INFO memory still counts it. Bug?
Show answer

No. Reads already return (nil); the background sweep just hasn’t reached it yet.

Remember

Redis keys and expiry: common questions

How do I set an expiry on a Redis key?

SET key value EX 60 sets it with a 60-second TTL, or EXPIRE key 60 on an existing key. TTL key shows the seconds left.