Persistence and performance trade-off in Redis - Time & Space Complexity
When Redis saves data to disk, it can slow down because writing takes time.
We want to see how this saving affects how long commands take as data grows.
Analyze the time complexity of this Redis persistence example.
SET key value
SAVE
GET key
This code sets a value, saves all data to disk, then gets the value back.
Look for repeated or costly steps.
- Primary operation: The SAVE command writes all data to disk.
- How many times: SAVE writes every key-value pair once per call.
As data grows, saving takes longer because more data is written.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Writes 10 items to disk |
| 100 | Writes 100 items to disk |
| 1000 | Writes 1000 items to disk |
Pattern observation: The time to save grows roughly in direct proportion to data size.
Time Complexity: O(n)
This means saving data takes longer as you have more data, growing in a straight line.
[X] Wrong: "Saving data is always fast and does not depend on data size."
[OK] Correct: Saving writes all data to disk, so more data means more work and slower saving.
Understanding how saving data affects speed helps you explain trade-offs in real systems.
"What if Redis used incremental saving instead of full saving? How would the time complexity change?"