Write Redis Lua scripts for atomic operations
✓Works with OpenClaudeYou are a Redis Lua scripting expert. The user wants to write atomic Lua scripts that execute inside Redis to perform complex operations without intermediate round-trips or race conditions.
What to check first
- Verify Redis server is running and accessible:
redis-cli pingshould returnPONG - Check your Redis version supports Lua (2.6+):
redis-cli info server | grep redis_version - Ensure you have a Redis client library that supports
EVALorEVALSHAcommands (redis-py, node-redis, ioredis, etc.)
Steps
- Write your Lua script as a string with access to KEYS and ARGV tables—Redis passes them automatically
- Use
redis.call()(orredis.pcall()for error handling) to execute Redis commands inside the script - Load the script with
EVAL script numkeys key1 key2 ... arg1 arg2or cache it withSCRIPT LOADfor reuse viaEVALSHA - Return values from Lua: numbers, strings, tables (arrays), and nil—Redis converts them to appropriate reply types
- Handle atomicity by keeping all state changes inside a single script execution—no partial failures between commands
- Test scripts locally with
redis-cli EVAL "return redis.call('GET', KEYS[1])" 1 mykeybefore integrating into applications - Use
SCRIPT EXISTS sha1 sha2 ...to check if cached scripts are still available before callingEVALSHA - Implement error handling with
redis.pcall()and conditional logic to retry or rollback operations atomically
Code
-- Redis Lua script: Atomic counter with rate limiting and expiration
-- KEYS[1]: counter key, KEYS[2]: rate limit key
-- ARGV[1]: max increments per window, ARGV[2]: window duration (seconds), ARGV[3]: increment amount
-- Returns: {success, current_count, ttl} or {0, "Rate limit exceeded", nil}
local counterKey = KEYS[1]
local rateLimitKey = KEYS[2]
local maxIncr = tonumber(ARGV[1])
local windowDuration = tonumber(ARGV[2])
local incrAmount = tonumber(ARGV[3])
-- Get current counter value
local currentCount = tonumber(redis.call('GET', counterKey)) or 0
-- Check rate limit window
local windowCount = tonumber(redis.call('GET', rateLimitKey)) or 0
-- If we would exceed the limit, reject atomically
if windowCount >= maxIncr then
return {0, "Rate limit exceeded", redis.call('TTL', rateLimitKey)}
end
-- Atomically increment counter and rate limit window
redis.call('INCRBY', counterKey, incrAmount)
local newCount = redis.call('INCR', rateLimitKey)
-- Set expiration on rate limit window (only on first increment)
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Database Skills
Other Claude Code skills in the same category — free to download.
Migration Generator
Generate database migration files
Query Optimizer
Analyze and optimize slow database queries
Schema Designer
Design database schema from requirements
Seed Data Generator
Generate database seed/sample data
Index Advisor
Suggest database indexes based on query patterns
ORM Model Generator
Generate ORM models from database schema
SQL to ORM
Convert raw SQL queries to ORM syntax
Database Backup Script
Create database backup and restore scripts
Want a Database skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.