Skip to content
Blog

← All articles

Rate Limiting Inside Redis: An Atomic Lua Script That Decides in Single-Digit Microseconds

A Redis Lua script that makes the whole rate-limit decision atomically inside Redis: several limits, request costs, Retry-After and RateLimit headers, self-expiring keys. Measured on Redis 8.2: 4 to 8 microseconds of server time per decision, where those microseconds go, why GET-then-SET let through 17 times the limit and WATCH/MULTI managed a quarter of the throughput, and how to run it in production.

By 15 min read

An in-process rate limiter only sees the traffic of its own process. As soon as an API runs on more than one server, the limiter’s state has to live somewhere shared, and Redis is the usual place. The hard part isn’t storing the state; it’s making the decision correctly when dozens of servers ask about the same client at once, without adding noticeable latency to every request.

This article builds a Redis Lua script that does the whole assessment inside Redis, in one atomic step: several limits at once, requests that cost more than one token, and everything an HTTP API needs for its response headers. We measured it on Redis 8.2: the decision costs Redis 4 to 8 microseconds, and we break down where each one goes. It builds on our articles on the math of token buckets and thread-safe in-process limiters. Every example was run before publishing.

The short answer#

Why the decision must happen inside Redis#

A rate-limit decision is a read, a calculation, and a write. There are three common ways to run them against Redis. We implemented the same GCRA limit (50 a second, burst of 25) all three ways and had 20 connections hammer one client’s key for two seconds. At most b + r·t = 125 requests should get through:

ApproachRound tripsAccepted (limit 125)Decisions per second
GET, decide in the app, then SET22,198–2,20573,000–78,000
WATCH / MULTI / EXEC3, more on retries12426,000–28,000 (1,003–1,073 aborted)
One Lua script1124104,000–106,000
  • GET then SET let through more than 17 times the limit. Between one server’s GET and its SET, the other 19 read the same old value and made the same decision. This is the most common bug in hand-written distributed rate limiters, and it gets worse exactly when a client is sending the most.
  • WATCH/MULTI/EXEC is correct: Redis aborts the transaction if the key changed after the WATCH, and the client retries. But under contention, it spends its time retrying: over a thousand aborts in two seconds, and a quarter of the throughput of the script.
  • The Lua script is correct and the fastest of the three: one round trip, no retries, no window for a race.

Why a script is atomic#

Redis executes commands on a single main thread, one at a time. A Lua script is treated as one command: while it runs, no other client’s command is executed, so nothing can change the keys between the script’s read and its write. That is the whole reason this design works, and it has a direct consequence: a slow script blocks everyone. A script that runs for 10 milliseconds stops every other command on that Redis for 10 milliseconds. (Once a script has run longer than busy-reply-threshold, 5 seconds by default, Redis starts answering other clients with a BUSY error until the script finishes or is killed.) A rate-limit script has to be short, and with no loops over data, it is: a handful of commands and some arithmetic.

The script#

limit.lua
-- limit.lua: the whole rate-limit decision for one request, run atomically inside Redis.
-- KEYS: one key per limit (e.g. per second and per day), all with the same {hash tag}.
-- ARGV: cost, then interval and burst for each limit. Intervals are in microseconds.
-- Returns {allowed, retry_after_us, remaining, reset_us}.
local t = redis.call("TIME")
local now = t[1] * 1000000 + t[2] -- microseconds, from Redis's clock
local cost = tonumber(ARGV[1])
local tats = redis.call("MGET", unpack(KEYS)) -- every limit's state in one call

local new, retry, remaining, reset_now, reset_after = {}, 0, math.huge, 0, 0
for i = 1, #KEYS do
  local interval, burst = tonumber(ARGV[2 * i]), tonumber(ARGV[2 * i + 1])
  local tat = math.max(tonumber(tats[i]) or now, now) -- GCRA: theoretical arrival time
  local new_tat = tat + cost * interval
  local allow_at = new_tat - burst * interval -- the earliest time this request fits
  if allow_at > now then
    retry = math.max(retry, allow_at - now)
  else
    remaining = math.min(remaining, math.floor((now - allow_at) / interval))
  end
  new[i] = new_tat
  reset_now = math.max(reset_now, tat - now) -- until every bucket is full again, if rejected
  reset_after = math.max(reset_after, new_tat - now) -- the same, if allowed
end

if retry > 0 then
  return {0, retry, 0, reset_now} -- rejected: nothing is charged to any limit
end
for i = 1, #KEYS do
  -- Expire each key when its bucket would be full: a missing key means the same thing.
  redis.call("SET", KEYS[i], new[i], "PX", math.ceil((new[i] - now) / 1000))
end
return {1, 0, remaining, reset_after}

Each part has a reason:

  • GCRA stores one number per limit, the theoretical arrival time. It is the same limiter as a token bucket in less state, as our math article shows. A request with cost c fits if TAT + c·T − b·T ≤ now.
  • Every limit is checked before any is charged. If the daily limit rejects a request, the per-second limit isn’t charged for it either. Our tests check that the per-second key is unchanged after a rejection by the daily one.
  • Time comes from Redis. Each app server’s clock is a little different; Redis’s clock is the same for all of them. Since Redis 7, scripts are replicated by their effects (the SET commands they ran), not by re-running them, so reading the time in a script is safe.
  • Microseconds as Lua numbers. Lua in Redis uses double-precision numbers, which represent integers exactly up to 253. Microseconds since 1970 stay below that until the year 2255.
  • Keys expire when the bucket would be full. After that moment, a missing key and the stored value mean the same thing, so Redis deletes idle clients for us, and memory holds only active ones.
  • The reply has everything the HTTP response needs: whether the request is allowed, how long to wait, how many requests remain, and when the limit resets.

Where the microseconds go#

Redis records how much time it spends in each command (INFO commandstats). We ran each variant with redis-benchmark, 50 connections and 100,000 different client keys, inside the Redis container on a 13th-generation Intel Core i9, and read the server time per call, in two runs:

CommandServer time per callCalls per second, 1 at a timeCalls per second, pipelined (16)
GET (for comparison)0.09 µs178,000–189,0002.5 million
INCR (for comparison)0.44–0.46 µs185,000–197,0001.7 million
Fixed-window script (INCR + EXPIRE)1.6–1.7 µs201,000–202,000476,000–480,000
GCRA script, 1 limit4.1–4.2 µs126,000–127,000204,000–208,000
GCRA Function (FCALL), 1 limit4.0–4.1 µs126,000–132,000213,000–214,000
Token bucket in a hash, 1 limit4.8–5.0 µs113,000–121,000178,000–183,000
limit.lua, 2 limits7.7–7.8 µs83,000–86,000116,000

So the decision really is single-digit microseconds of Redis time. To see what it’s made of, we added one piece at a time to a script and measured each step:

Script bodyServer time per callAdded by this step
return 10.71 µs0.71 µs: running a script at all
+ TIME1.38 µs0.67 µs
+ GET1.69 µs0.31 µs
+ SET2.57 µs0.88 µs
+ PX on the SET3.07 µs0.50 µs
The full GCRA script (with the arithmetic)4.1 µsabout 1 µs

Every redis.call costs a few tenths of a microsecond to nearly one, and the Lua arithmetic about one in total. The second limit in limit.lua adds one more SET and its math: 7.7 µs instead of 4.1.

Optimizations that matter#

  • One round trip. The biggest optimization is the one the script already makes: everything in one call. Two round trips aren’t just slower; as the table above shows, they’re wrong.
  • Fewer redis.calls. Read every limit with one MGET instead of one GET each, and skip the writes entirely when the request is rejected.
  • One string, not a hash. GCRA’s single number fits in a plain string key: 48 bytes per client in MEMORY USAGE, against 88 for a token bucket stored as a two-field hash, and 4.1 µs against 4.8–5.0.
  • Call by SHA. EVAL sends the whole script on every call. Redis caches compiled scripts, so the server time hardly changed in our test (4.1 µs), but every request carries the script’s text over the network. EVALSHA sends a 40-character hash instead. ioredis’s defineCommand does this automatically, falling back to EVAL once if Redis replies NOSCRIPT.
  • Pipelining for throughput. One Redis core made 126,000 single-limit decisions a second one at a time, and 204,000–214,000 with 16 requests in flight per connection, because it spends less time on network reads and writes. Most client libraries pipeline automatically when many requests share a connection.
  • No KEYS, no SCAN, no loops over data. Anything that grows with the number of clients belongs outside the script, because the script blocks Redis while it runs.

The client side#

middleware.mjs
// middleware.mjs: call limit.lua by its SHA (ioredis loads it on first use) and answer like an HTTP API.
import { readFileSync } from "node:fs";
import Redis from "ioredis";

const redis = new Redis(process.env.REDIS_URL ?? "redis://localhost:6379", {
  commandTimeout: 50, // a slow limiter is worse than none: give up after 50 ms
  maxRetriesPerRequest: 1,
});
redis.defineCommand("limit", { numberOfKeys: 2, lua: readFileSync(new URL("./limit.lua", import.meta.url), "utf8") });

const SECOND = { interval: 100_000, burst: 20 }; // 10 a second, bursts of 20
const DAY = { interval: 86_400_000_000 / 10_000, burst: 10_000 }; // 10,000 a day

export async function rateLimit(clientId, cost = 1) {
  const keys = [`rl:{${clientId}}:s`, `rl:{${clientId}}:d`]; // {clientId}: same cluster slot
  let reply;
  try {
    reply = await redis.limit(...keys, cost, SECOND.interval, SECOND.burst, DAY.interval, DAY.burst);
  } catch {
    return { status: 200, headers: {} }; // Redis down or slow: fail open (or closed, for costly endpoints)
  }
  const [allowed, retryUs, remaining, resetUs] = reply;
  const headers = { "RateLimit-Remaining": remaining, "RateLimit-Reset": Math.ceil(resetUs / 1e6) };
  if (allowed) return { status: 200, headers };
  return { status: 429, headers: { ...headers, "Retry-After": Math.ceil(retryUs / 1e6) } };
}

if (import.meta.main) {
  const statuses = [];
  for (let i = 0; i < 25; i++) statuses.push((await rateLimit("demo")).status);
  console.log(statuses.filter((s) => s === 200).length, statuses.at(-1)); // 20 429
  console.log(await redis.ttl("rl:{demo}:s"), await redis.ttl("rl:{demo}:d")); // 2 173: each expires when full again
  await redis.quit();
}

Three decisions here are as important as the script itself:

  • A short timeout. If Redis is slow, every API request waits for the limiter. 50 ms is generous for a call that normally takes well under a millisecond.
  • Fail open or closed, on purpose. When Redis can’t be reached, letting requests through keeps the API up; rejecting them protects whatever is behind it. Most APIs fail open for ordinary endpoints and closed for expensive or abuse-prone ones, like login or SMS sending.
  • Useful headers. Retry-After is standard HTTP. The RateLimit-Remaining and RateLimit-Reset headers come from earlier versions of an IETF draft that many APIs follow (the current draft combines them into one RateLimit header); they let a well-behaved client slow down before it is rejected.

Scripts or Functions#

Since Redis 7, the same Lua code can be loaded as a Function: a named library stored in the database, called with FCALL.

ratelimit-function.lua
#!lua name=ratelimit
-- ratelimit-function.lua: the GCRA check as a Redis Function. Loaded once with FUNCTION LOAD, it is stored in the
-- database itself: it survives restarts and is copied to replicas, unlike the EVAL script cache.
local function allow(keys, args)
  local t = redis.call("TIME")
  local now = t[1] * 1000000 + t[2]
  local interval, burst = tonumber(args[1]), tonumber(args[2])
  local tat = math.max(tonumber(redis.call("GET", keys[1])) or now, now)
  local new_tat = tat + interval
  if new_tat - burst * interval > now then
    return {0, new_tat - burst * interval - now}
  end
  redis.call("SET", keys[1], new_tat, "PX", math.ceil((new_tat - now) / 1000))
  return {1, 0}
end

redis.register_function("allow", allow)

In our measurements, a Function was as fast as the script (4.0–4.1 µs against 4.1–4.2). The difference is operational. The EVAL script cache is just a cache: it is empty after a restart or a failover, which is why clients must handle NOSCRIPT. A Function is part of the data set: it is saved with the database, copied to replicas, and there when the client calls it. Our tests check that it makes the same decisions as the script.

Cluster, replicas and capacity#

  • Redis Cluster. A script may only touch keys in one hash slot, and they must be passed in KEYS, not built inside the script. Putting the client ID in braces, rl:{client-42}:s and rl:{client-42}:d, makes Redis hash only that part, so both limits land on the same node. Different clients spread across the cluster, which is how the limiter scales out.
  • Replicas and failover. Writes go to the primary and are copied to replicas asynchronously, so a failover can lose the last few milliseconds of rate-limit state. For a rate limiter, that is usually fine: the worst case is a few extra requests getting through, once.
  • Capacity. At roughly 4 µs per decision, one Redis core can make on the order of 100,000 to 200,000 decisions a second, depending on pipelining. Beyond that, shard clients across a cluster, or put a small in-process limiter in front to reject obvious floods before they reach Redis, as in our in-process limiter article.
  • Memory. At 48 bytes per active client per limit, a million active clients with two limits need about 100 MB. Idle clients cost nothing, because their keys expire.

FAQ#

Isn’t a fixed window with INCR simpler and faster?

It is cheaper: 1.6 µs instead of 4.1 in our measurements. But a fixed window lets a client send twice its limit across a window boundary, and it can’t express a burst separately from the average. Our math article measures that: 200 requests in under a second against a limit of 100 a minute. The 2.5 µs difference rarely matters next to a network round trip.

Can the script be made faster still?

A little. Passing the time from the client would save TIME’s 0.7 µs, at the cost of trusting every app server’s clock, which defeats the point of a shared limiter. Beyond that, the script is mostly the cost of running any script plus one read and one write per limit.

Is there a ready-made module?

The redis-cell module implements GCRA natively as a CL.THROTTLE command, but it has to be installed on the server, which managed Redis services often don’t allow. A Lua script or Function works on any Redis 7 or later.

Does this work with Valkey?

Valkey, the open-source fork of Redis, supports the same EVAL, EVALSHA, and Functions commands, so the script should run unchanged. We tested it only on Redis 8.2.