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.
The shortcut
To predict any counter reply, keep a running total in your head: start at the current value (0 if missing), apply each command in order, and the reply is the new total.
Start
coins:ravidoes not exist, so the running total is 0.
The trap is doing the maths in your app: GET, add, SET. It looks the same in a test with one user and silently loses counts under real traffic.
Drills
Answer fast — trust the rule.
games:tom does not exist. What does INCR games:tom reply?
coins:meera holds "40". What does DECRBY coins:meera 15 reply?
word:today holds "planet". What does INCR word:today reply?
Two servers send INCR wordcraft:visits at the same moment while it holds "99". What replies do they get?
Remember
- INCR adds one inside Redis; a missing key starts at zero.
- Keep a running total: current value, apply each command, reply is the new total.
- Never GET-add-SET a counter in your app; let INCR do it atomically.
