Counter pattern in Redis - Time & Space Complexity
When using Redis counters, it is important to understand how the time to update or read a counter changes as the number of operations grows.
We want to know how fast Redis handles increasing increments or reads on a counter key.
Analyze the time complexity of the following Redis commands used to increment and read a counter.
INCR page_view_count
GET page_view_count
INCRBY page_view_count 5
GET page_view_count
This code increments a counter key and reads its value multiple times.
Look at what repeats when we use the counter pattern.
- Primary operation: Incrementing the counter with INCR or INCRBY.
- How many times: Each increment is a single operation, repeated as many times as needed.
Each increment or read command takes about the same time no matter how big the counter gets.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments, 10 reads |
| 100 | 100 increments, 100 reads |
| 1000 | 1000 increments, 1000 reads |
Pattern observation: The time per operation stays constant even as the number of increments grows.
Time Complexity: O(1)
This means each increment or read takes the same small amount of time, no matter how large the counter value becomes.
[X] Wrong: "Incrementing a very large counter will take longer because the number is bigger."
[OK] Correct: Redis stores counters efficiently and updates them in constant time, so the size of the number does not slow down the operation.
Understanding that Redis counters operate in constant time helps you explain how to handle high-frequency updates efficiently in real applications.
"What if we used a sorted set to count instead of a simple counter? How would the time complexity change?"