Code Reference

Expiry & TTL

Redis · Reference cheat sheet

Expiry & TTL

Redis · Reference cheat sheet


📋 Overview

Keys can expire automatically. TTL powers caches, sessions, and ephemeral locks. Expiry is per key (not per hash field).

🔧 Core concepts

CommandRole
EXPIRE key secondsSet TTL
PEXPIRETTL in ms
TTL / PTTLRemaining time (-1 no expire, -2 missing)
PERSISTRemove expiry
SET … EXSet value + TTL atomically
EXPIREATExpire at unix time
Eviction (when maxmemory)Examples
volatile-lruEvict expiring keys LRU
allkeys-lruEvict any key LRU
noevictionErrors on write when full

💡 Examples

Session TTL:

SET sess:abc123 '{"userId":42}' EX 1800
TTL sess:abc123

Refresh TTL:

EXPIRE sess:abc123 1800

Lock with auto-expiry:

SET lock:migrate 1 NX EX 60

⚠️ Pitfalls

  • Expired keys may still appear briefly until lazy/active expiration removes them.
  • Writing a key with SET without TTL removes any previous expiry unless using keep-ttl options.
  • Relying on TTL for correctness without handling miss paths causes subtle bugs.

On this page