Lua Scripts and Atomicity
| Why a pipeline isn't enough | What Lua gives you |
|---|---|
| Atomicity — another request can squeeze in between your read and your write | No interleaving is possible for the whole script |
| Data dependency — a pipeline fires all commands at once without looking at results in between, so it physically can't do "read, then decide based on what you read" | Runs server-side where the read result is right there in a variable |
Why atomicity matters — the #2 pipeline has a race
Goroutine A: ZREMRANGEBYSCORE (removes stale entries)
Goroutine B: ZREMRANGEBYSCORE (removes stale entries)
Goroutine A: ZCARD → sees 99, decides to allow
Goroutine B: ZCARD → sees 99, decides to allow
Goroutine A: ZADD → count = 100
Goroutine B: ZADD → count = 101 ← over limit, both were allowed-- This runs atomically — no interleaving possible
local count = redis.call("ZCARD", KEYS[1])
if count < tonumber(ARGV[1]) then
redis.call("ZADD", KEYS[1], ARGV[2], ARGV[3])
return 1 -- allowed
end
return 0 -- rejectedWhat Lua atomicity does NOT give you
EVAL vs script loading (EVALSHA)
// Every call sends the full script source — wastes bandwidth
result, err := rdb.Eval(ctx, scriptBody, keys, args...).Result()
// Load once, call by SHA — bandwidth efficient
sha, err := rdb.ScriptLoad(ctx, scriptBody).Result()
result, err := rdb.EvalSha(ctx, sha, keys, args...).Result()
// redis.NewScript handles this automatically:
// loads on first use, retries with EVAL on NOSCRIPT
script := redis.NewScript(scriptBody)
result, err := script.Run(ctx, rdb, keys, args...).Result()redis.NewScript is the right default in Go — it caches the SHA, falls back to EVAL if the script isn't loaded on the server (e.g. after a restart), and is safe to call concurrently.