PERSIST to remove expiry in Redis - Time & Space Complexity
We want to understand how long it takes to remove the expiration from a key in Redis using the PERSIST command.
How does the time needed change as the database grows?
Analyze the time complexity of the following Redis command.
PERSIST mykey
This command removes the expiration time from the key named "mykey", making it persistent.
Look for any repeated steps or loops inside the command.
- Primary operation: Checking if the key has an expiration and removing it.
- How many times: This happens once per command call, no loops or repeated scans.
The time to remove expiration does not depend on the number of keys or database size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The operation takes about the same time no matter how many keys exist.
Time Complexity: O(1)
This means removing the expiration from a key takes a constant amount of time regardless of database size.
[X] Wrong: "Removing expiration takes longer if the database has many keys."
[OK] Correct: The PERSIST command works directly on the specified key without scanning others, so its time does not grow with database size.
Understanding that some Redis commands run in constant time helps you reason about performance and choose the right commands for your needs.
"What if we used EXPIRE to set a new expiration instead of PERSIST? How would the time complexity compare?"