What is the use of using MULTI and EXEC in one client if the other client can still edit the key?
Redis-cli 1:
multi
set name ABC
Redis-cli 2:
set name XYZ
Redis-cli 1:
exec
The final value of name becomes ABC
So what was the point of using multi in redis-cli 1 when redis-cli 2 could still change while transaction in redis-cli 1 is still going on?
2
Answers
In this case, i.e. running single command with multi-exec, you cannot get any benefit. Even worse, multi-exec hurts performance, since you need to send 3 commands to Redis.
Multi-exec is used to run several commands in a transaction, although commands from other clients might mix with multi-exec commands.
Redis won’t run commands from client 1 until it receives
exec
. So Redis runs these command with the following order:MULTI
solves two problems.First, it allows you to execute things atomically. You can queue up several commands and then they run all at once:
This will set
foo
andbaz
at the point thatEXEC
is called. If something else changesfoo
orbaz
while the commands are being queued but beforeEXEC
is called, then these changes will be overridden.Note that to do this, the keys need to be on the same shard. If you are running in a clustered environment there are additional considerations. But that’s another, and somewhat bigger topic.
The other use for
MULTI
is for optimistic locking using theWATCH
commands. You can watch a field and if someone else changes is during the transaction, the transaction will fail.This will set
foo
at the point thatEXEC
is called. If something else changesfoo
while the commands are being queued but beforeEXEC
is called, then the queued commands will not be executed andEXEC
will return(nil)
.