Rate limiting: the bouncer at the door
Vertical version.
Chapters
Narration
Last time the wire was cut and you had to choose: answer anyway, or refuse to be wrong. This time nothing is broken. One regular at the chai stall is knocking five hundred times a second, and everyone behind him is still waiting. So you cap the knocking: for fairness, to protect the backend, to stop abuse, and to cap the bill. So you put a bouncer at the door. It sits at the edge, in the gateway, before any expensive work happens, and it counts per key: per user, per IP address, per API key. Under the limit, the request goes through. Over it, the door answers immediately, and the backend never sees the flood. Now, how do you count? The simple way is a fixed window: five per clock minute, reset on the minute. But a client can send five at fifty nine seconds and five more at the top of the next minute, ten requests in two seconds, straight through the seam. A sliding window counts over the last sixty seconds from now, so the seam has nowhere to hide. Two algorithms do the counting. A token bucket refills at a steady rate and holds a maximum, and each request spends one token. When the bucket is empty, you are rejected. Saved tokens mean a burst is forgiven. A leaky bucket does the opposite: requests queue and drain at a constant rate, so the output is perfectly smooth and anything overflowing is dropped. And say no properly. Four twenty nine, Too Many Requests, with a Retry-After header telling the client exactly how long to wait. A good client honours that hint, then doubles the wait on every further attempt, and adds jitter, random noise, because a thousand clients that all back off perfectly will retry in the same instant and knock you over again. The limiter is not a punishment. It is the promise that one loud client cannot spend everybody else's capacity.
Based on the board The Bouncer at the Door.
Try it in the lab: The bouncer at the door.
Covered in Rate limiting: the token bucket.
Saved in this browser, and to your account when you sign in.