BeginnerLesson 5 of 127 min read

Rate Limits: Staying Inside the Quota with a Token Bucket

Respect an API's rate limit by reading its headers, see what a naive burst does, build a client-side token bucket with a controllable clock, and discover why a bucket that allows a burst can still break a fixed-window limit.

In this lesson you will

  • Read rate limit headers
  • Explain fixed windows and token buckets
  • Build a client-side limiter
  • Choose a pacing that fits the server’s window

About 28 minutes

Forty parcels and a limit of ten

At the end of the day Noor must ask the courier for forty delivery quotes. The courier’s API allows 10 requests per 10-second window and answers 429 Too Many Requests beyond that. Providers set limits to protect their servers and to share capacity fairly, and breaking them can get a key throttled or blocked. A client has three options: ignore the limit and handle the 429 responses, which wastes requests and annoys the provider, slow down by design, or both. Responses often carry headers such as X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset, which the client can use to know where it stands.

A token bucket is the usual client-side tool. Imagine a bucket that holds up to C tokens and receives one new token every 1 / r seconds. Every request takes one token, and if the bucket is empty the client waits until a token arrives. The bucket allows a burst of up to C requests and then a steady rate of r per second. The limiter takes the clock as a parameter, so a test can run in virtual time without waiting. Choosing C and r needs care, because the server’s rule is a fixed window: at most 10 requests in each block of 10 seconds. A bucket with a capacity of 10 and a refill of one per second sounds like the right size, since 10 per 10 seconds is one per second on average, yet in a fixed window it can send its burst of 10 and then another 9 refilled tokens before the window closes: 19 requests in one window. The experiment below shows exactly that.

Strategy Result for 40 requests (limit 10 per fixed 10 s window)
Naive burst 10 succeed, 30 get 429
Bucket: capacity 10, 1 per second Burst then trickle: 19 land in the first window, 9 refused
Bucket: capacity 1, 1 per second All 40 succeed, in 39 seconds
Honour Retry-After after each 429 Works, with wasted requests
import json, threading, urllib.request, urllib.error
from http.server import BaseHTTPRequestHandler, HTTPServer

NOW = [0.0]                                              # the virtual clock shared by server and client
WINDOW, LIMIT = 10, 10
hits = {}
class Courier(BaseHTTPRequestHandler):
    def do_GET(self):
        w = int(NOW[0] // WINDOW); hits[w] = hits.get(w, 0) + 1
        code = 200 if hits[w] <= LIMIT else 429
        b = json.dumps({"ok": code == 200}).encode()
        self.send_response(code); self.send_header("X-RateLimit-Limit", str(LIMIT)); self.send_header("X-RateLimit-Remaining", str(max(0, LIMIT - hits[w])))
        self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)
    def log_message(self, *a): pass
srv = HTTPServer(("127.0.0.1", 0), Courier); url = "http://127.0.0.1:%d/quote" % srv.server_address[1]
threading.Thread(target=srv.serve_forever, daemon=True).start()
def call():
    try: return urllib.request.urlopen(url).status
    except urllib.error.HTTPError as e: return e.code

class TokenBucket:
    def __init__(self, capacity, per_second, clock):
        self.cap, self.rate, self.clock, self.tokens, self.last = capacity, per_second, clock, float(capacity), clock[0]
    def take(self):
        self._refill()
        if self.tokens < 1:
            self.clock[0] += (1 - self.tokens) / self.rate      # a real client would sleep here
            self._refill()
        self.tokens -= 1
    def _refill(self):
        self.tokens = min(self.cap, self.tokens + (self.clock[0] - self.last) * self.rate); self.last = self.clock[0]

def run(capacity, rate, n=40):
    hits.clear(); NOW[0] = 100.0                         # a window boundary in virtual time
    bucket = TokenBucket(capacity, rate, NOW); start = NOW[0]; res = []; times = []
    for _ in range(n):
        bucket.take(); res.append(call()); times.append(NOW[0] - start)
    return res, times, dict(sorted(hits.items()))

hits.clear(); NOW[0] = 100.0
naive = [call() for _ in range(40)]
print("naive burst              : ok =", naive.count(200), "| 429 =", naive.count(429))
r1, t1, w1 = run(10, 1.0)
print("bucket capacity 10, 1/s  : ok =", r1.count(200), "| 429 =", r1.count(429), "| virtual time", t1[-1], "s | requests per window", list(w1.values()))
r2, t2, w2 = run(1, 1.0)
print("bucket capacity 1, 1/s   : ok =", r2.count(200), "| 429 =", r2.count(429), "| virtual time", t2[-1], "s | requests per window", list(w2.values()))
print("DATA " + json.dumps({"naive": [naive.count(200), naive.count(429)], "b10": [r1.count(200), r1.count(429), t1[-1], list(w1.values())], "b1": [r2.count(200), r2.count(429), t2[-1], list(w2.values())], "t1": t1, "t2": t2}))
srv.shutdown()
naive burst              : ok = 10 | 429 = 30
bucket capacity 10, 1/s  : ok = 31 | 429 = 9 | virtual time 30.0 s | requests per window [19, 10, 10, 1]
bucket capacity 1, 1/s   : ok = 40 | 429 = 0 | virtual time 39.0 s | requests per window [10, 10, 10, 10]

The simulated courier counts requests per fixed 10-second window and refuses anything above 10. A naive client that sent all forty quote requests at once got 10 successes and 30 refusals with status 429: three quarters of its work was wasted, and a provider that logs the abuse might throttle the key. The second run used a token bucket with a capacity of 10 and a refill of one per second, which looks like exactly the quota. It was not: the first 10 requests went at once, as the full bucket allows, and then one more was sent each second until the window closed, so the server saw 19 requests in the first window, of which only 10 were accepted. The bucket got 31 successes and 9 refusals, and finished at 30 seconds of virtual time.

The third run used a bucket with a capacity of 1 and one token per second, which means one request per second with no burst. The server saw [10, 10, 10, 10] requests per window, never more than 10, and all 40 requests succeeded with 0 refusals, taking 39 seconds. The difference between the two buckets is the whole lesson. A token bucket guarantees a rate over time, but a fixed-window server counts requests per window, and a burst at the start of a window plus the refill during it exceeds the window’s count. If the server used a sliding window, the first bucket would have been fine. Always read how the provider counts, and when in doubt pace evenly with a small capacity, and use the X-RateLimit-Remaining header, which the server sends with every reply, to check your estimate against the server’s.

Independent check: the completion time of every request was predicted by a formula and not by running the limiter: with capacity C and refill rate r, request number i can go out at time max(0, (i – C) / r). Counting those predicted times per 10-second window gives 19, 10, 10 and 1 for the first bucket and 10, 10, 10 and 10 for the second, and the counts and finishing times from the run agree with the formula for all forty requests in both cases. The accepted requests are then the sum over windows of the smaller of the count and 10, 10 + 10 + 10 + 1 = 31, which equals the 31 successes observed. The virtual clock makes the check exact, and with a real clock, small delays would be added, so a real limiter uses a monotonic clock and a safety margin.

Check by hand for the capacity-1 bucket: the 40 requests go out at 0, 1, 2 and so on up to 39 seconds, so each block of 10 seconds holds exactly 10 requests, and the whole batch takes 39 seconds. For the capacity-10 bucket, 10 requests go at time 0 and the 11th to the 19th go at seconds 1 to 9 of the same window, which makes 19 requests in the window that holds the burst.

A burst allowance can break a fixed window

A bucket that allows a burst of the full quota and then refills continuously can send nearly twice the quota in one window. Match the limiter to the way the provider counts, or give it a small capacity.

Share one limiter per credential

If several threads or processes use the same API key, they share its quota. Put one limiter in front of all of them, or split the quota between them in advance.

About this course

Every program in this lesson was run while the course was written, with Python 3.13 (standard library only) against small mock APIs that the lesson itself starts on a local port, and cross-checked with curl, OpenSSL, Node.js or a second calculation. The services are invented stand-ins, not real vendors: always read the current documentation of the real API you use. Providers define limits in different ways, such as per second, per day or per endpoint, and some use sliding windows or token buckets of their own. Check the documentation for the exact rules.

Practice

Change the server to a sliding window and run the capacity-10 bucket again. Predict, with the formula, how many requests a bucket of capacity 5 and rate 2 per second gets accepted in the first window, then run it. Read X-RateLimit-Remaining and slow down when it falls below 2.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does a token bucket allow?

  1. Only a steady rate
  2. A burst up to its capacity, then a steady rate
  3. Only bursts
  4. No requests

Capacity and refill rate.

What does HTTP 429 mean?

  1. Too many requests
  2. Not found
  3. Bad key
  4. Server error

Look for Retry-After.

Why did the bucket with capacity 10 get refused?

  1. Burst plus refill sent 19 requests in one fixed window
  2. The server was down
  3. The clock was wrong
  4. Tokens expired

The window counts requests, not rate.

How long do 40 requests take at one per second with no burst?

  1. 40 seconds
  2. 10 seconds
  3. 4 seconds
  4. 39 seconds

39 gaps.

Why pass the clock into the limiter?

  1. It is faster
  2. It is required by HTTP
  3. To use less memory
  4. A test can run in virtual time

No waiting in tests.

Summary

  • Respect the quota: read the limit headers.
  • A token bucket allows a burst and then a steady rate.
  • A burst plus refill can exceed a fixed window: match the pacing to the provider.
  • Use a controllable clock so that limiters can be tested.

Next lesson

Lesson 6 covers pagination when consuming an API.

Questions

What is the difference between a fixed window and a sliding window?

A fixed window resets at set times, so a burst at the end of one window and the start of the next can double the rate for a moment. A sliding window counts the last N seconds at every moment and is smoother.

Are rate limits per key or per address?

Either, depending on the provider. Read the documentation, and do not try to bypass limits with many keys, which usually breaks the terms of service.

How do I know the quota?

From the documentation, the plan you pay for and the rate limit headers of responses.

Progress is saved in this browser.