Advertisement
Beginner Redis, Expiration & Eviction

How do you set an expiration time on a Redis key so it automatically gets deleted after a certain period?

Short answer

You can set an expiration time when creating a key using SET with the EX option for seconds or PX for milliseconds, or apply it to an already existing key using the EXPIRE command, after which Redis automatically removes the key once that time has passed without needing any…

Save Redis mock interview
Advertisement
AModel answer
You can set an expiration time when creating a key using SET with the EX option for seconds or PX for milliseconds, or apply it to an already existing key using the EXPIRE command, after which Redis automatically removes the key once that time has passed without needing any manual cleanup.
Example

SET session:abc123 'userdata' EX 3600 EXPIRE session:abc123 3600

Real-world example
A web application stores a user's login session in Redis with a one hour expiration, automatically logging them out and cleaning up the session data without needing a separate scheduled cleanup process.
Likely follow-ups
  • What happens if you set a new value on a key that already had an expiration set?
  • How do you check how much time is left before a key expires?
Related topics