Course contentsShow
← System Design
Lesson 1795 of 1,91943. Real-World System: Rate Limiter ServiceFree lesson

Redis Lua Scripts for Atomicity

Use Lua scripts in Redis to execute complex rate limiting logic atomically without race conditions.

Redis Lua Scripts for Atomicity

What you'll learn: How to execute complex rate limiting logic in Redis as a single atomic operation using Lua scripts, eliminating race conditions.

The Race Condition Problem

When rate limiting requires multiple Redis commands—like checking a counter, comparing it to a limit, and incrementing—you face a classic race condition. Between checking and incrementing, another request might sneak in, causing you to accidentally exceed your limit. Multiple clients could all "see" 99 requests, think they're the 100th, and all get approved.

Lua Scripts to the Rescue

Redis executes Lua scripts atomically: the entire script runs as one indivisible operation. No other command can interleave. Think of it like wrapping multiple Redis operations in a database transaction, but lighter-weight and guaranteed.

Instead of:

  1. GET counter (returns 99)
  2. Check if 99 < 100 in your application
  3. INCR counter (now multiple clients might all increment)

You send a single Lua script that does all three steps inside Redis:

local current = redis.call('GET', KEYS[1]) or 0
if tonumber(current) < tonumber(ARGV[1]) then
  redis.call('INCR', KEYS[1])
  redis.call('EXPIRE', KEYS[1], ARGV[2])
  return 1
else
  return 0
end

This script checks the counter, compares against the limit, increments only if allowed, sets expiration, and returns success/failure—all atomically. No gaps, no races.

Why This Matters for Rate Limiting

Rate limiting demands exact accuracy under high concurrency. Lua scripts guarantee that check-and-increment logic is bulletproof, even with thousands of simultaneous requests hitting the same key.

Key Takeaway:
Redis Lua scripts execute multiple commands atomically, preventing race conditions in complex rate limiting operations like check-then-increment logic.