0
0
Redisquery~5 mins

SET with expiry (EX, PX) in Redis

Choose your learning style9 modes available
Introduction
We use SET with expiry to store data that should disappear automatically after some time. This helps keep the database clean and saves space.
Storing a temporary login token that expires after 10 minutes.
Caching a webpage snapshot that should refresh every hour.
Saving a one-time password (OTP) that is valid for 5 minutes.
Keeping track of a user's session that ends after inactivity.
Limiting how long a message stays visible in a chat app.
Syntax
Redis
SET key value [EX seconds] [PX milliseconds]
EX sets the expiry time in seconds.
PX sets the expiry time in milliseconds.
Examples
Sets 'session_token' with value 'abc123' that expires in 600 seconds (10 minutes).
Redis
SET session_token abc123 EX 600
Sets 'cache_page' with value 'snapshot' that expires in 30000 milliseconds (30 seconds).
Redis
SET cache_page snapshot PX 30000
Sets 'temp_key' with value 'temp_value' without expiry (it stays until deleted).
Redis
SET temp_key temp_value
Sample Program
This sets 'user_token' with value 'xyz789' that expires in 5 seconds. The first TTL shows how many seconds remain before expiry (e.g. 5). After more than 5 seconds, the second TTL returns -2.
Redis
SET user_token xyz789 EX 5
TTL user_token
TTL user_token
OutputSuccess
Important Notes
If you set both EX and PX, the last one will be used.
TTL command returns -2 if the key does not exist or has expired.
Expiry time starts counting down immediately after SET.
Summary
SET with EX or PX lets you store data that disappears automatically.
Use EX for seconds and PX for milliseconds expiry times.
This helps manage temporary data like sessions or caches easily.