Search code examples
redisluatransactionsatomic

Lua Scripts vs Multi/Exec in Redis


Is there any reason to use lua scripts for atomicity in redis rather than using multi/exec style transactions?

I see some implementations specifically choose lua scripts when atomicity is needed but wouldn't it same with multi/exec as well or is it just a preference?


Solution

  • LUA is useful(and the only way) when you need to the result of one operation to use it in another. When you use MULTI/EXEC, you get results at the end of the transaction as an array. There won't be an intermediate response to use in the middle of the transaction.

    Let's say you have list, you LPOP one element and use that element name as a key to INCRBY some other other. You can't do it in MULTI/EXEC(you may use WATCH with them to fail if the watched key is modified) in a transactional way. You need to give/know all the required parameters before starting transaction. When you assign the value, then it won't be server side, but will be client side which may cause a racing condition.

    In LUA(with EVAL), you can do that assignment such as

    local elt = redis.call('LPOP', KEYS[1])
    local result = redis.call('INCRBY', elt, 2);
    
    return result 
    

    There may be some cases that "choosing" any of them can be an option, but in some you need LUA.