INCR
Introduction
In Dragonfly, as well as in Redis and Valkey, the INCR command is used to atomically increment the integer value of a key by one.
This is helpful for implementing counters, tracking requests, or managing sequence numbers since it is thread-safe and operates in constant time O(1).
Syntax
INCR key
- Time complexity: O(1)
- ACL categories: @write, @string, @fast
Parameter Explanations
key: The key whose value will be incremented by one. If the key doesn't exist, it will be automatically created with a value of0before being incremented.
Return Values
Returns the new value of the key after the increment as an integer.
Code Examples
Basic Example
Increment an integer stored in a key:
dragonfly$> SET mykey 10
OK
dragonfly$> INCR mykey
(integer) 11
Automatically Creating and Incrementing a Key
If the key does not exist, INCR will set it to 0 before incrementing it:
dragonfly$> EXISTS counter
(integer) 0
dragonfly$> INCR counter
(integer) 1
Using INCR with Negative Numbers
INCR can handle negative numbers too.
It will still increase the value by one in this case:
dragonfly$> SET mykey -5
OK
dragonfly$> INCR mykey
(integer) -4
Incrementing in a Loop
You can repeatedly call INCR to track a counter of operations:
dragonfly$> SET request_count 100
OK
dragonfly$> INCR request_count
(integer) 101
dragonfly$> INCR request_count
(integer) 102
Best Practices
- Use
INCRto implement performance-efficient counters due to its atomic nature. - Consider using the
EXPIREcommand alongside to set TTLs for temporary counters, such as tracking hits in a web application. - If you need to increment a value by something other than
1, use the closely relatedINCRBYcommand, which allows you to specify the increment amount.