Database / REDIS
How does Redis support Lua scripting for atomic operations?
Redis embeds a Lua interpreter directly in the server, and EVAL (or the cached, more efficient EVALSHA) runs a Lua script as a single atomic unit — the entire script executes with no other client command interleaved anywhere in the middle, the same guarantee a single native command gets.
-- atomic "increment if under a limit" check local current = tonumber(redis.call("GET", KEYS[1]) or "0") if current < tonumber(ARGV[1]) then return redis.call("INCR", KEYS[1]) else return -1 end
EVAL "..." 1 rate:user:1001 100
Keys the script will touch are passed explicitly via KEYS (rather than the script hardcoding key names), which matters for Redis Cluster compatibility, since the cluster needs to know up front which slots a script will access. Because the script logic runs entirely inside Redis rather than requiring a round trip back to the client between each step, it also cuts network latency for multi-step logic — a "check current value, conditionally increment" pattern that would otherwise need two separate round trips (with a race condition between them) becomes one atomic, single-round-trip operation.
More Related questions...
