skip to Main Content

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


  1. 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.

    client 1: multi
    client 1: set key value
    client 2: set key new-value
    client 1: set key2 another-value
    client 1: exec
    

    Redis won’t run commands from client 1 until it receives exec. So Redis runs these command with the following order:

    1. Redis receives MULTI command from client 1, and begin to queue commands from client 1
    2. Redis runs command from client 2, i.e. set key new-value
    3. Redis receives EXEC command, and runs all command between MULTI and EXEC from client 1.
    Login or Signup to reply.
  2. 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:

    127.0.0.1:6379> MULTI
    OK
    127.0.0.1:6379(TX)> SET foo bar
    QUEUED
    127.0.0.1:6379(TX)> SET baz qux
    QUEUED
    127.0.0.1:6379(TX)> EXEC
    1) OK
    2) OK
    

    This will set foo and baz at the point that EXEC is called. If something else changes foo or baz while the commands are being queued but before EXEC 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 the WATCH commands. You can watch a field and if someone else changes is during the transaction, the transaction will fail.

    127.0.0.1:6379> WATCH foo
    OK
    127.0.0.1:6379> MULTI
    OK
    127.0.0.1:6379(TX)> SET foo bar
    QUEUED
    127.0.0.1:6379(TX)> EXEC
    (nil)
    

    This will set foo at the point that EXEC is called. If something else changes foo while the commands are being queued but before EXEC is called, then the queued commands will not be executed and EXEC will return (nil).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search