0
0
Redisquery~10 mins

TTL-based expiry in Redis - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - TTL-based expiry
Set Key with TTL
Start Countdown Timer
Key Exists?
NoKey Expired and Deleted
Yes
Allow Access to Key
Repeat Check Until TTL Ends
This flow shows how Redis sets a key with a time-to-live (TTL), counts down, and deletes the key when TTL expires.
Execution Sample
Redis
SET user:1 "Alice" EX 5
GET user:1
(wait 6 seconds)
GET user:1
Set a key 'user:1' with value 'Alice' that expires after 5 seconds, then get it before and after expiry.
Execution Table
StepCommandActionKey StateOutput
1SET user:1 "Alice" EX 5Store key with TTL 5 secondsuser:1 = "Alice" (TTL=5s)OK
2GET user:1Check key existence and TTLuser:1 = "Alice" (TTL=4s)"Alice"
3(wait 6 seconds)TTL expires, key deleteduser:1 = <deleted>N/A
4GET user:1Key not found after expiryuser:1 = <deleted>(nil)
💡 After 5 seconds, TTL expires and Redis deletes the key automatically.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
user:1<not set>"Alice" (TTL=5s)"Alice" (TTL=4s)<deleted><deleted>
Key Moments - 2 Insights
Why does GET return "Alice" at step 2 but nil at step 4?
At step 2, the key still exists with TTL counting down (see execution_table row 2). By step 4, TTL expired and Redis deleted the key (row 3), so GET returns nil.
Does Redis delete the key exactly at TTL expiry or later?
Redis deletes the key as soon as TTL expires or shortly after during internal checks (row 3). So the key is not accessible after TTL ends.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output of GET user:1 at step 2?
A"Alice"
Bnil
CError
D"Bob"
💡 Hint
Check execution_table row 2 under Output column.
At which step does the key user:1 get deleted due to TTL expiry?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at execution_table row 3 where key state changes to .
If the TTL was set to 10 seconds instead of 5, what would be the output at step 4?
AError
Bnil
C"Alice"
D"Bob"
💡 Hint
Refer to variable_tracker and execution_table timing of TTL expiry.
Concept Snapshot
TTL-based expiry in Redis:
- Use SET key value EX seconds to set TTL
- Redis counts down TTL internally
- Key is accessible until TTL expires
- After TTL, key is deleted automatically
- GET returns nil if key expired
Full Transcript
This visual execution shows how Redis handles TTL-based expiry. First, a key 'user:1' is set with a value 'Alice' and a TTL of 5 seconds. Redis stores the key and starts counting down the TTL. When we GET the key before TTL expires, Redis returns 'Alice'. After waiting 6 seconds, the TTL expires and Redis deletes the key automatically. A subsequent GET returns nil because the key no longer exists. This demonstrates how TTL controls automatic key expiry in Redis.