Redis › Expiration & Eviction
How do you set an expiration time on a Redis key so it automatically gets deleted after a certain period?
BeginnerAnswer
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.
SET session:abc123 'userdata' EX 3600
EXPIRE session:abc123 3600Real-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.