Skip to content
Redis

Keys & Expiration

Set TTL, scan keys, and inspect the keyspace.

By EZ4Code Team
ttlexpirationscan

Code

# Set TTL on existing keys
EXPIRE session:abc 3600       # seconds
EXPIREAT cache:hot 1700000000 # unix timestamp
PEXPIRE token:xyz 60000       # milliseconds
TTL session:abc
PTTL session:abc

# Set + TTL atomically
SET token:xyz "data" EX 60

# Persist (remove TTL)
PERSIST session:abc

# Inspect the keyspace
KEYS user:*       # avoid in production
SCAN 0 MATCH user:* COUNT 100
TYPE user:1
OBJECT IDLETIME user:1
RANDOMKEY
DBSIZE

Explanation

EXPIRE sets a TTL on a key after which Redis removes it automatically; SET with EX is the atomic way to set value and TTL together. KEYS blocks the server on large keyspaces, so prefer SCAN for production iteration. OBJECT IDLETIME helps find rarely-accessed cache entries to evict.

More Redis Snippets