Skip to content
EXPIRE & TTL — Setting Timeouts
step 1/3

Reading — step 1 of 3

Key Expiry

~1 min readKey Expiry

EXPIRE & TTL — Setting Timeouts

One of Redis's killer features: keys can automatically delete themselves after a timeout.

Commands

  • EXPIRE key seconds — set TTL. Returns :1 if key exists, :0 if not
  • TTL key — get remaining seconds. Returns -1 if no expiry, -2 if key doesn't exist
  • PERSIST key — remove expiry. Returns :1 if removed, :0 if no expiry was set

How Redis Implements Expiry

Redis stores expiry times as absolute timestamps (not countdowns). When you call EXPIRE key 60, Redis stores current_time + 60s. On access, it checks if now > expiry_time.

Simulated Clock

Since our exercises run via stdin/stdout (not real-time), we use a WAIT <ms> command to advance a simulated clock. Your program should track time internally:

SET key value     → +OK
EXPIRE key 5      → :1        (expires in 5 seconds)
TTL key           → :5
WAIT 3000         → +OK       (advance clock by 3 seconds)
TTL key           → :2
WAIT 3000         → +OK       (advance clock by 3 more seconds)
TTL key           → :-2       (key expired and was deleted)

Implementation Tips

Store expiry as: expiry_times = {key: absolute_ms_timestamp} Track current time: clock = 0, incremented by WAIT commands.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…