Redis/INCR

When you  a nonexistent key in Redis, it is initialized to zero and then incremented. By contrast, attempting to  a nonexistent key in memcached (version 1.2.6 or later) will result in failure. This article describes an implementation of  on top of Redis that behaves in a fashion consistent with the memcached protocol, using pipelines.

The idea is to map  to this pipeline:

The value to return to the user is the second of the three returned by.

Scenario 1: Nonexistent key
Outcome: error. Key is still absent because RPOPing the last element out of a list nullifies it.

Scenario 2: Key is an integer
Outcome: key incremented.

Scenario 3: Key is a list
Outcome: error. Key is unmodified, because RPUSH and RPOP are each other’s inverse.

Scenario 4: Key is some other type
Outcome: error.