Platform notes · No. 14

The bucket that says no

Rate limiting, explained with a toy you can break. Drag the sliders, hit the burst button, and watch which requests get through.

Written for the Lumenpost API guild by Ines Okafor · 11 min read

Why bother

Last March one misconfigured client hit our search endpoint 1,284 times in 3.1 seconds. It wasn't an attack. A retry loop had lost its sleep call. The database survived, the p99 latency for everyone else went to 4.7 seconds, and we spent the afternoon writing the limiter this page is about.

A rate limiter is a bouncer with a rule. Every request asks "may I come in?" and the limiter answers yes or no, quickly, without asking the database. The interesting part is the rule. Different rules forgive bursts differently, cost different amounts of memory, and fail in different ways at the edges.

We'll start with the one I'd pick for almost any public API.

The token bucket

Picture a bucket that holds coins. A tap drips new coins in at a steady rate, say 5 per second, until the bucket is full. Each request that arrives must take one coin. If there is a coin, the request goes through. If the bucket is empty, the request gets a 429 Too Many Requests and the client has to wait.

That's the whole thing. Two numbers describe it.

R, the refill rate, is your long-run average. Over a minute, nobody gets more than about R × 60 requests.

C, the capacity, is how much burst you forgive. A client that has been quiet saves up to C coins and can spend them all at once.

Try it

Tokens added per second.
Most tokens the bucket can hold.
Average requests per second, arriving at random.
0
Accepted
0
Rejected (429)
10.0
Tokens now
0.0
Accepted/s, last 5 s

The strip along the bottom of the canvas is the last 10 seconds of decisions. Green ticks point up, red ones point down.

Things to try

Set incoming traffic just under R and leave it. Almost everything goes green, and the bucket stays near full. Now push traffic to roughly double R. The bucket drains in a couple of seconds and then settles into a rhythm: accepted requests per second climbs to R and stops there, and the rest turn red. That ceiling is the point.

Then pick "Quiet, then bursty" and press the burst button. With C at 20 the whole burst gets through, because the client earned those coins by being quiet. Press it again straight away and most of the second burst bounces. Drop C to 3 and try once more. Same average rate, far less patience for spikes.

R decides how much traffic you accept over time. C decides how lumpy that traffic is allowed to be.

The implementation is small enough to read in one breath. You don't need a timer that drips coins. You store the token count and the time you last looked, and top the bucket up lazily whenever a request shows up.

function allow(bucket, now) {
  // top up for the time since we last looked
  const elapsed = now - bucket.last;
  bucket.tokens = Math.min(bucket.capacity,
                           bucket.tokens + elapsed * bucket.rate);
  bucket.last = now;

  if (bucket.tokens >= 1) {
    bucket.tokens -= 1;
    return true;            // let it through
  }
  return false;             // 429, with Retry-After
}

Two numbers per client, one subtraction per request. In Redis this is a short Lua script keyed by API key, so every app server shares the same bucket. When you say no, send a Retry-After header. You can compute it exactly: (1 - tokens) / rate seconds.

Two other ways to count

Token buckets think in rates. Window limiters think in counts: "no more than 5 requests per minute." They're easier to explain to a customer, and they show up in a lot of pricing pages. The two diagrams below use the same 12 requests over two minutes with a limit of 5 per minute.

Fixed window

Chop time into minutes on the clock. Keep one counter per client per minute. When the minute rolls over, the counter resets to zero. It costs one integer and one INCR.

Fixed window diagram Two one-minute windows. Five requests near the end of the first minute and five at the start of the second are all accepted, so ten requests get through in nine seconds. The last two requests of the second minute are rejected.
acceptedrejected
The flaw sits on the boundary. Both windows are under their limit, yet 10 requests landed between 0:56 and 1:05. Fixed windows can let through twice the limit in a short span.

Sliding window

Instead of asking "how many this calendar minute?", ask "how many in the 60 seconds before right now?" The exact version, called a sliding log, keeps a timestamp for every accepted request and counts the ones that are younger than a minute. Drag the window to see what it counts at each moment.

Sliding window diagram The same requests judged by a 60 second sliding window. The burst at the start of the second minute is rejected because the window still contains the five earlier requests.
acceptedrejectedthe 60 s window
No boundary spike. The burst at 1:01 to 1:05 is refused because the window still holds the 5 requests from 0:12 to 0:58. Later, at 1:15 and 1:36, room has opened up and they're let in.

The price is memory. A sliding log stores one timestamp per accepted request, which is fine for a login form limited to 5 tries and silly for an endpoint allowing 10,000 a minute. The common compromise is the sliding window counter: keep the counts for this minute and the last one, and estimate.

estimate = previous_count × (1 - seconds_into_minute / 60)
         + current_count

Fifteen seconds into a minute, with 40 requests last minute and 9 so far, the estimate is 40 × 0.75 + 9 = 39. Two integers per client and it's within a few percent of the exact answer, as long as traffic inside a minute is roughly even.

Side by side

MethodState per clientBurstsBoundary spike
Token bucket2 numbersUp to C, on purposeNone
Fixed window1 counterWhole limit at onceUp to 2× the limit
Sliding log1 timestamp per requestWhole limit at onceNone
Sliding counter2 countersWhole limit at onceSmall, estimated away

Which one should you use?

My opinion, after running all four in production at some point:

Default to a token bucket

For a public or partner API, it matches how real clients behave. They're idle, then they do a page load's worth of calls. Set R to the sustained rate you can afford and C to the biggest honest burst you've seen in your logs. For us that was R = 20/s and C = 60.

Use a fixed window for quotas, not protection

"10,000 calls per day on the free plan" is a billing rule. Customers can read it, support can check it, and a 2× spike at midnight doesn't hurt anyone. Don't use it to keep a database alive.

Use a sliding log when the limit is tiny and strict

Password attempts, OTP sends, password resets. Five per 15 minutes means five, and storing five timestamps costs nothing.

Use a sliding counter when you need "per minute" at scale

If the contract is written as a count per minute and you have millions of keys, two counters per key is the cheapest honest answer.

Whatever you pick, a few rules travel with it. Key the limit by API key or user, not IP address, because offices and mobile carriers put thousands of people behind one IP. Return 429 with Retry-After so well-behaved clients back off on their own. And log every rejection with the key that caused it. The first time a limiter fires in anger, someone will ask who it was.