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

Lua Scripts for Atomic Rate Limit Operations

Execute rate limit logic atomically in Redis using Lua scripts to avoid race conditions and reduce round trips.

Lua Scripts for Atomic Rate Limit Operations

What You'll Learn

You'll learn how to use Redis Lua scripts to execute complete rate limiting logic atomically, preventing race conditions and drastically reducing network round trips.

Why Lua Scripts Matter for Rate Limiting

When implementing rate limiting with Redis, naive approaches using multiple commands (GET, INCR, EXPIRE) create a dangerous window where race conditions occur. Between reading a counter and incrementing it, another request might slip through, allowing users to exceed their limits.

Lua scripts solve this by executing multiple Redis operations as a single atomic transaction—Redis guarantees the script runs without interruption.

The Core Problem

Imagine checking if a user has quota (GET), incrementing their counter (INCR), and setting expiration (EXPIRE) as separate commands. Between these operations, thousands of concurrent requests could check the same old counter value, all deciding they have quota remaining. This violates your rate limit.

How Lua Scripts Help

A Lua script bundles all rate limit logic—checking current count, comparing against the limit, incrementing, and updating TTL—into one atomic block:

local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])

local current = redis.call('GET', key)
if current and tonumber(current) >= limit then
    return 0  -- rate limit exceeded
end

redis.call('INCR', key)
redis.call('EXPIRE', key, window)
return 1  -- request allowed

This script executes atomically. No other command interrupts it. You've eliminated race conditions entirely and reduced network latency from 3+ round trips to exactly one.

Additional Benefits

Beyond atomicity, Lua scripts execute directly on the Redis server, keeping all data local during computation—critical when checking sliding windows or token bucket refills that involve multiple keys or complex calculations.

Key Takeaway:
Lua scripts in Redis execute rate limiting logic atomically, eliminating race conditions and reducing network overhead from multiple round trips to a single operation.