ealeng

Episode 40 of 55 · Overload

Rate limits: a fixed window let 200 through in one millisecond, and four servers each let through every request

A limit of 100 requests a second, kept in each of four servers, refused nothing: all 4,027 requests sent in 10 seconds got through. One shared token bucket in Redis held it to about 100 a second after a first-second burst of 199. Then Redis froze for 3 seconds, and the choice between failing open and failing closed decided whether the limit vanished or the service did.

Lab 17 · Overload, Rate Limits and Backpressure10 min read
Video transcript8:24

0:00Cold open

0:01

I gave one client a limit of a hundred requests a second. Then that client sent about four hundred a second, to my four servers.

0:11

Every single request got through. Not one was refused.

0:16

I moved the limit into one shared place, and it held: about a hundred a second.

0:23

Then that shared place froze for three seconds. One setting decided the rest: everything got through, or nothing.

0:32

So how do you count to a hundred, on four machines, when the counter can stop answering?

0:39Intro

0:40

Hands-on system design, part forty.

0:44

Today: rate limiters. Three ways to count, why four servers multiply a limit, and what to do when the counter freezes.

0:53Meet Lucía

0:54

I’m Lucía, a platform engineer. Our public web API needs a rate limit: how many requests one client may make, per second.

1:03

Without one, a single client, a buggy script in a loop, say, can use up the servers everyone else shares.

1:11

The limit is per client, counted by a key, such as an API key.

1:17

Past the limit, the request is refused at once, with status four twenty-nine, “Too Many Requests”, before any real work.

1:26

Think of a museum that lets in a hundred visitors an hour. A fixed window is a counter that resets on the hour. A sliding window estimates the last sixty minutes. A token bucket is a ticket machine: it prints new tickets at a steady pace, and holds a hundred at most.

1:4501 · What you need

1:46

To run it yourself: Docker, for four copies of a small service, a load balancer that spreads requests across them, and Redis, a fast shared database.

1:58

The quick tests, including each limiter at the edge of its window, run without Docker in a couple of seconds. No cloud, nothing to pay for.

2:0902 · Three ways

2:10

First, a simulation: one program where I set each request’s time exactly. No network, no servers yet. The limit: a hundred a second.

2:21

A fixed window keeps one counter per client per second. At a hundred, it refuses until the next second starts.

2:30

A sliding window also counts part of last second. If last second had eighty, a quarter of the way in it counts sixty of them, plus this second’s.

2:41

A token bucket holds up to a hundred tokens, its burst, and refills at a hundred a second. Each request takes a token. No token, refused.

2:5303 · The edge

2:54

The first test: a hundred requests at nine hundred ninety-nine milliseconds, and a hundred more one millisecond later.

3:03

With a fixed window, how many of those two hundred get through?

3:10

All two hundred, in one millisecond. The first hundred land in one second, the rest in the next. Each counter sees only a hundred.

3:20

The sliding window let a hundred through. So did the token bucket: its hundred tokens were gone after the first hundred requests.

3:3004 · Steady traffic

3:32

The second test: three hundred requests a second, evenly spaced, for ten seconds. Three times the limit.

3:40

The token bucket let a hundred ninety-nine through in its first second. It starts full: a hundred stored tokens, plus ninety-nine refilled during that second. After that, exactly a hundred a second.

3:55

The sliding window let nine hundred ninety-one through: ninety-nine a second. It’s an estimate, and here it erred a hair on the safe side.

4:0605 · In code

4:07

In code, a token bucket is two numbers per client: how many tokens it has, and when it last looked. A new client starts full.

4:16

On each request, add a hundred tokens per second since the last look, never above a hundred. Half a second: fifty tokens.

4:26

Less than one token: refuse. Otherwise, allow it, and take one.

4:3306 · Four servers

4:34

Now for real. Four copies of the service, behind the load balancer. One client sends about four hundred requests a second, four times the limit, for ten seconds. Each server keeps its own token bucket, in its own memory.

4:50

Four thousand and twenty-seven sent. Every one got through, past a limit of a hundred a second.

4:59

Like four museum entrances, each with its own counter. Each server could let through at most about eleven hundred in ten seconds, and all of them got through. So each saw roughly a hundred a second: its own limit, with spare tokens for moments when more arrived at once.

5:17

Then one bucket, shared, in Redis, a fast in-memory database all four servers can reach. A hundred ninety-nine in the first second, a full bucket plus its refill, then about a hundred a second.

5:3207 · Shared, in code

5:33

The shared bucket is the same logic, written as a small script that runs inside Redis.

5:41

Redis runs the whole script as one step. So two servers can’t both read “one token left” and both take it.

5:5008 · Redis freezes

5:52

Every request now asks Redis first. So I froze Redis for three seconds. Each server waits fifty milliseconds, then decides alone: allow, which is failing open, or refuse, which is failing closed.

6:07

Failing open: for about three seconds, every request sent got through, about four hundred a second. The limit was simply gone.

6:17

Failing closed: nothing got through for about three seconds. The limit held, and the service was gone. Right after, the bucket was full again, so a hundred seventy-one got through that second: what it had stored, plus a second of refill.

6:33

And while it was frozen, requests sat out the fifty-millisecond timeout: one in a hundred took fifty-seven or more, where one normally takes two.

6:44

Neither is free. The question is which failure you’d rather have.

6:5009 · Which one

6:51

My rule of thumb: choose per endpoint, each address of your API, like login, before it happens, by what the limit protects.

7:01

A login: fail closed. There, the limit stops password guessing, and refusing logins for three seconds is survivable.

7:10

A “like” button: fail open. A few extra likes harm nobody, and refusing them all looks like an outage.

7:19

And anything that costs you money per call, usually closed: there, the limit is what keeps the bill in check.

7:28Back to Lucía

7:29

So, three lessons.

7:32

A fixed window lets twice the limit through at its edge. A sliding window closes that gap. A token bucket lets through at most its burst at once, then its rate.

7:44

A limit kept in each server is the limit times the servers. Share one counter.

7:50

And decide how the limiter fails, before it does. Open means no limit. Closed means no service.

7:58

Next time: what happens when it isn’t one client but everyone, more than the servers can handle. And retries that keep a system down after the problem is gone.

8:10

For today: one counter, and a plan for when it stops.Lucía: One counter. A plan for when it stops.

8:15Summary

8:16

Mind the window edge, share one counter, and decide how it fails before it does.

Key takeaways

  • ✓A fixed window lets through twice its limit at an edge: for a limit of 100 a second, 200 requests sent within one millisecond all got through, while a sliding window allowed 100 and a token bucket allowed 100.
  • ✓A token bucket allows its burst at once and then its rate: under steady traffic of 300 a second for 10 seconds it let through 199 in the first second (100 stored plus 99 refilled), then about 100 a second, 1,099 in all, against 991 for the sliding window and 1,000 for the fixed window.
  • ✓A limit kept in each of four servers is multiplied by four: the servers allowed all 4,027 requests sent in 10 seconds, about 400 a second, while one bucket shared through Redis allowed 1,108 in the same run, 111 a second on average.
  • ✓When Redis was frozen for 3 seconds, failing open let through all 1,166 requests sent in that window, so the limit was simply gone, and failing closed let through 10, so the service was gone; the slowest one in a hundred (the p99) took 56 to 57 ms, against a median of about 2 ms when Redis was running.
  • ✓A rate limit's failure mode is a product decision made per endpoint: the lab measured both behaviours but not the choice, and the rule of thumb (closed for logins, open for a like button, closed where each call costs money) is the video's advice, not a measurement.

A rate limit has one job: decide, for each request, whether this client has sent too many. The lab for this chapter, Lab 17 (Overload, Rate Limits and Backpressure) of the system design labs, tested three ways to count, a limit shared across four servers, and what happens when the shared store stops answering. The same numbers come out of every run: a fixed window lets through twice its limit at an edge, four servers each keeping their own count let through every request they were sent, and a shared bucket held the limit near 100 a second until the store froze.

The examples come from script 01_limiters.py, Lab 17's first exercise. Part A runs in one process on a clock the script controls. Parts B and C are live: one client sends 400 requests a second to a rate-limited endpoint (/limited) through a load balancer, HAProxy, to four copies of a small service. The servers, the load balancer and Redis (a fast shared in-memory database) all ran in Docker on one laptop, an Apple M4 Max. Each live configuration is one recorded run. The lab's README puts Lab 17's first exercise at about two minutes.

Three ways to count

Every limiter answers one question for each request: has this client, identified by a key such as an API key, exceeded its limit? The lab sets the limit at 100 requests a second. Past the limit, the server answers at once with status 429, "Too Many Requests", before doing any real work.

  • Fixed window. One counter per client for each one-second window. At 100, it refuses until the next second starts. It is the simplest, and it has a flaw at the edge of the window, shown below.
  • Sliding window. It counts the current second plus part of the previous one, weighted by how far into the current second the request is. If the previous second had 80 requests and the current one is a quarter of the way in, it counts 60 of those 80 plus this second's requests. It is an estimate, and it assumes the previous second's requests were spread evenly.
  • Token bucket. A bucket holds up to 100 tokens, the burst, and refills at 100 tokens a second. Each request takes one token; with no token, it is refused. A client with a full bucket can send 100 at once, and then only as fast as the bucket refills.

A token bucket needs two numbers per client, the tokens left and the time it last looked. That is why it is the usual choice for APIs: the burst is a number you set, and nothing about past requests is stored.

The edge, and the burst

The first test is a burst at the edge of a window: 100 requests at 0.999 seconds and 100 more one millisecond later, at 1.000 seconds.

Limiter Allowed out of 200 Most in any one second
Fixed window 200 200
Sliding window 100 100
Token bucket 100 100

The fixed window's two batches fall into two different one-second counters, so each counter sees 100 and allows all of them. The sliding window and the token bucket both see the 200 arrive within a millisecond and refuse the second batch.

The second test is steady traffic: 300 requests a second, evenly spaced, for 10 seconds. That is three times the limit, 3,000 requests in all.

Limiter Allowed out of 3,000 Most in any one second
Fixed window 1,000 101
Sliding window 991 100
Token bucket 1,099 199

The token bucket's 199 in the first second is a full bucket (100 stored tokens) plus the 99 that refilled during that second. After that it allowed exactly 100 a second, so the burst is visible at the start and nowhere else. The sliding window's 991 is its estimate at work: it erred a little on the safe side and refused a few that were within the limit. The fixed window's 1,000 is exact, but its first second's 101 shows the edge flaw again.

A token bucket does not close the edge gap. It caps the gap at its burst. That is the lesson: a burst is allowed by design, so size it on purpose.

Try it · Three ways to countRecorded results · simulated, exact clock

100 requests at 0.999 s and 100 at 1.000 s. Limit: 100 a second. 200 requests sent.

Fixed windowallowed 200 of 200 · most in one second 200
Sliding windowallowed 100 of 200 · most in one second 100
Token bucketallowed 100 of 200 · most in one second 100

Black tick = the limit of 100 in one second. Scale 0 to 200.

One limiter per server, or one shared

The live test puts a limit of 100 a second in front of four copies of the service. One client sends about 400 a second for 10 seconds: four times the limit.

With each server keeping its own token bucket in its own memory, every request got through. The script records 4,027 allowed in 10 seconds, about 403 a second. Since the four servers each allow a bucket's worth, that is the limit multiplied by the number of servers: four servers, four limits. The lab saves only the totals, not the count per server, so the even split is an inference from the load balancer's least-connections setting, not a measured figure.

With one bucket in Redis, shared by all four servers, the client was held to the limit. The run allowed 1,108 in 10 seconds, 111 a second on average, with 199 in the first second (the burst) and 99 to 108 in each second after it. Every server runs the same small script inside Redis, which applies the token bucket as one step. Two servers cannot both read "one token left" and both take it, which is the reason the logic lives in Redis and not in the application.

Limiter, 4 servers Allowed in 10 s Per second Most in any one second
In each server's memory 4,027 403 442
Shared, in Redis 1,108 111 199

When the shared store stops answering

Once every request asks Redis first, Redis becomes a dependency of every request. The lab tests this by freezing Redis for 3 seconds with CLIENT PAUSE, a Redis command that makes every client wait. Each limiter call has a 50 ms timeout. When the call times out, the server decides alone, and the choice is the failure mode:

  • Fail open: allow the request. The limit is gone while Redis is out.
  • Fail closed: refuse the request. The limit holds, and the service is gone for that client.
Try it · Redis frozen for 3 secondsRecorded results · one live run per mode
Allowed during freeze
1,166
p99 during freeze
57 ms
Median, normally
~2 ms
010020030040012345678910Allowed per second (shaded: Redis frozen, about 3.8 to 6.8 s)

Fail open: the limit was simply gone. Seconds 5 to 7 let through about 400 a second (376, 404, 420).

Limit 100 a second. Each limiter call waited out a 50 ms timeout. Largest one-second count: 436.

With fail open, all 1,166 requests sent during the freeze got through: about 400 a second in the seconds the freeze covered. With fail closed, 10 got through during the freeze, and nothing at all in seconds 5 and 6. Right after the freeze, the bucket had refilled, so fail closed let 171 through in one second: what it had stored plus a second of refill. The p99 (the slowest one in a hundred) took 57 ms with fail open and 56 ms with fail closed, against a median of about 2 ms when Redis was running normally.

Neither failure is free. The question is which one the endpoint can survive. The lab's README and the video give the same rule of thumb, which this chapter labels as theirs, not as something the lab measured:

  • A login: fail closed. The limit stops password guessing, and refusing logins for a few seconds is survivable.
  • A "like" button: fail open. A few extra likes harm nobody, and refusing every like looks like an outage.
  • Anything that costs money per call: usually fail closed, because the limit is what keeps the bill in check.

The workflow and the results

The script. 01_limiters.py runs all three parts in order. Part A is in-process and takes a few seconds. Parts B and C need Docker: four app instances, HAProxy and Redis. The script saves its results to data/results/01_limiters.json, which is where every number in this chapter comes from. Each live run is one recording.

What the lab reports, in its own table:

Limiter Fails Allowed Per second Most in one second Allowed in the 3 s Redis was frozen p99 during the freeze
In each server's memory (none) 4,027 403 442 (not frozen) (not measured)
Shared, in Redis (none) 1,108 111 199 (not frozen) (not measured)
Shared, Redis frozen open 2,093 209 436 1,166 (all sent) 57 ms
Shared, Redis frozen closed 912 91 209 10 56 ms

The per-second figures are the total divided by 10. The fail-open and fail-closed totals include the seconds before and after the freeze, so they are larger or smaller than the freeze alone.

Caveats

  • One run per configuration. Every live row is a single recording, so the numbers show what happened in that run, not the spread across runs.
  • Part A is a simulation. It uses an exact clock that the script controls, so it shows what each algorithm does with a given arrival pattern, not what a real network would produce.
  • The per-server split is not saved. The lab records 4,027 allowed across the four servers, not per server. The claim that each server allowed about 100 a second is an inference from the total and the bucket size, and the lab does not test it directly.
  • One client, one key. The live test used one client key, so it does not test many clients sharing a server, or a key-per-user limit with a real user mix.
  • The sent count is not in the results file. The 4,027 "sent" figure comes from the same seeded arrival schedule the load generator uses, rebuilt by the video's export step. The lab's JSON stores only what was allowed.
  • The freeze timing is approximate. The freeze was started from the host's clock while requests were timed in the load container, so the window is accurate to about 0.1 to 0.15 seconds.
  • Clock source. The limiter takes the time from the application, so servers with skewed clocks would disagree. The lab does not test skew. The script's comments mention Redis's own TIME as the fix.
  • Not tested: the sliding-window estimate under uneven traffic, a real attack on the login endpoint, clients that retry after a 429, a token bucket's cost on Redis at very high rates, and a limit across regions. The other four exercises of this lab (load shedding, retry storms, flash sales, autoscaling) are covered in the next chapters.

Check your understanding

Try each question before opening its answer.

A fixed window with a limit of 100 a second let through 200 requests sent within one millisecond. Why does a sliding window allow only 100?

The sliding window counts the current second plus part of the previous one. When the second batch arrives a millisecond later, the previous second already holds the first 100, so the estimate is already at the limit and the second batch is refused. The fixed window keeps separate counters per second, so the two batches fall into two different counters, each with room for 100.

Under steady traffic of 300 a second, why did the token bucket allow 199 in the first second and then exactly 100 a second?

The bucket starts full, with 100 stored tokens, and it refills at 100 a second. During the first second it refilled 99 tokens while the traffic was taking them, so 100 plus 99 gave 199. After that the bucket is empty and refills only 100 a second, so the allowance drops to the rate.

Four servers each keep a limit of 100 a second, and the client sends 400 a second. Why did all 4,027 requests get through?

Each server's bucket counts only the requests that server received. The load balancer spread the client's requests across the four servers, and each server had room for its own 100 a second, so no single bucket was ever empty. The limit was effectively 100 times the number of servers. One shared bucket in Redis fixes this, by counting every server's requests against the same bucket.

Redis froze for 3 seconds. Why did failing closed let 171 through in the second after the freeze, when nothing got through during it?

While Redis was frozen, the token bucket stayed in Redis and kept refilling in time, so when Redis answered again the bucket was full. The first second after the freeze could take what had accumulated, which is the stored burst plus a second of refill. A burst after an outage is normal for a token bucket: the limit was never really off for the bucket, only for the calls that could not reach it.

Why is a per-endpoint choice between fail open and fail closed better than one setting for the whole API?

Because the cost of each failure differs by endpoint. A login's limit protects against guessing, so letting attempts through while the limit is gone is the dangerous failure. A like button's limit protects against nothing important, so refusing every like during an outage looks like the whole site is down. Choosing per endpoint, before the outage, is the only way to make each case right.

Next up: Chapter 41, retry storms and load shedding. This chapter's limiter turned requests away at the edge. Next, a system with no limit at all gets more traffic than it can handle, and a retry policy that keeps it down after the cause is gone.

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.