Key design, expiry and what TTL really returns

Redis Course · lesson 3 of 19 · 5 min read

A key is your only index in Redis, and a TTL is the only thing stopping it living forever.

Open this lesson in the learning hub

Key points

  • The convention is colon separated namespaces such as user:1000:profile or cart:sess:abc123.
  • Keys are binary safe and may be up to 512 MB, but every byte is stored per key, so keep them short and regular.
  • SET key val EX 60 sets the value and a 60 second expiry in one atomic command.
  • TTL key returns the seconds left, -1 when the key has no expiry, and -2 when the key does not exist.
  • A plain SET clears any existing expiry unless you pass KEEPTTL, which arrived in Redis 6.0.
  • Expired keys are removed lazily on access and by an active cycle that samples 20 keys with a TTL, ten times a second.

Example

SET  session:abc123 "user:1000" EX 1800   # 30 minute session
TTL  session:abc123                       # (integer) 1800
EXPIRE session:abc123 60 XX               # XX = only if a TTL already exists (7.0+)
PERSIST session:abc123                    # remove the expiry, key becomes permanent
TTL  session:abc123                       # (integer) -1  -> lives forever now
TTL  session:nope                          # (integer) -2  -> no such key
SET  session:abc123 "user:1001" KEEPTTL   # 6.0+: change value, keep the clock

Every cache key needs a TTL, and only KEEPTTL or a fresh EX survives an overwrite.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Redis Course course, and every lesson in it is listed on the Redis Course contents page.