INCR and DECR
Every time someone opens Wordcraft, a counter should go up by one. Twenty web servers handle those visits at the same moment. If each server reads the number, adds one and writes it back, visits get lost. Redis has a command that makes the whole problem disappear.
The rule
INCR adds one inside Redis; a missing key starts at zero.
INCR treats a string value as a whole number, adds one and replies with the new value. DECR subtracts one. INCRBY and DECRBY change the number by any whole amount.
127.0.0.1:6379> INCR wordcraft:visits
(integer) 1
127.0.0.1:6379> INCR wordcraft:visits
(integer) 2
127.0.0.1:6379> INCRBY wordcraft:visits 10
(integer) 12
127.0.0.1:6379> DECR wordcraft:visits
(integer) 11
127.0.0.1:6379> GET wordcraft:visits
"11"Three details matter:
- Missing key = 0. The first
INCRcreated the key and replied1. ADECRon a missing key replies-1. - It is still a string.
GETshows"11"in quotes; Redis stores the digits and does the maths when asked. - Only whole numbers. If the value is
"hello"or"3.5",INCRreplies(error) ERR value is not an integer or out of range. (For decimals there isINCRBYFLOAT.)
Why it is safe. Redis runs commands one at a time, so no other command can sneak in between reading the old number and writing the new one. That is what "atomic" means: the command happens entirely or not at all, never half-way. Two servers sending INCR at the same instant get 12 and 13, never 12 twice.