Video in progress

Strong Junior ⚡ Redis and caching

Does a MULTI/EXEC transaction in Redis roll back when something fails?

No. MULTI/EXEC runs the commands one after another with no other client interleaving, but if one of them fails at runtime, the rest still run and the earlier ones are not undone.

📖 Answer

MULTI
SET a 1
LPUSH a x        # a is a String, this gives a WRONGTYPE error
SET b 2
EXEC
1) OK
2) (error) WRONGTYPE ...
3) OK            # b was written, and a stays changed

Only a syntax error (an unknown command inside MULTI) makes EXEC reject the whole block.

There's another difference from a SQL transaction: a value you read inside MULTI can't be used in the next command, because all replies only arrive after EXEC. For "read, check, write" there are two ways:

  • WATCH key: if another client changes the key before EXEC, the transaction is aborted and you retry (optimistic locking);
  • a Lua script (EVAL): the whole logic runs atomically on the server, and it's often simpler.

In Spring, you call multi()/exec() inside redisTemplate.execute(SessionCallback) so that the individual calls don't end up on different connections.