Skip to the workspace
Pebellslearn by building
Strings  ›  Lesson

INCR and DECR

INCR 12 minINCR and DECR add or subtract one from a number stored as a string, treat a missing key as zero, and reply with the new value.

redis / INCR and DECR

Explore each scene at your own pace.

01 · The rule

The rule

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 INCR created the key and replied 1. A DECR on a missing key replies -1.
  • It is still a string. GET shows "11" in quotes; Redis stores the digits and does the maths when asked.
  • Only whole numbers. If the value is "hello" or "3.5", INCR replies (error) ERR value is not an integer or out of range. (For decimals there is INCRBYFLOAT.)

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.