Temporary data with TTL in Redis - Time & Space Complexity
We want to understand how the time to set temporary data with expiration changes as we add more data.
How does Redis handle the time cost when we add keys that expire automatically?
Analyze the time complexity of the following Redis commands.
SET user:1000 "Alice" EX 60
SET user:1001 "Bob" EX 60
SET user:1002 "Carol" EX 60
GET user:1000
DEL user:1001
This code sets keys with a time-to-live (TTL) of 60 seconds, then reads and deletes keys.
Look for repeated actions that affect time.
- Primary operation: Setting keys with expiration (SET with EX option)
- How many times: Once per key added, each key has its own expiration timer
As you add more keys with TTL, each SET command takes about the same time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 SET commands, each quick |
| 100 | 100 SET commands, each still quick |
| 1000 | 1000 SET commands, each similar speed |
Pattern observation: Time per SET stays about the same no matter how many keys exist.
Time Complexity: O(1)
This means setting a key with TTL takes about the same time no matter how many keys are stored.
[X] Wrong: "Setting a key with expiration gets slower as more keys with TTL exist."
[OK] Correct: Redis manages expirations efficiently, so each SET with TTL runs in constant time regardless of total keys.
Knowing that setting temporary data with TTL is fast helps you design systems that rely on quick expiration without slowing down as data grows.
"What if we used a Lua script to set multiple keys with TTL in one call? How would the time complexity change?"