How to Implement Real Time Counter with Redis
Use Redis'
INCR command to implement a real time counter that increments a key atomically. This command increases the stored number by one each time it is called, making it perfect for counting events in real time.Syntax
The INCR command increases the integer value of a key by one. If the key does not exist, it is set to 0 before incrementing.
INCR key: Increments the value stored atkeyby 1.- If the key contains a value that is not an integer, Redis returns an error.
- The operation is atomic, so it is safe for concurrent increments.
redis
INCR counter_key
Example
This example shows how to create and increment a real time counter named page_views. Each call to INCR page_views increases the count by one.
redis
127.0.0.1:6379> INCR page_views (integer) 1 127.0.0.1:6379> INCR page_views (integer) 2 127.0.0.1:6379> INCR page_views (integer) 3
Output
(integer) 1
(integer) 2
(integer) 3
Common Pitfalls
Common mistakes when implementing a real time counter in Redis include:
- Trying to increment a key that holds a non-integer value, which causes an error.
- Not initializing the key properly if you expect a starting value other than zero.
- Using
INCRBYFLOATwhen only integer increments are needed, which can complicate counting.
Always ensure the key is used only for integer counting to avoid errors.
redis
127.0.0.1:6379> SET page_views "hello" OK 127.0.0.1:6379> INCR page_views (error) ERR value is not an integer or out of range # Correct usage: 127.0.0.1:6379> DEL page_views (integer) 1 127.0.0.1:6379> INCR page_views (integer) 1
Output
(error) ERR value is not an integer or out of range
(integer) 1
Quick Reference
| Command | Description |
|---|---|
| INCR key | Increment integer value of key by 1 atomically |
| INCRBY key increment | Increment integer value of key by specified increment |
| DEL key | Delete the key to reset the counter |
| GET key | Retrieve the current value of the counter |
Key Takeaways
Use Redis INCR command for atomic, real time increments of counters.
Ensure the key stores an integer to avoid errors when incrementing.
Initialize or reset counters with DEL if needed before incrementing.
INCRBY allows increments by numbers other than one if required.
Redis counters are fast and safe for concurrent access in real time.