Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 42 ยท Working with Redis

Transactions: MULTI, EXEC and WATCH

Learn Redis transactions: MULTI, EXEC and DISCARD, why there is no rollback, how queue errors differ from run errors, and WATCH check-and-set locking.

Every single Redis command is atomic, but real tasks often need several commands to happen together: move money between two balances, decrement stock and record an order, update a record and its index. If another client slips a command between your steps, it can see a half-finished state. A transaction is Redis's answer: you queue a group of commands, and the server then runs them back to back, with no other client's commands in between.

Redis transactions are simpler than the ones in a SQL database, and different in one important way: they have no rollback. This lesson explains exactly what they do guarantee, what they do not, and how WATCH adds optimistic locking so you can do safe read-then-write logic.

The runnable examples use a JavaScript emulator that follows the real rules for these commands. Real redis-cli transcripts are read-only blocks.

MULTI, EXEC and DISCARD

MULTI starts a transaction. After it, each command you send is not run: the server answers QUEUED and stores it. EXEC then runs the whole queue in order and replies with an array holding one result per command. DISCARD throws the queue away instead.

TEXT
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> SET balance:alice 100
QUEUED
127.0.0.1:6379(TX)> INCRBY balance:alice -30
QUEUED
127.0.0.1:6379(TX)> INCRBY balance:bob 30
QUEUED
127.0.0.1:6379(TX)> EXEC
1) OK
2) (integer) 70
3) (integer) 30

While the queue executes, no other client's command is processed. That is the isolation guarantee, and it comes for free from Redis running one command at a time (see What Is Redis?). Other clients see the state before the transaction or the state after it, never something in between.

The life of a transaction

MULTI Start queuing.
Commands Each reply is QUEUED.
EXEC Run the queue in one uninterrupted block.
DISCARD Or drop the queue instead.

Nothing executes until EXEC.

1 / 2

No rollback

In a SQL database a failed statement can roll the whole transaction back. Redis does not do that. Once EXEC starts, every queued command runs, even if one of them fails. A command that fails at that moment (for example INCR on a value that is not a number) puts an error in its slot of the reply array, and the other commands still take effect.

The design is deliberate. Errors that happen at run time are almost always programming mistakes, such as using the wrong type for a key, and the Redis authors chose not to complicate the server and slow it down with rollback machinery for bugs that should be caught in development. The practical rule is: test your transactions, and check every item of the reply.

There are two different kinds of error, and they behave differently:

  • Errors while queuing (unknown command, wrong number of arguments, out of memory). The server flags the transaction, and the later EXEC is refused with EXECABORT, so none of the commands run.
  • Errors while executing (wrong type for the key, non-integer value). The rest of the queue still runs, and the error appears in the reply array.

Run both cases here. The emulator keeps one queue per client, supports SET, GET, INCR, INCRBY, LPUSH and DEL, and prints replies in redis-cli style.

JS MULTI/EXEC, DISCARD and the two kinds of error

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the third scenario, INCR title fails because hello is not a number, yet both INCR visits commands run, and visits ends at 2. In the fourth, one bad command at queue time makes EXEC refuse everything, and clicks was never created. Real Redis behaves this way (versions since 2.6.5 abort a transaction that had a queuing error).

A related detail: commands such as SET are not "undone" by a later failure, so if you need all-or-nothing semantics for logic that can fail, validate first (using WATCH, below, or a Lua script) and then queue only commands that cannot fail.

The problem: read, decide, write

A transaction is a fixed list of commands. You cannot read a value in the middle of it and branch on it, because replies only arrive at EXEC. That is a problem for patterns like "withdraw 30 only if the balance is at least 30": you must GET the balance first, decide in your application, and then write. Between your GET and your EXEC, another client may have changed the balance.

WATCH solves exactly this. It marks keys to monitor. If any watched key is modified by another client before your EXEC, the EXEC does nothing and returns a null reply, and you retry. This is optimistic locking, also called check-and-set (CAS): nobody is blocked, and conflicts are rare enough that retrying is cheap.

TEXT
WATCH balance:alice
GET balance:alice            # you read 100 and decide to withdraw 30
MULTI
SET balance:alice 70
EXEC                         # returns the array of replies, or (nil) if balance:alice changed

Rules to remember:

  • WATCH must come before the GET you base your decision on, and before MULTI.
  • A conflict makes EXEC return nil, and the whole queue is skipped. The only correct response is to start again from WATCH.
  • EXEC, DISCARD and UNWATCH all forget the watched keys. A connection that closes also forgets them.
  • Any write counts as a modification, including DEL and writes from your own connection between WATCH and EXEC. (In modern versions a watched key that merely reaches its expiry time does not abort the transaction.)

Never put the WATCH/GET step on a pooled connection that other code may use between your commands. Keep one dedicated connection for the whole check-and-set cycle (see Using Redis from code).

Check-and-set with conflicts

The example below adds WATCH to the emulator by giving every key a version number that increases on each write. At WATCH time the client remembers the versions. At EXEC time it compares them. Two clients race to withdraw from the same account, and a helper retries after a conflict, the way a real application would.

JS WATCH: optimistic check-and-set with a retry

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first part shows the lost update that WATCH prevents: without it, Bob's write would have overwritten Alice's and the account would hold 70 instead of 40. The second part shows the pattern you will actually write: loop, WATCH, read, decide, MULTI, write, EXEC, and repeat when EXEC returns nil. The emulator models the version check, not the network.

When to choose something else

WATCH shines when conflicts are rare. If many clients fight over one hot key, most attempts fail and the retries pile up. Two alternatives are often better:

  • A single atomic command, when one exists. INCRBY and HINCRBY need no transaction at all. SET key value NX is a one-command check-and-set for "create if absent".
  • A Lua script or Redis Function, which can read, decide and write in one atomic step on the server, with no round trips and no retries (see Lua Scripting and Functions).

Also remember that in Redis Cluster all keys of one transaction must live in the same hash slot, and that Redis transactions do not provide durability on their own: after EXEC the data is as durable as your persistence settings make it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to commands sent between MULTI and EXEC?

    After MULTI the server queues commands and replies QUEUED. Nothing executes until EXEC.
  2. 2. A transaction contains INCR visits, INCR title (title holds the text hello) and INCR visits again. What does EXEC do?

    Redis has no rollback. A command that fails at run time reports its own error while the other commands still execute.
  3. 3. You send a command with the wrong number of arguments after MULTI. What does a later EXEC return?

    Errors detected while queuing flag the transaction, and EXEC refuses to run it (EXECABORT).
  4. 4. EXEC returns nil after you used WATCH. What should your code do?

    nil means a watched key changed and the whole queue was skipped. The decision was based on stale data, so repeat the read-decide-write cycle.
  5. 5. When is a Lua script usually a better fit than WATCH?

    A script does read, decide and write atomically on the server without retries, which handles hot keys better than optimistic locking.

Summary

  • MULTI queues commands (each reply is QUEUED), EXEC runs them back to back with no other client in between, and DISCARD drops the queue.
  • There is no rollback: a command that fails at run time reports an error in its slot while the others still run, so check every reply item.
  • An error detected while queuing makes EXEC abort with EXECABORT and run nothing.
  • WATCH implements optimistic locking: if a watched key changes before EXEC, EXEC returns nil and you retry the whole read-decide-write cycle.
  • Prefer a single atomic command, or a Lua script, when contention is high; in Cluster all keys of a transaction must share a hash slot.

Next, see how to send many commands efficiently and broadcast messages in Pipelining and Pub/Sub.