Video in progress
When do you need a Lua script in Redis, and what does its atomicity rely on?
When you need to turn a read-check-write sequence of several commands into one atomic step. The script runs inside the server and no other command runs until it finishes. The atomicity comes from that same single thread.
📖 Answer
A typical case is letting only the owner delete a lock:
-- KEYS[1] = the lock key, ARGV[1] = the owner's token
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0
If you write this in the application as GET and then DEL, the lock can expire between the two, another client can take it, and you delete its lock.
In Spring:
private static final RedisScript<Long> UNLOCK =
RedisScript.of(new ClassPathResource("unlock.lua"), Long.class);
Long removed = redisTemplate.execute(UNLOCK, List.of(lockKey), token);
Spring sends the script with EVALSHA and falls back to EVAL if the server doesn't have it cached, so the whole text doesn't go over the network every time.
Things to watch for:
- if a script runs long, all of Redis waits. Once it exceeds
busy-reply-threshold(formerlylua-time-limit), other clients get aBUSYerror; - in a cluster, all the keys the script uses must be in one slot and passed through
KEYS; - if an error happens inside the script, writes done earlier are not rolled back.
Redis 7 introduced FUNCTION LOAD: storing scripts on the server as a named library, with replication and persistence. If many services use one script, that's more convenient.
Sign up to mark studied questions and save your progress.