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:

RPUSH key (some value) INCR key RPOP (some value)

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

Scenario 1: Nonexistent key
redis&gt; MULTI OK redis&gt; RPUSH mykey 1 QUEUED redis&gt; INCR mykey QUEUED redis&gt; RPOP mykey QUEUED redis&gt; EXEC 1) (integer) 1 2) (error) ERR Operation against a key holding the wrong kind of value 3) &quot;1&quot; Outcome: error. Key is still absent because RPOPing the last element out of a list nullifies it.

Scenario 2: Key is an integer
redis&gt; SET mykey 1 OK redis&gt; MULTI OK redis&gt; RPUSH mykey 1 QUEUED redis&gt; INCR mykey QUEUED redis&gt; RPOP mykey QUEUED redis&gt; EXEC 1) (error) ERR Operation against a key holding the wrong kind of value 2) (integer) 2 3) (error) ERR Operation against a key holding the wrong kind of value Outcome: key incremented.

Scenario 3: Key is a list
redis&gt; del mykey (integer) 1 redis&gt; RPUSH mykey 1 (integer) 1 redis&gt; RPUSH mykey 2 (integer) 2 redis&gt; RPUSH mykey 3 (integer) 3 redis&gt; LRANGE mykey 0 inf 1) &quot;1&quot; redis&gt; LRANGE mykey 0 -1 1) &quot;1&quot; 2) &quot;2&quot; 3) &quot;3&quot; redis&gt; MULTI OK redis&gt; RPUSH mykey 1 QUEUED redis&gt; INCR mykey QUEUED redis&gt; RPOP mykey QUEUED redis&gt; EXEC 1) (integer) 4 2) (error) ERR Operation against a key holding the wrong kind of value 3) &quot;1&quot; redis&gt; LRANGE mykey 0 -1 1) &quot;1&quot; 2) &quot;2&quot; 3) &quot;3&quot; Outcome: error. Key is unmodified, because RPUSH and RPOP are each other’s inverse.

Scenario 4: Key is some other type
redis&gt; HMSET mykey year 2012 OK redis&gt; MULTI OK redis&gt; RPUSH mykey 1 QUEUED redis&gt; INCR mykey QUEUED redis&gt; RPOP mykey QUEUED redis&gt; EXEC 1) (error) ERR Operation against a key holding the wrong kind of value 2) (error) ERR Operation against a key holding the wrong kind of value 3) (error) ERR Operation against a key holding the wrong kind of value Outcome: error.