DEL and UNLINK for deletion in Redis - Time & Space Complexity
When deleting keys in Redis, it's important to know how the time it takes grows as you delete more keys.
We want to understand how the commands DEL and UNLINK behave as the number of keys changes.
Analyze the time complexity of these Redis commands:
DEL key1 key2 key3 ... keyN
UNLINK key1 key2 key3 ... keyN
These commands delete one or more keys from the database, but they work differently internally.
Look at what repeats when deleting multiple keys:
- Primary operation: Deleting each key one by one.
- How many times: Once for each key given to DEL or UNLINK.
As you increase the number of keys to delete, the work grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 delete actions |
| 100 | About 100 delete actions |
| 1000 | About 1000 delete actions |
Pattern observation: The time grows linearly as you add more keys to delete.
Time Complexity: O(n)
This means the time to delete keys grows directly with the number of keys you delete.
[X] Wrong: "UNLINK deletes keys instantly with no cost regardless of how many keys."
[OK] Correct: UNLINK frees memory asynchronously but still must process each key, so its time grows with the number of keys.
Understanding how deletion commands scale helps you write efficient Redis code and explain your choices clearly in real projects or interviews.
"What if we delete keys one by one in a loop instead of passing them all at once? How would the time complexity change?"