0
0
Redisquery~5 mins

Transactions vs Lua scripts in Redis

Choose your learning style9 modes available
Introduction

Transactions and Lua scripts help you run multiple commands together in Redis safely and efficiently.

When you want to make sure several commands run one after another without interruption.
When you need to perform complex operations that require logic or calculations inside Redis.
When you want to avoid other clients changing data while your commands run.
When you want to improve performance by sending fewer requests to Redis.
When you want to keep your data consistent during multiple related changes.
Syntax
Redis
MULTI
  command1
  command2
  ...
EXEC

Transactions start with MULTI and end with EXEC.

Lua scripts run with EVAL and can include logic like loops and conditions.

Examples
This transaction increments two counters together.
Redis
MULTI
INCR counter
INCR another_counter
EXEC
This Lua script increments the counter key and returns the new value.
Redis
EVAL "return redis.call('INCR', KEYS[1])" 1 counter
Sample Program

This transaction increments the 'visits' key twice safely.

Redis
MULTI
INCR visits
INCR visits
EXEC
OutputSuccess
Important Notes

Transactions queue commands and run them all at once with EXEC.

Lua scripts run atomically, meaning no other commands run during the script.

Lua scripts can do more complex tasks than transactions because they support logic.

Summary

Transactions group commands to run together safely.

Lua scripts run commands with logic inside Redis atomically.

Use transactions for simple grouped commands, Lua scripts for complex logic.