How-To Guide

How to Build a Rate Limiter with Redis

Enforce per-client request limits across many instances with an atomic Redis algorithm that survives restarts and clock skew.

On this page

  1. Introduction
  2. Why Rate Limit
  3. Algorithms Compared
  4. A Sliding Window in Redis
  5. Atomicity with a Script
  6. Handling Redis Failure
  7. Distributing the Limit
  8. Conclusion

Introduction

Rate limiting protects a service from a client that sends too much, whether by accident or on purpose, and it must work when the service runs on many instances behind a load balancer. An in-process counter fails there because each instance counts separately, so the effective limit is the per-instance limit times the instance count. Redis is the common shared store: all instances increment the same counter, and an atomic operation makes the check-and-increment safe under concurrency. This article covers the algorithms, an atomic sliding-window implementation, and how to behave when Redis itself is unavailable.

Why Rate Limit

A rate limit bounds how many requests a client may make in a period, so one client cannot consume the capacity the others need. It protects against a bug that loops, a script that scrapes, and a misconfigured client that retries aggressively. It also makes the cost of a client predictable, which is a business concern as much as a reliability one.

The limit must be enforced where the request arrives, before the expensive work, so the rejected request is cheap. Enforcing it after a database query defeats the purpose, because the cost has already been paid.

Algorithms Compared

A fixed window counts requests in a fixed period and resets at the boundary; it is simple but allows a burst of up to double the limit across the boundary, because the last instant of one window and the first of the next both allow the full count. A sliding window smooths this by counting over the last period at each request. A token bucket allows a controlled burst up to a bucket size and refills at a steady rate, which models a client that occasionally bursts but averages below the limit.

For most APIs a sliding window is the right default: it is predictable and does not allow the boundary burst. A token bucket is right when a burst is expected and acceptable. Pick deliberately, because the choice determines the worst-case behavior under load.

A Sliding Window in Redis

A simple and atomic sliding window stores the request timestamps in a sorted set per client, removes the ones older than the window, counts what remains, and adds the current one if under the limit. All of it must run in one atomic script, or two concurrent requests can both read a count under the limit and both proceed, exceeding it. Redis executes a Lua script atomically, which is the mechanism to use.

-- rate_limit.lua: atomic sliding-window limit for one client key.
-- KEYS[1] = client key, ARGV = [now_ms, window_ms, limit, member]
local key    = KEYS[1]
local now    = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit  = tonumber(ARGV[3])
local member = ARGV[4]

-- Drop entries older than the window.
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
local count = redis.call('ZCARD', key)
if count >= limit then
  return {0, count}                     -- rejected
end
redis.call('ZADD', key, now, member)
redis.call('PEXPIRE', key, window)      -- expire the key when idle
return {1, count + 1}                   -- accepted

Atomicity with a Script

The script must be the only path that mutates the key, because any non-atomic sequence of read and write lets two requests interleave. Loading the script once and invoking it by its SHA avoids sending the body on every call. The client passes a unique member so two requests at the same millisecond do not collide in the sorted set.

const fs = require('node:fs');
const crypto = require('node:crypto');
const redis = require('ioredis');
const client = new redis();

const script = fs.readFileSync('./rate_limit.lua', 'utf8');
let sha;
async function ensureLoaded() {
  sha ??= await client.script('load', script);
}

async function allow(clientKey, { windowMs, limit }) {
  await ensureLoaded();
  const now = Date.now();
  const member = now + ':' + crypto.randomUUID();   // unique per request
  try {
    const [allowed] = await client.evalsha(sha, 1, clientKey, now, windowMs, limit, member);
    return allowed === 1;
  } catch (err) {
    if (String(err.message).includes('NOSCRIPT')) { sha = undefined; return allow(clientKey, { windowMs, limit }); }
    throw err;
  }
}

Handling Redis Failure

If Redis is unavailable, the limiter must choose a behaviour: fail open, allowing requests, or fail closed, rejecting them. Failing open risks overload but keeps the service available; failing closed protects the service but turns a Redis blip into an outage of everything. For most APIs, fail open is the safer choice, because the limiter is a protection rather than a correctness control, and the service should survive the limiter’s store being down.

Bound the time spent waiting on Redis with a short timeout so a slow Redis does not add latency to every request. If the check exceeds the timeout, apply the fallback policy. This is the same principle as any dependency: a timeout and an explicit degradation, rather than an unbounded wait.

Distributing the Limit

A single Redis instance is a bottleneck and a single point of failure; a cluster shards the keys but complicates the atomicity. Shard the limiter by client key so each client’s key lives on one shard, and the script remains atomic for that client. A global limit across all clients is harder and usually unnecessary; per-client limits are the common case.

Choose the key carefully: an API key or a user id gives a fair per-caller limit, while an IP address is coarse behind a NAT where many users share one address. Combine a per-key limit with a coarser per-IP limit to catch a client that rotates keys, and make the limits explicit so a legitimate client knows the budget.

Conclusion

A rate limiter with Redis enforces a shared limit across instances by incrementing one key atomically. Use a sliding window for predictable behavior, implement the check and increment in a single Lua script so concurrent requests cannot both pass, load the script by SHA, and give each request a unique member. Handle Redis failure with a bounded timeout and an explicit fail-open or fail-closed policy, shard by client key, and choose the key so the limit is fair behind NAT. Then a client that sends too much is slowed without affecting the rest.

Sources: Redis: rate limiting patterns, Redis: EVAL and Lua scripting, Stripe: rate limiters.

FAQ

Why is an in-process rate limiter wrong behind a load balancer?
Because each instance counts separately, so the effective limit is the per-instance limit times the number of instances. A shared store such as Redis lets all instances increment the same counter, which enforces the intended limit.
Should the rate limiter fail open or fail closed when Redis is down?
Usually fail open for an API protection, because the limiter guards against overload rather than enforcing correctness, and failing closed turns a Redis blip into a full outage. Use a bounded timeout and an explicit policy rather than an unbounded wait.

Related Examples