Database Management
Redis
Subjective
Oct 05, 2025
How do you implement Redis Lua scripting for atomic operations?
Detailed Explanation
Lua scripts execute atomically on Redis server:
**Basic Script Execution:**
# Simple Lua script
EVAL "return redis.call('SET', KEYS[1], ARGV[1])" 1 mykey myvalue
# Get and increment atomically
EVAL "local val = redis.call('GET', KEYS[1]) or 0; redis.call('SET', KEYS[1], val + ARGV[1]); return val + ARGV[1]" 1 counter 5
**Script Caching:**
# Load script and get SHA
SCRIPT LOAD "return redis.call('GET', KEYS[1])"
# Returns: "6b1bf486c81ceb7edf3c093f4c48582e38c0e791"
# Execute by SHA
EVALSHA 6b1bf486c81ceb7edf3c093f4c48582e38c0e791 1 mykey
**Complex Example - Rate Limiting:**
-- rate_limit.lua
local key = KEYS[1]
local window = tonumber(ARGV[1])
local limit = tonumber(ARGV[2])
local current_time = tonumber(ARGV[3])
-- Clean old entries
redis.call('ZREMRANGEBYSCORE', key, 0, current_time - window)
-- Count current requests
local current_requests = redis.call('ZCARD', key)
if current_requests < limit then
-- Add current request
redis.call('ZADD', key, current_time, current_time)
redis.call('EXPIRE', key, window)
return {1, limit - current_requests - 1}
else
return {0, 0}
end
**Python Usage:**
rate_limit_script = r.register_script(open('rate_limit.lua').read())
# Check rate limit (100 requests per 60 seconds)
result = rate_limit_script(
keys=['user:123:requests'],
args=[60, 100, int(time.time())]
)
allowed, remaining = result
if allowed:
print(f"Request allowed. {remaining} remaining")
else:
print("Rate limit exceeded")
**Benefits:**
• Atomic execution
• Reduced network traffic
• Server-side logic
• Better performance for complex operations
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts