Keys and Expiry
Naming, TTLs, and the only garbage collection there is.
Chapter 1 said a key is the only way in. So: what to call them, and how to expire them.
Key naming
There is no enforced scheme. The convention everyone uses is colon-separated segments, from general to specific:
SET user:1138:name ada
SET user:1138:session abc123
GET user:1138:namePick one shape and keep it. A codebase with two conventions has two namespaces nobody can list.
SET with options
SET takes modifiers that remove a round trip. EX sets a lifetime in seconds:
SET token abc EX 100
TTL tokenNX writes only if the key is absent; XX only if it exists:
SET lock 1 NX
SET lock 2 NX
GET lock
SET lock 3 XX
GET lock
SET fresh 1 XXOne trap worth meeting now. A plain SET over an existing key discards its TTL:
SET k v1 EX 100
SET k v2
TTL kKEEPTTL is the fix:
SET k v1 EX 100
SET k v2 KEEPTTL
TTL kEXPIRE and TTL
EXPIRE adds a lifetime to a key that already exists:
SET city London
TTL city
EXPIRE city 60
TTL cityIt returns whether it did anything, so a missing key is a 0 rather than an error:
EXPIRE nothing 60Minus one and minus two
TTL has three kinds of answer, and two of them are negative:
SET forever v
SET temp v EX 60
TTL forever
TTL temp
TTL missingPERSIST
It removes an expiry, turning a temporary key permanent:
SET k v EX 100
TTL k
PERSIST k
TTL k
PERSIST kHow keys actually expire
No timer per key. A key goes when something reads it, or when a background job samples it:
SET blink v PX 300
EXISTS blinkEXISTS blink
GET blink
DBSIZEredis-cli INFO stats | grep expired_keysSCAN, and never KEYS
SCAN walks the keyspace in batches. It replies with a cursor and some keys:
SET only:1 v
SCAN 0The first element is the cursor for next time. A 0 means finished; anything else is where
to resume.
MATCH filters, and belongs with a generous COUNT:
MSET u:1 a other 1
SCAN 0 MATCH u:* COUNT 100KEYS does the same job in one reply, and that is the problem:
SET u:1 a
KEYS u:*RENAME, COPY, TOUCH
SET old v
RENAME old new
EXISTS old
GET new
COPY new dup
GET dup
TOUCH new dup missingTOUCH counts how many exist, and counts as a read — see chapter 10’s LRU.
RENAME overwrites the destination without asking. RENAMENX refuses instead:
SET a 1
SET b 2
RENAME a b
GET b
SET c 3
RENAMENX c bChoosing a TTL
A key with no TTL is permanent. Give cached data an expiry as you write it:
SET page:home:html "<h1>hi</h1>" EX 300
SET config:version 7
TTL page:home:html
TTL config:version