Rate Limiting & Throttling — System Design

A rate limit counted in each server's memory leaks when there are many servers: on 24 servers, a bot limited to 10 per 10 seconds gets through 240 times…

The account scalper99 may order only 10 times per 10 seconds. Its bot fires 300 requests, and 240 get through. Not one server miscounted.

It's like a concert venue with 24 entrance gates, and a rule that each person may enter at most 10 times. If every gate guard counts on their own notepad, someone who keeps switching gates can enter 24 × 10 = 240 times, and every guard believes the rule is being kept. For the rule to hold, every guard must ask one central desk over the radio before opening the gate.

Rate limiting caps how many requests one client may send within a time span. This lesson is about the design: a limiter shared by many servers.

One limit, 24 servers

The basics of rate limiting (why it's needed, the 429 answer, three ways of counting) are in the Rate Limiting lesson of the API track, and the login version is in Rate Limiting for Authentication. The examples there run on one server. TicketTune at 10:00 isn't one server: from the What Is System Design lesson, the ticket war needs 24 app servers behind a load balancer.

The rule: the account scalper99 may POST /orders at most 10 times per 10 seconds. Its bot sends 300 requests in 10 seconds, 30 a second, and the load balancer deals them out in turn (round robin). If the counter lives in each server's memory, each server only sees its own share:

App servers Requests each server receives Allowed (max 10 per server) Total allowed
1 300 10 10
2 150 10 20
6 50 10 60
24 12 or 13 10 240

The result: 240 get through, 24 times the limit. The effective limit becomes number of servers × limit, and the more servers you add for the ticket war, the looser the limiter gets. Every server is right by its own notes; what's wrong is where the counter is kept.

One shared counter in Redis

The fix: every server asks one place. Redis fits: its data is in memory, one command takes about 0.5 ms, and its commands are atomic (run one at a time, never interleaved). Here is a fixed window limiter (one counter per 10-second window) with ioredis:

const LIMIT = 10;
const WINDOW = 10; // seconds

async function isAllowed(userId) {
  const windowNo = Math.floor(Date.now() / 1000 / WINDOW);
  const key = `rl:${userId}:${windowNo}`;
  const [[, count]] = await redis.multi().incr(key).expire(key, WINDOW).exec();
  return count <= LIMIT;
}

app.post("/orders", async (req, res, next) => {
  if (!(await isAllowed(req.user.id))) {
    const secondsLeft = WINDOW - (Math.floor(Date.now() / 1000) % WINDOW);
    res.set("Retry-After", String(secondsLeft));
    return res.status(429).json({ error: "Too many requests" });
  }
  next();
});

In redis-cli, the bot's first request in this window looks like this:

> MULTI
OK
> INCR rl:scalper99:179151480
QUEUED
> EXPIRE rl:scalper99:179151480 10
QUEUED
> EXEC
1) (integer) 1
2) (integer) 1

The 11th request gets 1) (integer) 11, so it's refused. With a shared counter, however many servers there are, 10 get through.

GET then SET: shared but still leaking

A counter in Redis isn't enough if it's raised the wrong way. The version beginners often write:

const count = Number(await redis.get(key)) || 0; // read
if (count >= LIMIT) return false;
await redis.set(key, count + 1, "EX", WINDOW); // write
return true;

Between GET and SET there's a gap. Servers receiving a request in the same millisecond read the same value, say 4, and all write 5. Five requests get through, the counter goes up by one. In the Lab's model, with 24 servers, 150 of 300 get through: better than 240, but still 15 times the limit. That's a race condition: the result depends on who goes first. INCR closes the gap, because read, add and write happen as one command inside Redis.

Three algorithms and their memory

The three algorithms from the API track's Rate Limiting lesson, seen from the design side: how much memory each uses per user.

Algorithm What it stores per user Raw bytes Behaviour
Fixed window 1 counter 8 simple; at a window boundary 2 × the limit can get through in a short time
Token bucket token count + refill time 16 allows a burst up to the bucket's capacity, then follows the refill rate
Sliding window log the time of every request in the window limit × 8 most accurate, memory grows with the limit

A token bucket holds as many tokens as its capacity, say 10. Every request takes 1 token, and tokens refill at a steady rate, say 1 a second. A bot that stays quiet for a long time and then fires 15 requests at once gets only 10 through: bursts are allowed, but never beyond the capacity. A fixed window has a hard limit per window that resets periodically, so 10 requests at second 9.9 and 10 more at second 10.1 all get through.

For 1,000,000 active users (TicketTune's DAU), the data alone:

Redis adds tens of bytes of overhead per key, so the real numbers are bigger, but the comparison holds: a log uses memory in proportion to its limit. The middle way is a sliding window counter: two fixed-window counters (this window and the previous one), and the request count is estimated from both, weighted. Nearly as accurate as a log, only 16 bytes. In Redis, a fixed window needs just INCR; a token bucket and a sliding window log need a Lua script or MULTI so their read-compute-write is atomic.

🤔 When Redis goes down

A shared limiter adds one more dependency. If Redis doesn't answer, decide up front:

Also give the Redis call a short timeout (say 50 ms). A limiter that waits long on Redis slows down every request.

⚠️ Limiters that leak, or block forever

TL;DR: A rate limit counted in each server's memory leaks when there are many servers: on 24 servers, a bot limited to 10 per 10 seconds gets through 240 times, because the effective limit is servers × limit. The fix is one shared counter in Redis raised atomically: INCR and EXPIRE in one MULTI/EXEC (or a Lua script), with the window number in the key (rl:scalper99:179151480). Reading then writing (GET then SET) still leaks through a race condition (150 get through in the Lab's model). Over the limit, answer 429 Too Many Requests with Retry-After. A token bucket allows a burst up to the bucket's capacity, then follows the refill rate; a fixed window has a hard limit per window that resets periodically. Memory per user: fixed window 8 bytes, token bucket 16 bytes, sliding window log limit × 8 bytes (a million users: 8 MB, 16 MB, 80 MB). Also decide how it behaves when Redis is down: fail open or fail closed.

⚡ A counter in each server leaks

Guess first: the limit is 10 per 10 seconds. A bot sends 300 requests, dealt out in turn to 24 servers, and each server counts in its own memory. How many get through?

240, 24 times the limit. Every server is right by its own notes; what's wrong is where the count is kept.

Meaning: The effective limit becomes number of servers × limit, and loosens every time servers are added.

⚡ One shared counter in Redis

Write:

const windowNo = Math.floor(Date.now() / 1000 / WINDOW);
const key = `rl:${userId}:${windowNo}`;
const [[, count]] = await redis.multi().incr(key).expire(key, WINDOW).exec();
return count <= LIMIT;

Meaning: INCR adds one to the counter and returns the new value in a single atomic step, and EXPIRE deletes the key once the window is over. However many servers there are, 10 get through. GET then SET still leaks through a race condition.

⚡ Over the limit: 429

Meaning: A request over the limit is answered 429 Too Many Requests, plus Retry-After: how many seconds until it may try again.

⚡ Token bucket

Meaning: The bucket holds as many tokens as its capacity, say 10. Every request takes 1 token, and tokens refill at a steady rate. A bot that stays quiet for a long time and then fires 15 requests at once gets only 10 through: bursts are allowed, but never beyond the capacity.

What you will learn