Counters
Integers stored as strings
Section titled “Integers stored as strings”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 and DECR
Section titled “INCR and DECR”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 0OK127.0.0.1:6379> INCR pageviews:home(integer) 1127.0.0.1:6379> INCR pageviews:home(integer) 2127.0.0.1:6379> INCR pageviews:home(integer) 3127.0.0.1:6379> DECR pageviews:home(integer) 2SET pageviews:home 0
INCR pageviews:home
INCR pageviews:home
INCR pageviews:home
DECR pageviews:homeINCRBY and DECRBY
Section titled “INCRBY and DECRBY”When you need to add or subtract values other than 1, use INCRBY and DECRBY:
127.0.0.1:6379> SET score:player1 100OK127.0.0.1:6379> INCRBY score:player1 50(integer) 150127.0.0.1:6379> DECRBY score:player1 30(integer) 120127.0.0.1:6379> INCRBY score:player1 -10(integer) 110SET score:player1 100
INCRBY score:player1 50
DECRBY score:player1 30
INCRBY score:player1 -10INCRBYFLOAT
Section titled “INCRBYFLOAT”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.5OK127.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 temperatureReal-world pattern: page-view counter
Section titled “Real-world pattern: page-view counter”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) 1127.0.0.1:6379> INCR views:article:42(integer) 2127.0.0.1:6379> INCR views:article:42(integer) 3127.0.0.1:6379> GET views:article:42"3"INCR views:article:42
INCR views:article:42
INCR views:article:42
GET views:article:42Real-world pattern: rate limiter
Section titled “Real-world pattern: rate limiter”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) 1127.0.0.1:6379> EXPIRE ratelimit:ip:203.0.113.5 60(integer) 1127.0.0.1:6379> INCR ratelimit:ip:203.0.113.5(integer) 2127.0.0.1:6379> TTL ratelimit:ip:203.0.113.5(integer) 57In 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