SET with expiry (EX, PX) in Redis - Time & Space Complexity
We want to understand how the time it takes to run a Redis SET command with an expiry changes as we add more data.
Specifically, we ask: does setting a key with expiration take longer when the database grows?
Analyze the time complexity of the following Redis commands.
SET mykey "Hello" EX 10
SET anotherkey "World" PX 5000
These commands set keys with expiration times in seconds (EX) and milliseconds (PX).
Look for any repeated work inside the command execution.
- Primary operation: Storing the key and value, and scheduling the expiration.
- How many times: Each command runs once per key set; no loops or repeated traversals inside the command.
The time to set a key with expiry stays about the same no matter how many keys are in the database.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Constant time to set and schedule expiry |
| 100 | Still constant time per command |
| 1000 | Still constant time per command |
Pattern observation: The work does not grow with the number of keys; it stays steady.
Time Complexity: O(1)
This means setting a key with an expiry takes the same amount of time regardless of how many keys are stored.
[X] Wrong: "Setting a key with expiry takes longer as the database grows because Redis must check all keys for expiration."
[OK] Correct: Redis handles expirations efficiently using internal data structures, so setting a key with expiry is a quick, direct operation.
Knowing that setting keys with expiry is fast and does not slow down as data grows helps you design efficient caching and session systems.
"What if we used a command that scans all keys to set expiry instead? How would the time complexity change?"