0
0
Redisquery~10 mins

EXPIRE and TTL for time-to-live in Redis - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - EXPIRE and TTL for time-to-live
Set Key with Value
Apply EXPIRE with seconds
Key has TTL countdown
Check TTL with TTL command
If TTL > 0
Key exists
No
TTL expired
Key deleted
This flow shows how a key is set, given a time-to-live (TTL) with EXPIRE, and how TTL counts down until the key is deleted.
Execution Sample
Redis
SET session:user123 "active"
EXPIRE session:user123 5
TTL session:user123
(wait 6 seconds)
TTL session:user123
Set a key, apply a 5-second expiration, check TTL before and after expiration.
Execution Table
StepCommandActionTTL Value (seconds)Key Exists?
1SET session:user123 "active"Key set with valueNo TTL (persistent)Yes
2EXPIRE session:user123 5TTL set to 5 seconds5Yes
3TTL session:user123 (immediately)Check TTL5Yes
4(wait 6 seconds)Time passes, TTL counts down0 (expired)No
5TTL session:user123 (after wait)Check TTL after expiration-2 (key does not exist)No
💡 Key expires after 5 seconds, TTL becomes -2 indicating key no longer exists.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 4Final
session:user123 (exists)NoYesYesNoNo
TTL (seconds)N/ANo TTL50 (expired)-2 (no key)
Key Moments - 3 Insights
Why does TTL return -2 after the key expires?
TTL returns -2 when the key does not exist anymore, as shown in step 5 of the execution_table.
Does setting EXPIRE immediately delete the key?
No, EXPIRE sets a countdown. The key remains until TTL reaches zero, as seen between steps 2 and 4.
What happens if you check TTL before setting EXPIRE?
TTL returns -1 meaning the key exists but has no expiration, similar to step 1 where no TTL is set.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the TTL value immediately after setting EXPIRE?
A-1
B0
C5
D-2
💡 Hint
Check step 2 and 3 in the execution_table for TTL values after EXPIRE command.
At which step does the key stop existing?
AStep 3
BStep 4
CStep 2
DStep 1
💡 Hint
Look at the 'Key Exists?' column in the execution_table to find when it changes to 'No'.
If you do not set EXPIRE, what TTL value will TTL command return?
A-1
B0
C-2
D5
💡 Hint
Refer to the variable_tracker and key_moments about TTL values when no expiration is set.
Concept Snapshot
EXPIRE key seconds - sets time-to-live for a key
TTL key - shows remaining seconds before expiration
TTL returns -1 if no expiration set
TTL returns -2 if key does not exist
Key is deleted automatically when TTL reaches zero
Full Transcript
This visual execution shows how Redis EXPIRE sets a time-to-live on a key. First, a key is set with SET. Then EXPIRE sets a countdown in seconds. TTL command checks how many seconds remain. When TTL reaches zero, the key is deleted. TTL returns -1 if the key has no expiration and -2 if the key does not exist. This helps manage temporary data automatically.