EXPIRE and TTL for time-to-live in Redis - Time & Space Complexity
When using Redis commands like EXPIRE and TTL, it's important to know how their speed changes as your data grows.
We want to understand how long these commands take when you have many keys or set many expirations.
Analyze the time complexity of the following Redis commands.
SET session:user123 "data"
EXPIRE session:user123 3600
TTL session:user123
This code sets a key, assigns it a time-to-live of one hour, and then checks how much time is left before it expires.
Look for any repeated steps or loops inside these commands.
- Primary operation: Checking or setting expiration on a single key.
- How many times: Each command works on one key at a time, no loops over multiple keys.
These commands handle one key at a time, so their work does not increase with the total number of keys.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 keys | Same small number of steps per command |
| 100 keys | Still same small number of steps per command |
| 1000 keys | No increase in steps per command |
Pattern observation: The time to run EXPIRE or TTL stays about the same no matter how many keys exist.
Time Complexity: O(1)
This means setting or checking expiration takes the same short time regardless of how many keys you have.
[X] Wrong: "Checking TTL gets slower as I add more keys because Redis must look through all keys."
[OK] Correct: Redis stores expiration info efficiently, so TTL only checks one key directly without scanning others.
Knowing that EXPIRE and TTL run in constant time helps you explain how Redis handles time-based data efficiently, a useful skill in many real projects.
"What if we wanted to set expiration on many keys at once? How would that affect the time complexity?"