Skip to content

Counters

Redis stores everything as a string, but it recognises when a string is a valid integer (or float) and lets you do arithmetic on it with dedicated commands. The key insight is that these operations are atomic — Redis executes each one as a single, uninterruptible step.

INCR key increments the integer value by 1. DECR key decrements by 1. If the key does not exist, Redis treats the missing value as 0 before applying the operation.

127.0.0.1:6379> SET pageviews:home 0
OK
127.0.0.1:6379> INCR pageviews:home
(integer) 1
127.0.0.1:6379> INCR pageviews:home
(integer) 2
127.0.0.1:6379> INCR pageviews:home
(integer) 3
127.0.0.1:6379> DECR pageviews:home
(integer) 2
SET pageviews:home 0
INCR pageviews:home
INCR pageviews:home
INCR pageviews:home
DECR pageviews:home

When you need to add or subtract values other than 1, use INCRBY and DECRBY:

127.0.0.1:6379> SET score:player1 100
OK
127.0.0.1:6379> INCRBY score:player1 50
(integer) 150
127.0.0.1:6379> DECRBY score:player1 30
(integer) 120
127.0.0.1:6379> INCRBY score:player1 -10
(integer) 110
SET score:player1 100
INCRBY score:player1 50
DECRBY score:player1 30
INCRBY score:player1 -10

For floating-point arithmetic (prices, averages, sensor data), use INCRBYFLOAT. There is no DECRBYFLOAT — just pass a negative delta.

127.0.0.1:6379> SET temperature 22.5
OK
127.0.0.1:6379> INCRBYFLOAT temperature 1.3
"23.8"
127.0.0.1:6379> INCRBYFLOAT temperature -5.0
"18.8"
127.0.0.1:6379> GET temperature
"18.8"
SET temperature 22.5
INCRBYFLOAT temperature 1.3
INCRBYFLOAT temperature -5.0
GET temperature

Because INCR initialises a missing key to 0 before incrementing, you do not need a SET 0 first. Combine with EXPIRE for a rolling-window counter:

127.0.0.1:6379> INCR views:article:42
(integer) 1
127.0.0.1:6379> INCR views:article:42
(integer) 2
127.0.0.1:6379> INCR views:article:42
(integer) 3
127.0.0.1:6379> GET views:article:42
"3"
INCR views:article:42
INCR views:article:42
INCR views:article:42
GET views:article:42

Track how many requests an IP has made within a window. Use INCR plus EXPIRE set only on the first increment:

127.0.0.1:6379> INCR ratelimit:ip:203.0.113.5
(integer) 1
127.0.0.1:6379> EXPIRE ratelimit:ip:203.0.113.5 60
(integer) 1
127.0.0.1:6379> INCR ratelimit:ip:203.0.113.5
(integer) 2
127.0.0.1:6379> TTL ratelimit:ip:203.0.113.5
(integer) 57

In application code you check: if the result of INCR exceeds your limit (e.g., 100), reject the request. The key auto-deletes after 60 seconds, resetting the window.

INCR ratelimit:ip:203.0.113.5
EXPIRE ratelimit:ip:203.0.113.5 60
INCR ratelimit:ip:203.0.113.5
TTL ratelimit:ip:203.0.113.5
What value does INCR use when the key does not exist yet?
Which command increments a floating-point value?
Why is INCR safe for concurrent counters?
How do you subtract 5 using INCRBYFLOAT?