TExcelTAD
Home › Redis › Redis Transactions

Redis Transactions

A single Redis command is always atomic. A transaction extends that guarantee to a group of commands: they run one after another with no other client's commands in between. Redis transactions use four commands: MULTI, EXEC, DISCARD and WATCH.

MULTI and EXEC

MULTI starts a transaction. Every following command is not executed but queued, and Redis answers QUEUED. EXEC then runs the whole queue at once and returns an array with one reply per command.

redis · try it yourself
SET account:ada 100
SET account:linus 20
MULTI
DECRBY account:ada 30
INCRBY account:linus 30
EXEC
MGET account:ada account:linus
redis> SET account:ada 100
OK
redis> SET account:linus 20
OK
redis> MULTI
OK
redis> DECRBY account:ada 30
QUEUED
redis> INCRBY account:linus 30
QUEUED
redis> EXEC
1) (integer) 70
2) (integer) 50
redis> MGET account:ada account:linus
1) "70"
2) "50"

No other client can observe the moment where Ada's account was already debited but Linus's was not yet credited. Either both commands run, or (if the connection drops before EXEC) neither does.

DISCARD

DISCARD throws the queue away and leaves transaction mode:

redis · try it yourself
SET stock 5
MULTI
DECR stock
DECR stock
DISCARD
GET stock
redis> SET stock 5
OK
redis> MULTI
OK
redis> DECR stock
QUEUED
redis> DECR stock
QUEUED
redis> DISCARD
OK
redis> GET stock
"5"

Errors inside a transaction

There are two kinds of errors, and Redis handles them very differently.

1. Errors while queuing (unknown command, wrong number of arguments): Redis remembers the problem and refuses the whole transaction at EXEC:

redis · try it yourself
SET counter 1
MULTI
INCR counter
INCRBY counter
EXEC
GET counter
redis> SET counter 1
OK
redis> MULTI
OK
redis> INCR counter
QUEUED
redis> INCRBY counter
(error) ERR wrong number of arguments for 'incrby' command
redis> EXEC
(error) EXECABORT Transaction discarded because of previous errors.
redis> GET counter
"1"

2. Errors while executing (for example a command against the wrong type): the failing command returns an error, but the others still run. Redis does not roll back:

redis · try it yourself
SET name Ada
SET visits 10
MULTI
INCR visits
INCR name
INCR visits
EXEC
GET visits
redis> SET name Ada
OK
redis> SET visits 10
OK
redis> MULTI
OK
redis> INCR visits
QUEUED
redis> INCR name
QUEUED
redis> INCR visits
QUEUED
redis> EXEC
1) (integer) 11
2) (error) ERR value is not an integer or out of range
3) (integer) 12
redis> GET visits
"12"

The second command failed, yet visits was incremented twice. Redis skips rollback on purpose: such errors are programming mistakes (wrong type, wrong key) that should be caught during development, and leaving out rollback keeps transactions simple and fast.

Note: If you come from SQL, this is the biggest difference: a Redis transaction guarantees isolation (nothing interleaves) but not rollback.

Optimistic locking with WATCH

Commands inside MULTI cannot read values and decide what to do next: you only get the results after EXEC. To implement "read a value, compute, write back" safely, Redis offers optimistic locking:

  1. WATCH key marks keys to observe.
  2. Read the values you need (normal commands, not queued).
  3. MULTI, queue the writes, EXEC.
  4. If any watched key was modified between WATCH and EXEC, EXEC does nothing and returns (nil). Your program then retries from step 1.

In this first example nothing interferes, so the transaction succeeds:

redis · try it yourself
SET seats:flight42 3
WATCH seats:flight42
GET seats:flight42
MULTI
DECR seats:flight42
RPUSH bookings:flight42 ada
EXEC
GET seats:flight42
redis> SET seats:flight42 3
OK
redis> WATCH seats:flight42
OK
redis> GET seats:flight42
"3"
redis> MULTI
OK
redis> DECR seats:flight42
QUEUED
redis> RPUSH bookings:flight42 ada
QUEUED
redis> EXEC
1) (integer) 2
2) (integer) 1
redis> GET seats:flight42
"2"

Now we simulate a second client that changes the key after our WATCH. In real life that SET would come from another connection; any modification counts, even one from the same connection:

redis · try it yourself
SET seats:flight42 3
WATCH seats:flight42
GET seats:flight42
SET seats:flight42 0
MULTI
DECR seats:flight42
RPUSH bookings:flight42 ada
EXEC
GET seats:flight42
LLEN bookings:flight42
redis> SET seats:flight42 3
OK
redis> WATCH seats:flight42
OK
redis> GET seats:flight42
"3"
redis> SET seats:flight42 0
OK
redis> MULTI
OK
redis> DECR seats:flight42
QUEUED
redis> RPUSH bookings:flight42 ada
QUEUED
redis> EXEC
(nil)
redis> GET seats:flight42
"0"
redis> LLEN bookings:flight42
(integer) 0

EXEC returned (nil): the transaction was aborted, so we did not oversell a flight that had just sold out. After EXEC (successful or not) all keys are unwatched automatically; UNWATCH does it by hand.

The retry loop in application code

Client libraries wrap WATCH in a helper. In redis-py it looks like this:

python
import redis

r = redis.Redis(decode_responses=True)

def book_seat(flight, user):
    key = f"seats:{flight}"
    with r.pipeline() as pipe:
        while True:
            try:
                pipe.watch(key)                 # 1. watch
                seats = int(pipe.get(key) or 0) # 2. read (runs immediately)
                if seats <= 0:
                    pipe.unwatch()
                    return False
                pipe.multi()                    # 3. queue the writes
                pipe.decr(key)
                pipe.rpush(f"bookings:{flight}", user)
                pipe.execute()                  #    EXEC
                return True
            except redis.WatchError:            # 4. someone changed the key: retry
                continue

When to use what

Need Tool
One atomic change a single command (INCR, LMOVE, SET NX ...)
Several writes that must not interleave MULTI / EXEC
Read, decide, then write WATCH + MULTI / EXEC, or a Lua script
Complex logic with many reads and writes a Lua script (next lesson): simpler and no retries

Test yourself

What does Redis reply to a command sent after MULTI?

  1. Its normal result
  2. QUEUED
  3. OK
  4. (nil)

Inside a transaction, the second of three commands fails at run time with WRONGTYPE. What happens?

  1. All three are rolled back
  2. Only the first runs
  3. The first and third run; the second returns an error
  4. EXEC returns (nil)

What does EXEC return when a WATCHed key was modified after WATCH?

  1. An error
  2. (nil), and no queued command runs
  3. The results of the commands
  4. QUEUED