100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Redis

Redis Transactions: MULTI/EXEC

Understand how Redis groups commands into atomic transactions using MULTI, EXEC, DISCARD, and optimistic locking with WATCH.

Key ManagementIntermediate10 min readJul 10, 2026
Analogies

What MULTI/EXEC Actually Guarantees

A Redis transaction begins with MULTI, which puts the connection into a queuing state: every subsequent command is not executed immediately but appended to a queue, and Redis replies QUEUED to each one. Calling EXEC then runs every queued command sequentially and atomically as a single unit, with no other client's commands interleaved in between, because Redis is single-threaded for command execution. This gives you isolation (no interleaving) and atomicity of execution order, but it is important to understand this is not the same guarantee as a relational database's ACID transaction, since Redis will not roll back earlier commands in the batch if a later command fails at runtime.

🏏

Cricket analogy: MULTI/EXEC is like a captain locking in an entire bowling change and field placement plan before the umpire signals play, so the whole sequence executes as one uninterrupted passage of play with no other team's action slipping in between overs.

bash
MULTI
QUEUED
DECRBY account:alice:balance 100
QUEUED
INCRBY account:bob:balance 100
QUEUED
EXEC
1) (integer) 400
2) (integer) 600

# If a queued command has a syntax error, EXEC is aborted entirely:
MULTI
QUEUED
SET foo bar
QUEUED
NOTACOMMAND
(error) ERR unknown command 'NOTACOMMAND'
EXEC
(error) EXECABORT Transaction discarded because of previous errors.

Runtime Errors Do Not Roll Back

Redis distinguishes between two failure classes. A syntax or queuing error (an unknown command, wrong number of arguments) is caught before EXEC even runs, and Redis aborts the entire transaction with EXECABORT, executing nothing. But a runtime error, such as running INCR on a key that holds a string value, is only detected while EXEC is actually executing that specific command — Redis will still run every other queued command in the batch and simply return an error for the failing one within the results array, exactly the behavior a relational database's transaction rollback is designed to prevent.

🏏

Cricket analogy: This is like a pre-approved batting order that gets rejected entirely if a name is misspelled before the match starts (caught early, nothing happens), versus a batter getting run out mid-innings — the rest of the batting order still proceeds, it doesn't cancel the whole innings.

Never assume MULTI/EXEC gives you rollback-on-failure semantics like a SQL transaction. If command 3 of 5 in your transaction fails at runtime, commands 1, 2, 4, and 5 have already been applied and stay applied. Your application logic must be designed to tolerate partial application, or you must validate inputs before queuing commands to avoid runtime errors in the first place.

Optimistic Locking with WATCH

WATCH key marks a key for optimistic locking: if any other client modifies a watched key between your WATCH call and your EXEC call, Redis aborts your transaction automatically, EXEC returns a null reply, and none of your queued commands are applied. This gives you a classic check-and-set pattern, common for implementing things like a balance transfer that first reads a balance, checks it's sufficient, then commits the debit — all without needing a heavier server-side locking mechanism. The typical pattern is WATCH the relevant keys, read their current values with GET/HGET outside the transaction, decide what to queue based on those values, then MULTI, queue the writes, and EXEC; on a null reply from EXEC, the whole read-decide-write cycle is retried.

🏏

Cricket analogy: WATCH is like a third umpire flagging that they'll review a run-out decision only if the replay footage hasn't been altered since they started reviewing — if the footage changes mid-review, they discard the decision and ask for a fresh review from scratch.

python
import redis

r = redis.Redis()

def transfer(from_key, to_key, amount):
    with r.pipeline() as pipe:
        while True:
            try:
                pipe.watch(from_key)
                balance = int(pipe.get(from_key) or 0)
                if balance < amount:
                    pipe.unwatch()
                    raise ValueError("Insufficient balance")
                pipe.multi()
                pipe.decrby(from_key, amount)
                pipe.incrby(to_key, amount)
                pipe.execute()  # raises WatchError if from_key changed
                break
            except redis.WatchError:
                continue  # someone else modified from_key, retry

transfer("account:alice:balance", "account:bob:balance", 100)

When to Reach for Lua Scripts Instead

MULTI/EXEC queues commands client-side and sends them together, but it cannot make branching decisions based on a value read mid-transaction, since all commands are queued blindly before any of them execute. When your logic needs conditional branching (read a value, then decide which of several different commands to run based on that value, all atomically), a Lua script executed with EVAL or EVALSHA is the better tool, because the entire script runs atomically on the server with full access to intermediate results, no round trips, and no risk of another client's write landing in the middle of your decision logic the way it theoretically could between separate client-side round trips even with WATCH.

🏏

Cricket analogy: This is like the difference between a captain pre-committing a fixed bowling order regardless of how the innings unfolds (MULTI/EXEC) versus giving the on-field vice-captain full authority to adapt bowling changes in real time based on how each over actually plays out (Lua script) — the latter can react to intermediate outcomes, the former can't.

A Lua script run via EVAL is itself atomic for the same reason MULTI/EXEC is: Redis's single-threaded command execution means no other command can interleave while the script runs. This makes Lua scripting the go-to choice for atomic read-then-conditionally-write logic that's too dynamic for MULTI/EXEC's blind command queuing.

  • MULTI starts queuing commands (each replies QUEUED); EXEC runs the whole queue atomically and without interleaving from other clients.
  • Syntax/queuing errors abort the entire transaction before EXEC runs (EXECABORT); no queued command executes.
  • Runtime errors (e.g. INCR on a string) do not roll back other commands in the batch — everything else still executes.
  • WATCH implements optimistic locking: if a watched key changes before EXEC, the transaction aborts and EXEC returns null.
  • The standard pattern is WATCH, read values, decide what to queue, MULTI, queue writes, EXEC, and retry on null.
  • DISCARD cancels a queued transaction before EXEC without running any of the queued commands.
  • For logic requiring conditional branching on values read mid-transaction, a Lua script (EVAL/EVALSHA) is the correct tool, not MULTI/EXEC.

Practice what you learned

Was this page helpful?

Topics covered

#Redis#RedisStudyNotes#Database#RedisTransactionsMULTIEXEC#Transactions#MULTI#EXEC#Actually#StudyNotes#SkillVeris