0
0
Redisquery~5 mins

Atomic operations with Lua in Redis

Choose your learning style9 modes available
Introduction

Atomic operations make sure a set of commands run all together without interruption. This keeps data safe and correct.

When you want to update multiple keys in Redis at the same time without other commands interfering.
When you need to check a value and change it only if it meets a condition, all in one step.
When you want to do complex logic that Redis commands alone can't handle safely.
When you want to avoid race conditions in a busy system where many clients change data.
When you want to keep your data consistent during multiple related changes.
Syntax
Redis
EVAL script numkeys key [key ...] arg [arg ...]

EVAL runs a Lua script atomically in Redis.

numkeys tells Redis how many keys the script will use.

Examples
Sets the key mykey to myvalue atomically.
Redis
EVAL "return redis.call('set', KEYS[1], ARGV[1])" 1 mykey myvalue
Deletes mykey only if its value matches expectedvalue.
Redis
EVAL "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end" 1 mykey expectedvalue
Sample Program

This script checks if the key counter exists. If not, it sets it to 10. Otherwise, it returns the current value. All happens atomically.

Redis
EVAL "local current = redis.call('get', KEYS[1]) if not current then redis.call('set', KEYS[1], ARGV[1]) return ARGV[1] else return current end" 1 counter 10
OutputSuccess
Important Notes

Lua scripts in Redis run atomically, so no other commands run in the middle.

Use KEYS array for keys and ARGV array for other arguments inside the Lua script.

Keep scripts short and simple for better performance.

Summary

Atomic operations with Lua keep multiple Redis commands safe and consistent.

Use EVAL to run Lua scripts atomically.

Lua scripts can read and write keys and use arguments for flexible logic.