← All posts

Build a rate limiter: the token bucket in 20 lines

November 25, 2026

Every public API needs a rate limiter. Without one, a single buggy client, a scraper or a retry storm can use up capacity meant for everyone else.

The simplest idea sounds fine: “allow 5 requests per second”. But the obvious way to build it has a hole, and the better way is shorter than you’d expect.

The obvious way: fixed windows

Count requests in each wall-clock second. When the count passes the limit, reject until the next second starts.

class FixedWindow {
  private count = 0;
  private windowStart = 0;

  constructor(private limit: number, private windowMs: number) {}

  tryTake(now: number): boolean {
    if (now - this.windowStart >= this.windowMs) {
      this.windowStart = Math.floor(now / this.windowMs) * this.windowMs;
      this.count = 0;
    }
    if (this.count >= this.limit) return false;
    this.count++;
    return true;
  }
}

The hole: a client sends 5 requests at 900 ms and 5 more at 1100 ms. Each window sees only 5, so all 10 pass. That is 10 requests in 200 ms against a limit of “5 per second”. Clients who time their bursts for the boundary can briefly double your intended load.

The better way: a bucket of tokens

Picture a bucket that holds up to capacity tokens. Tokens drip in at a steady rate. Each request takes one token. No token, no request.

Two numbers describe the whole policy:

  • Refill rate: the long-run average you allow (tokens per second).
  • Capacity: the largest burst you tolerate.
class TokenBucket {
  private tokens: number;
  private last: number;
  private capacity: number;
  private refillPerSec: number;

  constructor(capacity: number, refillPerSec: number, now: number) {
    this.capacity = capacity;
    this.refillPerSec = refillPerSec;
    this.tokens = capacity; // start full
    this.last = now;
  }

  tryTake(now: number, cost = 1): boolean {
    const elapsedSec = (now - this.last) / 1000;
    this.tokens = Math.min(this.capacity, this.tokens + elapsedSec * this.refillPerSec);
    this.last = now;
    if (this.tokens < cost) return false;
    this.tokens -= cost;
    return true;
  }
}

Notice there is no timer and no background job. The bucket doesn’t refill on a schedule. Instead, each call works out how many tokens would have arrived since the last call and adds them. That makes it cheap: two numbers of state per client.

Passing now in, instead of reading the clock inside, is on purpose. It makes the class trivially testable, because your tests control time.

Watching it work

A bucket with capacity 5 and a refill of 1 token per second:

const bucket = new TokenBucket(5, 1, 0);

// 7 requests at t = 0
Array.from({ length: 7 }, () => bucket.tryTake(0));
// true, true, true, true, true, false, false

bucket.tryTake(500);   // false: only half a token has arrived
bucket.tryTake(1000);  // true: a full token has arrived
bucket.tryTake(1000);  // false: spent

// After a long quiet period the bucket refills, but never above capacity
Array.from({ length: 7 }, () => bucket.tryTake(11000));
// true, true, true, true, true, false, false

The last line is the important one: idle time earns you a burst of 5, not 10. The capacity is a hard cap.

Now repeat the boundary trick from before against a bucket with capacity 5 and a refill of 5 per second. Five requests at 900 ms use up the bucket. At 1100 ms only one token has come back, so just one more request passes: 6 in total, not 10.

Choosing the numbers

  • Refill rate = the sustained rate you can afford per client.
  • Capacity = how bursty a well-behaved client is allowed to be. A page that fires 8 calls on load needs a capacity of at least 8, or normal users get rejected.
  • Cost lets expensive calls take more than one token. A search that costs 10 times a lookup can take 10 tokens.

Things that bite in production

1. State has to be shared. One bucket per server means a client talking to 4 servers gets 4 times the limit. Either keep buckets in a shared store (Redis is the usual choice, with the read-modify-write done atomically in a script) or accept the approximation and divide the limit by the number of servers.

2. Pick the key carefully. Per IP punishes offices and mobile carriers behind one address. Per API key is fairer for authenticated traffic. Many systems use both, plus a global bucket as a last line of defence.

3. Tell clients what happened. Return 429 Too Many Requests with a Retry-After header. Good clients back off; without the header they guess, and often guess aggressively.

4. Decide what happens when the limiter itself is down. Failing open keeps the service up but unprotected. Failing closed protects the backend but turns a limiter outage into a full outage. For most APIs, fail open with an alert.

5. Don’t forget to forget. Millions of idle clients means millions of buckets. Drop any bucket that has been full for a while, since a missing bucket and a full one behave the same.

When a token bucket is the wrong tool

  • You need a strict “no more than N in any window”. The bucket allows a burst of capacity and then the steady rate on top, so over a short span it can let through slightly more than the average. A sliding-window log gives exact counts at the cost of storing every timestamp.
  • You’re limiting concurrency, not rate. “At most 10 requests in flight” is a different problem: use a semaphore or a bulkhead, which releases capacity when work finishes, not when time passes.
  • You need fairness between clients. A bucket per client doesn’t stop one busy client from using most of a shared backend. That needs queueing or weighted scheduling.

The short version

A token bucket stores two numbers per client, needs no timers, allows bursts up to a limit you choose, and enforces an average rate. If you only build one rate limiter, build this one.

Go from reading to building

Paren's System Design course covers token buckets, sliding windows and a full rate limiter case study, with code you run in the browser.

Start free