Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

System Design (High-Level Design)  Module 20 – Building blocks: control, safety and platform services

Rate-limiting algorithms compared

How token bucket, leaky bucket, fixed window, sliding log and sliding window counter limiters treat bursts, what each stores, and which to use for an API.

  • Intermediate
  • 35 minutes
  • Examples run with Python 3.14.8, Pyodide 314.0.7, Node.js 24.21.0 and quickjs 0.32.0
  • By MySmartCoPilot
Free: 35 minutes

What you will learn

  • Implement token bucket, leaky bucket, fixed window, sliding log and sliding window counter limiters
  • Compare their burst behaviour, memory and accuracy on the same traffic
  • Choose an algorithm, a key and the numbers for a given API
  • Send 429 responses that tell a client when to retry, with Retry-After and the RateLimit fields

Before you start

A rate limiter answers one question for every request: has this client used up its allowance? If it has not, the request goes on; if it has, the request is refused at once with 429 Too Many Requests, or held back until it fits. Five algorithms do almost all of this work. A A rate limiter that holds up to b tokens and gains r tokens a second. Each request takes a token, so a burst of up to b passes at once, and any T seconds carry at most b + r × T requests. allows bursts up to a set size and a steady rate after that. A A rate limiter that queues requests and lets them out at a steady r a second, refusing those that find b already waiting: the service sees an even stream, and bursts become waiting time. queues requests and lets them out at an even pace. A A rate limiter that counts requests per clock window, such as each minute, and starts again at zero when the next window begins. counts requests per clock second or minute, which is cheap, but lets up to twice the limit through at a window’s edge. A A rate limiter that keeps the time of every request it allowed in the last window, and allows a request while fewer than the limit remain. keeps a timestamp for every request and is exact. A A rate limiter that keeps the counts of the current fixed window and the previous one, and estimates the last full window from them. estimates a sliding window from two counts. This lesson builds all five, runs them on the same traffic, measures how far each strays from its limit and what it stores, and ends with how to choose one and how to tell clients they were limited.

A limiter decides from a key, a cost, a limit and the time

Every limiter works from the same inputs. The key says whose allowance a request uses: an API key, a user, an account, a tenant or a network address. The cost says how much of it the request uses, usually 1, though an expensive search may cost more than a cheap read. The limit is a rate, often with a burst size, and the time is when the request arrives. The answer is allow or refuse, or, for a leaky bucket, a later moment at which the request may go on.

Limits exist for four reasons, and the reason decides which algorithm fits. They protect capacity, so that one client’s surge cannot use up servers that everyone shares. They share capacity fairly between clients who pay for the same service. They cap costs that grow with every request, such as a text message sent for every one-time code or a call to a paid service. And they slow abuse: password guessing, scraping and spam.

The figure follows one request past the three layers that can limit it, and the answer a refused request gets:

A request passes an edge proxy, an API gateway and a service before a database; each limits by what it knows, and refusals return 429.Clientan app, a script or a partnerEdge proxyper address: floods stop hereAPI gatewayper API key: rate and burstServiceper endpoint: requests in progress;sheds load when overloadedDatabase or partner APIsent work at a pace it can takerequests429 Too Many RequestsRetry-After: 2

Limits along one request's path

Text description of the diagram

The diagram shows one request's path from top to bottom, and the limit each layer applies.

  1. The client, which may be an app, a script or a partner's system, sends requests.
  2. The edge proxy limits per network address, so that floods stop before they reach anything expensive.
  3. The API gateway limits per API key, with a rate and a burst size.
  4. The service limits the requests in progress per endpoint, and sheds load when it is overloaded.
  5. The database or partner API at the end is sent work at a pace it can take.

A dashed arrow goes from the API gateway back to the client: a refused request gets the answer 429 Too Many Requests with a Retry-After field, here 2 seconds.

Each layer limits by what it knows. An edge proxy sees only network addresses, so it can stop a flood but cannot tell one customer from another. The API gateway: A reverse proxy in front of many APIs that does the work they all share before a request reaches a service: it checks who is calling, applies rate and size limits, and routes by path. More in “Forward proxies, reverse proxies and gateways” knows the API key and can enforce what each customer bought. The service knows which endpoints are expensive and how busy it is. Limits near the client are cheap and coarse; limits near the work are precise.

A rate limit is also only one kind of limit. Stripe’s engineering blog describes four that run together on its API: a request rate limiter per user, a limiter on how many requests each user has in progress at once, and two load shedding: Refusing excess work quickly and cheaply when a server nears its capacity, ideally the least important work first, so that the requests it does accept are still answered in time. More in “Load shedding, backpressure and degradation” that look at the whole system instead of one user. One of them keeps capacity back for critical requests, and the other drops the least important traffic when workers run short (Stripe). The first two decide by a client’s allowance, the shedders by the state of the servers. A limit on requests in progress is a rate limit in another form: by Little’s law, 20 searches a second that take 3 seconds each keep 60 in progress.

Checkpoint

Check: What a limiter decides, and why

  1. Question 1 of 2 A flood of anonymous requests hits your sign-up page, and the edge proxy must stop it before it reaches anything expensive. Which key can the edge proxy limit by?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The network address, with a loose limit, because many people can share one address

    Each layer limits by what it knows. The edge proxy sees network addresses, so it can stop a flood by address, but it cannot tell one customer from another, and a limit on an address must be loose because many people may share it.

  2. Question 2 of 2 An export endpoint receives 25 requests a second, and each export takes 2 seconds. By Little's law, how many exports are in progress at once?

    Type a number.

    A hint

    Requests in progress equal the arrival rate times the time each one takes.

    Show the answer: Question 2 of 2

    Answer: 50 exports

    L = λW = 25 a second × 2 s = 50 in progress. A limit of 25 starts a second therefore also allows 50 at once; a limit on requests in progress, such as Stripe's, caps that number directly.

A token bucket lets a saved burst through, then a steady rate

All five limit one key at a time; a real limiter keeps one copy of this state per key, in a table or a key-value store. The code is the version this lesson runs. Time comes in as an argument, in whole milliseconds, so the same requests always get the same decisions, and every comparison uses whole numbers, so rounding never changes a decision. A service would pass in a monotonic clock: A clock that only measures elapsed time, for timeouts, leases and durations, rather than telling the time of day. More in “Clocks and ordering: Lamport, vector and HLC” instead of the time of day: Python’s time.monotonic never runs backwards, and correcting the computer’s time does not move it (Python documentation).

A token bucket holds up to b tokens and gains r tokens a second. Every request takes a token, and a request that finds the bucket empty is refused. This one starts full, so a client that has been quiet can send a burst of b requests at once, and after that it gets r a second. Over any stretch of T seconds, a token bucket lets through at most

b+r×Tb + r \times T

requests: what the bucket held at the start plus what T seconds earned. That bound is what you promise a client, and what the service behind the limiter must be sized for.

No timer adds the tokens. Each request first adds what the time since the previous request earned, up to b, then takes its token. So the state per key is two numbers: the tokens, and the time they were last brought up to date.

A token bucket: r tokens a second drip into a bucket of up to b; a request takes one, or is refused if none is left.r tokensadded a secondBucket:up to b tokensA request takes a tokenand goes on at once.No token left: refusedtokens drip in

Token bucket: the tokens drip, the requests pass at once

Text description of the diagram

The diagram shows a token bucket from top to bottom.

  1. Tokens are added at r a second.
  2. They drip into the bucket, which holds up to b tokens. Tokens that arrive when it is full are lost.
  3. A request takes a token and goes on at once. If no token is left, the request is refused.

Because the tokens are saved up while the client is quiet, up to b requests can pass at once.

Here is that bucket as a program: 10 tokens, 5 more a second, a burst of 14 at 0 ms, then a request every 100 ms:

One program · 14 languages A token bucket of 10 tokens that gains 5 a second O(1) a request, two numbers per key

Python 3.14 · main.py

class TokenBucket:
    """Up to `capacity` tokens, refilled at `rate` tokens a second."""

    def __init__(self, rate: int, capacity: int, now_ms: int) -> None:
        self.rate = rate
        self.capacity = capacity
        # Thousandths of a token keep every number whole; a new bucket is full.
        self.milli = capacity * 1000
        self.at = now_ms

    def refill(self, now_ms: int) -> None:
        # No timer runs: each call adds what the time since the last call earned.
        if now_ms > self.at:
            self.milli = min(
                self.capacity * 1000, self.milli + (now_ms - self.at) * self.rate
            )
            self.at = now_ms

    def allow(self, now_ms: int) -> bool:
        self.refill(now_ms)
        if self.milli >= 1000:
            self.milli -= 1000
            return True
        return False

    def retry_after_ms(self, now_ms: int) -> int:
        self.refill(now_ms)
        missing = 1000 - self.milli
        return 0 if missing <= 0 else (missing + self.rate - 1) // self.rate


bucket = TokenBucket(rate=5, capacity=10, now_ms=0)
print("A bucket of 10 tokens that gains 5 a second")
allowed = sum(bucket.allow(0) for _ in range(14))
print(
    f"     0 ms  a burst of 14: {allowed} allowed, {14 - allowed} refused,"
    f" retry after {bucket.retry_after_ms(0)} ms"
)
for now in range(100, 1100, 100):
    if bucket.allow(now):
        allowed += 1
        print(f"{now:>6} ms  allowed")
    else:
        print(f"{now:>6} ms  refused, retry after {bucket.retry_after_ms(now)} ms")
print(
    f"Allowed from 0 to 1,000 ms: {allowed} = 10 for the burst + 5 earned in one second"
)

In Python: sum() counts the requests the burst let through, because True is 1 in Python, and // keeps the wait a whole number of milliseconds, where / would give a float.

Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py

JavaScript Node 24 · main.mjs

// Up to `capacity` tokens, refilled at `rate` tokens a second.
class TokenBucket {
  constructor(rate, capacity, nowMs) {
    this.rate = rate;
    this.capacity = capacity;
    // Thousandths of a token keep every number whole; a new bucket is full.
    this.milli = capacity * 1000;
    this.at = nowMs;
  }

  refill(nowMs) {
    // No timer runs: each call adds what the time since the last call earned.
    if (nowMs > this.at) {
      this.milli = Math.min(this.capacity * 1000, this.milli + (nowMs - this.at) * this.rate);
      this.at = nowMs;
    }
  }

  allow(nowMs) {
    this.refill(nowMs);
    if (this.milli >= 1000) {
      this.milli -= 1000;
      return true;
    }
    return false;
  }

  retryAfterMs(nowMs) {
    this.refill(nowMs);
    const missing = 1000 - this.milli;
    return missing <= 0 ? 0 : Math.ceil(missing / this.rate);
  }
}

const pad = (n) => String(n).padStart(6);
const bucket = new TokenBucket(5, 10, 0);
console.log("A bucket of 10 tokens that gains 5 a second");
let allowed = 0;
for (let i = 0; i < 14; i++) {
  if (bucket.allow(0)) allowed++;
}
console.log(
  `     0 ms  a burst of 14: ${allowed} allowed, ${14 - allowed} refused,` +
    ` retry after ${bucket.retryAfterMs(0)} ms`,
);
for (let now = 100; now <= 1000; now += 100) {
  if (bucket.allow(now)) {
    allowed++;
    console.log(`${pad(now)} ms  allowed`);
  } else {
    console.log(`${pad(now)} ms  refused, retry after ${bucket.retryAfterMs(now)} ms`);
  }
}
console.log(`Allowed from 0 to 1,000 ms: ${allowed} = 10 for the burst + 5 earned in one second`);

In JavaScript: Numbers are doubles, but every value here is a whole number far below 2⁵³, so the arithmetic stays exact; Math.ceil rounds the wait up.

Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs

Java 25 LTS · Main.java

import java.util.Locale;

public class Main {
  /** Up to {@code capacity} tokens, refilled at {@code rate} tokens a second. */
  static final class TokenBucket {
    private final int rate;
    private final int capacity;
    // Thousandths of a token keep every number whole; a new bucket is full.
    private int milli;
    private int at;

    TokenBucket(int rate, int capacity, int nowMs) {
      this.rate = rate;
      this.capacity = capacity;
      this.milli = capacity * 1000;
      this.at = nowMs;
    }

    private void refill(int nowMs) {
      // No timer runs: each call adds what the time since the last call earned.
      if (nowMs > at) {
        milli = Math.min(capacity * 1000, milli + (nowMs - at) * rate);
        at = nowMs;
      }
    }

    boolean allow(int nowMs) {
      refill(nowMs);
      if (milli >= 1000) {
        milli -= 1000;
        return true;
      }
      return false;
    }

    int retryAfterMs(int nowMs) {
      refill(nowMs);
      int missing = 1000 - milli;
      return missing <= 0 ? 0 : (missing + rate - 1) / rate;
    }
  }

  public static void main(String[] args) {
    Locale.setDefault(Locale.ROOT);
    TokenBucket bucket = new TokenBucket(5, 10, 0);
    System.out.println("A bucket of 10 tokens that gains 5 a second");
    int allowed = 0;
    for (int i = 0; i < 14; i++) {
      if (bucket.allow(0)) {
        allowed++;
      }
    }
    System.out.printf(
        "     0 ms  a burst of 14: %d allowed, %d refused, retry after %d ms%n",
        allowed, 14 - allowed, bucket.retryAfterMs(0));
    for (int now = 100; now <= 1000; now += 100) {
      if (bucket.allow(now)) {
        allowed++;
        System.out.printf("%6d ms  allowed%n", now);
      } else {
        System.out.printf("%6d ms  refused, retry after %d ms%n", now, bucket.retryAfterMs(now));
      }
    }
    System.out.printf(
        "Allowed from 0 to 1,000 ms: %d = 10 for the burst + 5 earned in one second%n", allowed);
  }
}

In Java: printf formats for the default locale, which in some locales means other digits, so main sets Locale.ROOT first; %6d pads the time to six characters.

Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java

C++23 · main.cpp

#include <algorithm>
#include <print>

// Up to `capacity` tokens, refilled at `rate` tokens a second.
class TokenBucket {
public:
  TokenBucket(int rate, int capacity, int now_ms)
      : rate_(rate), capacity_(capacity), milli_(capacity * 1000), at_(now_ms) {
  }

  bool allow(int now_ms) {
    refill(now_ms);
    if (milli_ >= 1000) {
      milli_ -= 1000;
      return true;
    }
    return false;
  }

  int retry_after_ms(int now_ms) {
    refill(now_ms);
    const int missing = 1000 - milli_;
    return missing <= 0 ? 0 : (missing + rate_ - 1) / rate_;
  }

private:
  void refill(int now_ms) {
    // No timer runs: each call adds what the time since the last call earned.
    if (now_ms > at_) {
      milli_ = std::min(capacity_ * 1000, milli_ + (now_ms - at_) * rate_);
      at_ = now_ms;
    }
  }

  int rate_;
  int capacity_;
  // Thousandths of a token keep every number whole; a new bucket is full.
  int milli_;
  int at_;
};

int main() {
  TokenBucket bucket(5, 10, 0);
  std::println("A bucket of 10 tokens that gains 5 a second");
  int allowed = 0;
  for (int i = 0; i < 14; ++i) {
    if (bucket.allow(0)) {
      ++allowed;
    }
  }
  std::println(
      "     0 ms  a burst of 14: {} allowed, {} refused, retry after {} ms",
      allowed, 14 - allowed, bucket.retry_after_ms(0));
  for (int now = 100; now <= 1000; now += 100) {
    if (bucket.allow(now)) {
      ++allowed;
      std::println("{:>6} ms  allowed", now);
    } else {
      std::println("{:>6} ms  refused, retry after {} ms", now,
                   bucket.retry_after_ms(now));
    }
  }
  std::println("Allowed from 0 to 1,000 ms: {} = 10 for the burst + 5 earned "
               "in one second",
               allowed);
}

In C++: The data members end in an underscore, a common C++ convention, and std::println's {:>6} right-aligns the time as Python's format does.

Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main

C# 14 · .NET 10 · app.cs

using System.Globalization;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

var bucket = new TokenBucket(5, 10, 0);
Console.WriteLine("A bucket of 10 tokens that gains 5 a second");
int allowed = 0;
for (int i = 0; i < 14; i++)
{
    if (bucket.Allow(0))
    {
        allowed++;
    }
}
Console.WriteLine(
    $"     0 ms  a burst of 14: {allowed} allowed, {14 - allowed} refused,"
    + $" retry after {bucket.RetryAfterMs(0)} ms");
for (int now = 100; now <= 1000; now += 100)
{
    if (bucket.Allow(now))
    {
        allowed++;
        Console.WriteLine($"{now,6} ms  allowed");
    }
    else
    {
        Console.WriteLine($"{now,6} ms  refused, retry after {bucket.RetryAfterMs(now)} ms");
    }
}
Console.WriteLine(
    $"Allowed from 0 to 1,000 ms: {allowed} = 10 for the burst + 5 earned in one second");

// Up to capacity tokens, refilled at rate tokens a second.
sealed class TokenBucket
{
    private readonly int _rate;
    private readonly int _capacity;
    // Thousandths of a token keep every number whole; a new bucket is full.
    private int _milli;
    private int _at;

    public TokenBucket(int rate, int capacity, int nowMs)
    {
        _rate = rate;
        _capacity = capacity;
        _milli = capacity * 1000;
        _at = nowMs;
    }

    public bool Allow(int nowMs)
    {
        Refill(nowMs);
        if (_milli >= 1000)
        {
            _milli -= 1000;
            return true;
        }
        return false;
    }

    public int RetryAfterMs(int nowMs)
    {
        Refill(nowMs);
        int missing = 1000 - _milli;
        return missing <= 0 ? 0 : (missing + _rate - 1) / _rate;
    }

    private void Refill(int nowMs)
    {
        // No timer runs: each call adds what the time since the last call earned.
        if (nowMs > _at)
        {
            _milli = Math.Min(_capacity * 1000, _milli + (nowMs - _at) * _rate);
            _at = nowMs;
        }
    }
}

In C#: {now,6} pads the time inside the interpolated string, and the culture is set to the invariant one first, so no number is formatted by local custom.

Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs

C23 · main.c

#include <stdbool.h>
#include <stdio.h>

// Up to `capacity` tokens, refilled at `rate` tokens a second.
typedef struct {
  int rate;
  int capacity;
  // Thousandths of a token keep every number whole; a new bucket is full.
  int milli;
  int at;
} TokenBucket;

static TokenBucket bucket_new(int rate, int capacity, int now_ms) {
  return (TokenBucket){.rate = rate,
                       .capacity = capacity,
                       .milli = capacity * 1000,
                       .at = now_ms};
}

static void refill(TokenBucket *b, int now_ms) {
  // No timer runs: each call adds what the time since the last call earned.
  if (now_ms > b->at) {
    const int milli = b->milli + (now_ms - b->at) * b->rate;
    b->milli = milli < b->capacity * 1000 ? milli : b->capacity * 1000;
    b->at = now_ms;
  }
}

static bool allow(TokenBucket *b, int now_ms) {
  refill(b, now_ms);
  if (b->milli >= 1000) {
    b->milli -= 1000;
    return true;
  }
  return false;
}

static int retry_after_ms(TokenBucket *b, int now_ms) {
  refill(b, now_ms);
  const int missing = 1000 - b->milli;
  return missing <= 0 ? 0 : (missing + b->rate - 1) / b->rate;
}

int main(void) {
  TokenBucket bucket = bucket_new(5, 10, 0);
  printf("A bucket of 10 tokens that gains 5 a second\n");
  int allowed = 0;
  for (int i = 0; i < 14; i++) {
    if (allow(&bucket, 0)) {
      allowed++;
    }
  }
  printf(
      "     0 ms  a burst of 14: %d allowed, %d refused, retry after %d ms\n",
      allowed, 14 - allowed, retry_after_ms(&bucket, 0));
  for (int now = 100; now <= 1000; now += 100) {
    if (allow(&bucket, now)) {
      allowed++;
      printf("%6d ms  allowed\n", now);
    } else {
      printf("%6d ms  refused, retry after %d ms\n", now,
             retry_after_ms(&bucket, now));
    }
  }
  printf("Allowed from 0 to 1,000 ms: %d = 10 for the burst + 5 earned in one "
         "second\n",
         allowed);
  return 0;
}

In C: C has no classes, so the bucket is a struct built with a designated initializer, and every function takes it by pointer.

Recorded with Apple clang 21.0.0 (C23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang -std=c23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.c -o main && ./main

PHP 8.5 · main.php

<?php

declare(strict_types=1);

/** Up to $capacity tokens, refilled at $rate tokens a second. */
final class TokenBucket
{
    // Thousandths of a token keep every number whole; a new bucket is full.
    private int $milli;
    private int $at;

    public function __construct(private int $rate, private int $capacity, int $nowMs)
    {
        $this->milli = $capacity * 1000;
        $this->at = $nowMs;
    }

    public function allow(int $nowMs): bool
    {
        $this->refill($nowMs);
        if ($this->milli < 1000) {
            return false;
        }
        $this->milli -= 1000;
        return true;
    }

    public function retryAfterMs(int $nowMs): int
    {
        $this->refill($nowMs);
        $missing = 1000 - $this->milli;
        return $missing <= 0 ? 0 : intdiv($missing + $this->rate - 1, $this->rate);
    }

    private function refill(int $nowMs): void
    {
        // No timer runs: each call adds what the time since the last call earned.
        if ($nowMs > $this->at) {
            $milli = $this->milli + ($nowMs - $this->at) * $this->rate;
            $this->milli = min($this->capacity * 1000, $milli);
            $this->at = $nowMs;
        }
    }
}

$bucket = new TokenBucket(5, 10, 0);
echo "A bucket of 10 tokens that gains 5 a second\n";
$allowed = 0;
for ($i = 0; $i < 14; $i++) {
    if ($bucket->allow(0)) {
        $allowed++;
    }
}
printf(
    "     0 ms  a burst of 14: %d allowed, %d refused, retry after %d ms\n",
    $allowed,
    14 - $allowed,
    $bucket->retryAfterMs(0),
);
for ($now = 100; $now <= 1000; $now += 100) {
    if ($bucket->allow($now)) {
        $allowed++;
        printf("%6d ms  allowed\n", $now);
    } else {
        printf("%6d ms  refused, retry after %d ms\n", $now, $bucket->retryAfterMs($now));
    }
}
printf("Allowed from 0 to 1,000 ms: %d = 10 for the burst + 5 earned in one second\n", $allowed);

In PHP: Constructor property promotion declares rate and capacity in the parameter list, and intdiv divides whole numbers where / could return a float.

Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. It runs in your browser with php-wasm 0.2.0 (PHP 8.5.2). To run it yourself: php main.php

Rust 1.99 · main.rs

/// Up to `capacity` tokens, refilled at `rate` tokens a second.
struct TokenBucket {
    rate: u32,
    capacity: u32,
    // Thousandths of a token keep every number whole; a new bucket is full.
    milli: u32,
    at: u32,
}

impl TokenBucket {
    fn new(rate: u32, capacity: u32, now_ms: u32) -> Self {
        Self {
            rate,
            capacity,
            milli: capacity * 1000,
            at: now_ms,
        }
    }

    fn refill(&mut self, now_ms: u32) {
        // No timer runs: each call adds what the time since the last call earned.
        if now_ms > self.at {
            self.milli = (self.milli + (now_ms - self.at) * self.rate).min(self.capacity * 1000);
            self.at = now_ms;
        }
    }

    fn allow(&mut self, now_ms: u32) -> bool {
        self.refill(now_ms);
        if self.milli >= 1000 {
            self.milli -= 1000;
            true
        } else {
            false
        }
    }

    fn retry_after_ms(&mut self, now_ms: u32) -> u32 {
        self.refill(now_ms);
        1000u32.saturating_sub(self.milli).div_ceil(self.rate)
    }
}

fn main() {
    let mut bucket = TokenBucket::new(5, 10, 0);
    println!("A bucket of 10 tokens that gains 5 a second");
    let mut allowed = (0..14).filter(|_| bucket.allow(0)).count();
    println!(
        "     0 ms  a burst of 14: {allowed} allowed, {} refused, retry after {} ms",
        14 - allowed,
        bucket.retry_after_ms(0)
    );
    for now in (100..=1000).step_by(100) {
        if bucket.allow(now) {
            allowed += 1;
            println!("{now:>6} ms  allowed");
        } else {
            println!(
                "{now:>6} ms  refused, retry after {} ms",
                bucket.retry_after_ms(now)
            );
        }
    }
    println!("Allowed from 0 to 1,000 ms: {allowed} = 10 for the burst + 5 earned in one second");
}

In Rust: saturating_sub stops the missing tokens at 0 instead of wrapping below zero in a u32, and div_ceil rounds the wait up, so no branch is needed.

Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main

TypeScript 6.0 · main.ts

// Up to `capacity` tokens, refilled at `rate` tokens a second.
class TokenBucket {
  readonly rate: number;
  readonly capacity: number;
  private milli: number;
  private at: number;

  constructor(rate: number, capacity: number, nowMs: number) {
    this.rate = rate;
    this.capacity = capacity;
    // Thousandths of a token keep every number whole; a new bucket is full.
    this.milli = capacity * 1000;
    this.at = nowMs;
  }

  private refill(nowMs: number): void {
    // No timer runs: each call adds what the time since the last call earned.
    if (nowMs > this.at) {
      this.milli = Math.min(this.capacity * 1000, this.milli + (nowMs - this.at) * this.rate);
      this.at = nowMs;
    }
  }

  allow(nowMs: number): boolean {
    this.refill(nowMs);
    if (this.milli >= 1000) {
      this.milli -= 1000;
      return true;
    }
    return false;
  }

  retryAfterMs(nowMs: number): number {
    this.refill(nowMs);
    const missing = 1000 - this.milli;
    return missing <= 0 ? 0 : Math.ceil(missing / this.rate);
  }
}

const pad = (n: number): string => String(n).padStart(6);
const bucket = new TokenBucket(5, 10, 0);
console.log("A bucket of 10 tokens that gains 5 a second");
let allowed = 0;
for (let i = 0; i < 14; i++) {
  if (bucket.allow(0)) allowed++;
}
console.log(
  `     0 ms  a burst of 14: ${allowed} allowed, ${14 - allowed} refused,` +
    ` retry after ${bucket.retryAfterMs(0)} ms`,
);
for (let now = 100; now <= 1000; now += 100) {
  if (bucket.allow(now)) {
    allowed++;
    console.log(`${pad(now)} ms  allowed`);
  } else {
    console.log(`${pad(now)} ms  refused, retry after ${bucket.retryAfterMs(now)} ms`);
  }
}
console.log(`Allowed from 0 to 1,000 ms: ${allowed} = 10 for the burst + 5 earned in one second`);

In TypeScript: The fields are declared above the constructor and set in it, because parameter properties are not erasable syntax and a type-stripping runtime could not run them.

Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts

Go 1.27 · main.go

package main

import "fmt"

// TokenBucket holds up to capacity tokens, refilled at rate tokens a second.
type TokenBucket struct {
	rate     int
	capacity int
	// Thousandths of a token keep every number whole; a new bucket is full.
	milli int
	at    int
}

func NewTokenBucket(rate, capacity, nowMs int) *TokenBucket {
	return &TokenBucket{rate: rate, capacity: capacity, milli: capacity * 1000, at: nowMs}
}

func (b *TokenBucket) refill(nowMs int) {
	// No timer runs: each call adds what the time since the last call earned.
	if nowMs > b.at {
		b.milli = min(b.capacity*1000, b.milli+(nowMs-b.at)*b.rate)
		b.at = nowMs
	}
}

func (b *TokenBucket) Allow(nowMs int) bool {
	b.refill(nowMs)
	if b.milli >= 1000 {
		b.milli -= 1000
		return true
	}
	return false
}

func (b *TokenBucket) RetryAfterMs(nowMs int) int {
	b.refill(nowMs)
	missing := 1000 - b.milli
	if missing <= 0 {
		return 0
	}
	return (missing + b.rate - 1) / b.rate
}

func main() {
	bucket := NewTokenBucket(5, 10, 0)
	fmt.Println("A bucket of 10 tokens that gains 5 a second")
	allowed := 0
	for range 14 {
		if bucket.Allow(0) {
			allowed++
		}
	}
	fmt.Printf("     0 ms  a burst of 14: %d allowed, %d refused, retry after %d ms\n",
		allowed, 14-allowed, bucket.RetryAfterMs(0))
	for now := 100; now <= 1000; now += 100 {
		if bucket.Allow(now) {
			allowed++
			fmt.Printf("%6d ms  allowed\n", now)
		} else {
			fmt.Printf("%6d ms  refused, retry after %d ms\n", now, bucket.RetryAfterMs(now))
		}
	}
	fmt.Printf("Allowed from 0 to 1,000 ms: %d = 10 for the burst + 5 earned in one second\n",
		allowed)
}

In Go: min is built into the language, for range 14 counts the burst, and the methods take a pointer receiver because they change the bucket.

Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go

Swift 6.4 · main.swift

func pad(_ n: Int, to width: Int) -> String {
  let digits = String(n)
  return String(repeating: " ", count: max(0, width - digits.count)) + digits
}

/// Up to `capacity` tokens, refilled at `rate` tokens a second.
struct TokenBucket {
  let rate: Int
  let capacity: Int
  // Thousandths of a token keep every number whole; a new bucket is full.
  private var milli: Int
  private var at: Int

  init(rate: Int, capacity: Int, nowMs: Int) {
    self.rate = rate
    self.capacity = capacity
    milli = capacity * 1000
    at = nowMs
  }

  private mutating func refill(_ nowMs: Int) {
    // No timer runs: each call adds what the time since the last call earned.
    if nowMs > at {
      milli = min(capacity * 1000, milli + (nowMs - at) * rate)
      at = nowMs
    }
  }

  mutating func allow(_ nowMs: Int) -> Bool {
    refill(nowMs)
    guard milli >= 1000 else { return false }
    milli -= 1000
    return true
  }

  mutating func retryAfterMs(_ nowMs: Int) -> Int {
    refill(nowMs)
    let missing = 1000 - milli
    return missing <= 0 ? 0 : (missing + rate - 1) / rate
  }
}

var bucket = TokenBucket(rate: 5, capacity: 10, nowMs: 0)
print("A bucket of 10 tokens that gains 5 a second")
var allowed = 0
for _ in 0..<14 {
  if bucket.allow(0) {
    allowed += 1
  }
}
print(
  "     0 ms  a burst of 14: \(allowed) allowed, \(14 - allowed) refused,"
    + " retry after \(bucket.retryAfterMs(0)) ms")
for now in stride(from: 100, through: 1000, by: 100) {
  if bucket.allow(now) {
    allowed += 1
    print("\(pad(now, to: 6)) ms  allowed")
  } else {
    print("\(pad(now, to: 6)) ms  refused, retry after \(bucket.retryAfterMs(now)) ms")
  }
}
print("Allowed from 0 to 1,000 ms: \(allowed) = 10 for the burst + 5 earned in one second")

In Swift: TokenBucket is a struct, a value type, so the methods that change it are marked mutating and the bucket itself is a var.

Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main

Ruby 4.0 · main.rb

# frozen_string_literal: true

# Up to `capacity` tokens, refilled at `rate` tokens a second.
class TokenBucket
  def initialize(rate, capacity, now_ms)
    @rate = rate
    @capacity = capacity
    # Thousandths of a token keep every number whole; a new bucket is full.
    @milli = capacity * 1000
    @at = now_ms
  end

  def allow(now_ms)
    refill(now_ms)
    return false if @milli < 1000

    @milli -= 1000
    true
  end

  def retry_after_ms(now_ms)
    refill(now_ms)
    missing = 1000 - @milli
    missing <= 0 ? 0 : (missing + @rate - 1) / @rate
  end

  private

  def refill(now_ms)
    # No timer runs: each call adds what the time since the last call earned.
    return unless now_ms > @at

    @milli = [@capacity * 1000, @milli + ((now_ms - @at) * @rate)].min
    @at = now_ms
  end
end

bucket = TokenBucket.new(5, 10, 0)
puts 'A bucket of 10 tokens that gains 5 a second'
allowed = 14.times.count { bucket.allow(0) }
puts "     0 ms  a burst of 14: #{allowed} allowed, #{14 - allowed} refused, " \
     "retry after #{bucket.retry_after_ms(0)} ms"
100.step(1000, 100) do |now|
  if bucket.allow(now)
    allowed += 1
    puts "#{now.to_s.rjust(6)} ms  allowed"
  else
    puts "#{now.to_s.rjust(6)} ms  refused, retry after #{bucket.retry_after_ms(now)} ms"
  end
end
puts "Allowed from 0 to 1,000 ms: #{allowed} = 10 for the burst + 5 earned in one second"

In Ruby: 14.times.count with a block counts the requests the burst let through, and refill returns early with a guard clause, as RuboCop's style prefers.

Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb

Kotlin 2.4 · Main.kt

// Up to `capacity` tokens, refilled at `rate` tokens a second.
class TokenBucket(
    private val rate: Int,
    private val capacity: Int,
    nowMs: Int,
) {
    // Thousandths of a token keep every number whole; a new bucket is full.
    private var milli = capacity * 1000
    private var at = nowMs

    private fun refill(nowMs: Int) {
        // No timer runs: each call adds what the time since the last call earned.
        if (nowMs > at) {
            milli = minOf(capacity * 1000, milli + (nowMs - at) * rate)
            at = nowMs
        }
    }

    fun allow(nowMs: Int): Boolean {
        refill(nowMs)
        if (milli < 1000) return false
        milli -= 1000
        return true
    }

    fun retryAfterMs(nowMs: Int): Int {
        refill(nowMs)
        val missing = 1000 - milli
        return if (missing <= 0) 0 else (missing + rate - 1) / rate
    }
}

fun main() {
    val bucket = TokenBucket(5, 10, 0)
    println("A bucket of 10 tokens that gains 5 a second")
    var allowed = (1..14).count { bucket.allow(0) }
    println(
        "     0 ms  a burst of 14: $allowed allowed, ${14 - allowed} refused, " +
            "retry after ${bucket.retryAfterMs(0)} ms",
    )
    for (now in 100..1000 step 100) {
        val at = now.toString().padStart(6)
        if (bucket.allow(now)) {
            allowed++
            println("$at ms  allowed")
        } else {
            println("$at ms  refused, retry after ${bucket.retryAfterMs(now)} ms")
        }
    }
    println("Allowed from 0 to 1,000 ms: $allowed = 10 for the burst + 5 earned in one second")
}

In Kotlin: The constructor declares rate and capacity as private vals, while nowMs is a plain parameter, used only to set the starting time.

Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar

Dart 3.13 · main.dart

import 'dart:math';

/// Up to `capacity` tokens, refilled at `rate` tokens a second.
class TokenBucket {
  final int rate;
  final int capacity;
  // Thousandths of a token keep every number whole; a new bucket is full.
  int _milli;
  int _at;

  TokenBucket(this.rate, this.capacity, int nowMs)
    : _milli = capacity * 1000,
      _at = nowMs;

  void _refill(int nowMs) {
    // No timer runs: each call adds what the time since the last call earned.
    if (nowMs > _at) {
      _milli = min(capacity * 1000, _milli + (nowMs - _at) * rate);
      _at = nowMs;
    }
  }

  bool allow(int nowMs) {
    _refill(nowMs);
    if (_milli < 1000) return false;
    _milli -= 1000;
    return true;
  }

  int retryAfterMs(int nowMs) {
    _refill(nowMs);
    final missing = 1000 - _milli;
    return missing <= 0 ? 0 : (missing + rate - 1) ~/ rate;
  }
}

void main() {
  final bucket = TokenBucket(5, 10, 0);
  print('A bucket of 10 tokens that gains 5 a second');
  var allowed = 0;
  for (var i = 0; i < 14; i++) {
    if (bucket.allow(0)) allowed++;
  }
  print(
    '     0 ms  a burst of 14: $allowed allowed, ${14 - allowed} refused, '
    'retry after ${bucket.retryAfterMs(0)} ms',
  );
  for (var now = 100; now <= 1000; now += 100) {
    final at = now.toString().padLeft(6);
    if (bucket.allow(now)) {
      allowed++;
      print('$at ms  allowed');
    } else {
      print('$at ms  refused, retry after ${bucket.retryAfterMs(now)} ms');
    }
  }
  print(
    'Allowed from 0 to 1,000 ms: $allowed = 10 for the burst + 5 earned in one second',
  );
}

In Dart: ~/ is integer division, and the initializer list sets the private fields before the constructor body would run.

Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart

What every language printed

A bucket of 10 tokens that gains 5 a second
     0 ms  a burst of 14: 10 allowed, 4 refused, retry after 200 ms
   100 ms  refused, retry after 100 ms
   200 ms  allowed
   300 ms  refused, retry after 100 ms
   400 ms  allowed
   500 ms  refused, retry after 100 ms
   600 ms  allowed
   700 ms  refused, retry after 100 ms
   800 ms  allowed
   900 ms  refused, retry after 100 ms
  1000 ms  allowed
Allowed from 0 to 1,000 ms: 15 = 10 for the burst + 5 earned in one second

The output shows both halves of the behaviour. Ten requests of the burst pass at once and four are refused; then one request in two passes, because a token takes 200 ms to earn. Fifteen passed in the first second, the 10 the bucket held and the 5 the second earned: b + r × T exactly. Every refusal also knows how long the client must wait, which a server sends as Retry-After.

Send bursts of your own, let time pass, and change the size and the rate:

Interactive model Token bucket rate limiter

Send requests one at a time or in a burst, let time pass, and change the bucket size and the refill rate. A request needs one token; without one it is rejected with 429.

At the start: The bucket holds 5 of 5 tokens and gains 1 token a second, so up to 5 requests pass at once and 1 a second keep passing after that. No requests yet.

Widely used systems limit this way. Amazon API Gateway throttles requests with a token bucket in which a token counts for a request, configured by a rate (the tokens added each second) and a burst (the bucket’s capacity), and it describes these limits as targets applied on a best-effort basis rather than guaranteed ceilings (API Gateway documentation). Envoy’s local rate limit filter applies a token bucket too, and answers 429 when it runs out (Envoy documentation). Stripe’s request rate limiter is a token bucket per user, kept in Redis (Stripe).

Key idea

A token bucket promises at most b + r × T requests in any T seconds, the burst it saved plus the rate it earned, and that sum is also what the service behind it must be sized for.

Checkpoint

Check: The token bucket and its bound

  1. Question 1 of 2 A bucket holds at most 10 tokens and gains 5 a second. It was emptied at 0 ms. At 1,400 ms a burst of 20 requests arrives at once. How many of them pass?

    Type a number.

    A hint

    Count what 1.4 seconds earned, and remember the bucket's size.

    Show the answer: Question 1 of 2

    Answer: 7 requests

    1.4 s × 5 tokens a second = 7 tokens, under the size of 10, so 7 requests pass and 13 are refused. The next token arrives 200 ms later.

  2. Question 2 of 2 A bucket that gains 8 tokens a second holds a quarter of a token. How many milliseconds must a client wait before a request of one token can pass, rounded up to a whole millisecond?

    Type a number.

    A hint

    Divide the missing part of a token by the rate.

    Show the answer: Question 2 of 2

    Answer: 94 ms

    The bucket is missing 0.75 of a token, and 0.75 ÷ 8 = 0.09375 s, which is 93.75 ms: 94 ms rounded up. The program in this section computes the same wait in thousandths of a token: (750 + 8 − 1) ÷ 8 = 94 in whole numbers.

A leaky bucket paces requests, and as a meter it is GCRA

A leaky bucket as a queue

A leaky bucket turns the idea around: the requests themselves go into the bucket and leave it at a steady rate, one every 1/r seconds. If b requests are already waiting, a new one is refused. The service behind a leaky bucket never sees a burst; it sees an even stream, and the price is the time requests spend waiting.

A leaky bucket: up to b requests wait and one leaves every 1/r seconds; arrivals that find it full are refused.Requests arriveat any rate.Bucket full: refusedBucket:up to b requests waitingOne leaves every 1/r sfor the servicerequests drip out

Leaky bucket: the requests themselves wait and drip out

Text description of the diagram

The diagram shows a leaky bucket used as a queue, from top to bottom.

  1. Requests arrive at any rate. A request that finds the bucket full is refused.
  2. Up to b requests wait in the bucket.
  3. One request leaves for the service every 1/r seconds: the requests drip out.

The service sees an even stream of requests, whatever the arrivals looked like, and a burst becomes waiting time.

A leaky bucket that lets 5 requests a second out and holds 10 Python · limiters/leaky_bucket.py
# Leaky bucket as a queue: requests wait in the bucket and leave it at a steady `rate` a second, one every
# 1000 / rate ms. At most `size` requests are in the bucket at once; a request that finds it full is refused.
# The service behind it never sees a burst, and the price is the time requests spend waiting.
from collections import deque


class LeakyBucket:
    def __init__(self, rate, size):
        self.gap = 1000 // rate          # ms between two requests leaving (rate must divide 1000)
        self.size = size                 # how many requests may be in the bucket at once
        self.inside = deque()            # when each request still in the bucket leaves it, in order
        self.last_leave = -self.gap      # when the latest request left or will leave

    def offer(self, now_ms):
        """When the request leaves the bucket for the service (ms), or None if the bucket is full."""
        while self.inside and self.inside[0] < now_ms:
            self.inside.popleft()        # it has left already
        if len(self.inside) >= self.size:
            return None
        leave = max(now_ms, self.last_leave + self.gap)
        self.last_leave = leave
        self.inside.append(leave)
        return leave


if __name__ == "__main__":
    bucket = LeakyBucket(rate=5, size=10)
    print("A bucket that lets 5 requests a second out and holds 10")
    leaves = [bucket.offer(0) for _ in range(14)]
    sent = [t for t in leaves if t is not None]
    print(f"A burst of 14 at 0 ms: {len(sent)} accepted, {leaves.count(None)} refused")
    print("They leave at (ms):", ", ".join(str(t) for t in sent))
    print(f"The last accepted request waits {sent[-1]} ms; the service never sees two within 200 ms")
    print(f"At 1,000 ms another arrives and leaves at {bucket.offer(1000)} ms")

Output

A bucket that lets 5 requests a second out and holds 10
A burst of 14 at 0 ms: 10 accepted, 4 refused
They leave at (ms): 0, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800
The last accepted request waits 1800 ms; the service never sees two within 200 ms
At 1,000 ms another arrives and leaves at 2000 ms

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 leaky_bucket.py

The same burst of 14 is treated differently. Ten requests are accepted, but only the first goes on at once; the others leave 200 ms apart, so the tenth waits 1.8 seconds. Four are refused, because the bucket is full. A leaky bucket suits work that can wait but must not arrive in bursts, such as calls to a partner whose contract allows a fixed number a second. It suits interactive requests badly, because a waiting request holds a connection open and keeps a person waiting.

NGINX’s limit_req module describes its method as a leaky bucket. Its documentation says that requests above the configured rate are delayed until their number exceeds the burst size, and then refused with an error; the burst size is zero unless you set one, the nodelay parameter passes the requests within the burst at once instead of delaying them, and refused requests get status 503 unless limit_req_status sets another code (NGINX documentation). For a limit on clients, set it to 429, so that a client can tell its own excess from an overloaded server.

GCRA: a token bucket in one number

A leaky bucket can also work without a queue, as a meter that only decides whether a request conforms and never delays anything. Used that way, it makes the same decisions as a token bucket. ITU-T Recommendation I.371, written for ATM networks, defines this as the A leaky bucket used as a meter, defined in ITU-T I.371: it keeps one number per key and makes the same decisions as a token bucket. and gives two equivalent versions of it: a continuous-state leaky bucket, and a virtual scheduling algorithm that keeps a single number, the theoretical arrival time (ITU-T I.371, Annex A).

The In GCRA, the moment the next request would be due if requests came exactly at the steady rate. is when the next request would be due if requests came exactly at the steady rate. A request may arrive early by up to a tolerance; one that comes earlier still is refused. A tolerance of b − 1 intervals behaves like a bucket of b tokens, and the script checks that on 5,000 bursty requests:

GCRA and the token bucket on 5,000 bursty requests Python · limiters/gcra.py
# GCRA, the generic cell rate algorithm of ITU-T I.371 (Annex A), in its "virtual scheduling" form: a token
# bucket kept as one number per key, the theoretical arrival time (TAT), the moment the next request would be due
# if requests came exactly at the steady rate. A request may come early by up to `tolerance`, which is what lets a
# burst through.
import random

from token_bucket import TokenBucket


class GCRA:
    def __init__(self, rate, burst):
        self.interval = 1000 // rate                     # T: ms between requests at the steady rate
        self.tolerance = (burst - 1) * self.interval     # tau: how early a request may arrive
        self.tat = None                                  # theoretical arrival time of the next request

    def allow(self, now_ms):
        tat = now_ms if self.tat is None else max(self.tat, now_ms)
        if now_ms < tat - self.tolerance:                # too early: the burst allowance is used up
            return False
        self.tat = tat + self.interval
        return True


if __name__ == "__main__":
    rng = random.Random(7)
    times, t = [], 0
    for _ in range(5000):                                # bursty traffic: gaps from 0 to 300 ms
        t += rng.choice([0, 0, 0, 1, 5, 20, 50, 100, 300])
        times.append(t)
    gcra, bucket = GCRA(rate=10, burst=10), TokenBucket(rate=10, capacity=10)
    a = [gcra.allow(x) for x in times]
    b = [bucket.allow(x) for x in times]
    same = sum(x == y for x, y in zip(a, b))
    print(f"{len(times)} requests over {times[-1] / 1000:.1f} s; GCRA allowed {sum(a)}, the token bucket {sum(b)}")
    print(f"Same decision for {same} of {len(times)} requests")
    print(f"State per key: GCRA keeps 1 number (TAT = {gcra.tat} ms), the token bucket 2"
          f" ({bucket.milli / 1000:g} tokens at {bucket.at} ms)")

Output

5000 requests over 253.2 s; GCRA allowed 2535, the token bucket 2535
Same decision for 5000 of 5000 requests
State per key: GCRA keeps 1 number (TAT = 253937 ms), the token bucket 2 (2.69 tokens at 253206 ms)

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 gcra.py

Every decision agrees, and GCRA stores half as much: one timestamp per key instead of a count and a timestamp. With millions of keys, half the state is worth having.

Here is the one number at work on a smaller case: 5 requests a second, so one is due every 200 ms, and a burst of 3, so the tolerance is 400 ms. Step through seven requests:

Interactive · step by step GCRA keeps one number per client Step through seven requests at a meter that allows 5 a second and a burst of 3, and watch its one number move.
GCRA keeps one number per client, step 9 of 9. Showing Client, GCRA meter (TAT 1,000 ms), Service (received 5). In focus: GCRA meter, Service.ClientGCRA meterTAT 1,000 msServicereceived 5

The drawing shows the whole scene; its 9 steps are listed below.

Every step as text
  1. The settings. The meter allows 5 requests a second, so one is due every 200 ms, and a burst of 3, so a request may arrive up to 400 ms before it is due. It keeps one number, the theoretical arrival time (TAT), when the next request is due at the steady rate.
  2. Request 1 at 0 ms. There is no TAT yet, so the first request counts as due now. It passes, and the TAT moves on by one interval, to 200 ms.
  3. Request 2 at 0 ms. The second request arrives 200 ms before it is due. That is inside the 400 ms tolerance, so it passes, and the TAT becomes 400 ms.
  4. Request 3 at 0 ms. The third is 400 ms early, exactly the tolerance, so it passes too and the TAT becomes 600 ms. Three requests at once are the burst of 3.
  5. Request 4 at 0 ms. The fourth would be 600 ms early, more than the 400 ms allowed. It is refused, and a refusal changes nothing, so the TAT stays at 600 ms.
  6. Request 5 at 100 ms. At 100 ms a request is still 500 ms early, so it is refused as well. Requests can pass again from 200 ms, the TAT minus the tolerance.
  7. Request 6 at 200 ms. At 200 ms a request is exactly 400 ms early, so it passes and the TAT moves to 800 ms. After the burst, one request every 200 ms passes, the steady rate.
  8. Request 7 at 600 ms. At 600 ms a request is only 200 ms early, so it passes and the TAT becomes 1,000 ms. In those 400 ms the meter gave back two requests' worth of tolerance, as a token bucket earns two tokens.
  9. One number. Seven requests, five passed, and the meter stored one number the whole time. A token bucket of 3 tokens that earns 5 a second makes the same seven decisions with two numbers.

Three requests at 0 ms pushed the theoretical arrival time to 600 ms, so the fourth, 600 ms early, was refused and changed nothing; from 200 ms on, the steady rate took over.

Checkpoint

Check: The leaky bucket and GCRA

  1. Question 1 of 2 A leaky bucket lets 4 requests a second out and holds 8. A burst of 10 arrives at 0 ms. At what time, in milliseconds, does the last accepted request leave for the service?

    Type a number.

    A hint

    One request leaves every 1,000 ÷ 4 ms, the first at once.

    Show the answer: Question 1 of 2

    Answer: 1750 ms

    8 requests are accepted and 2 refused. They leave 250 ms apart, at 0, 250, 500 and so on, so the eighth leaves at 7 × 250 = 1,750 ms. The service never sees two requests closer than 250 ms, and the eighth request waited 1.75 s for that.

  2. Question 2 of 2 A GCRA meter expects one request every 100 ms and allows a tolerance of 300 ms. Its theoretical arrival time is now 1,000 ms. What is the earliest time, in milliseconds, at which the next request passes?

    Type a number.

    A hint

    A request may arrive up to the tolerance before it is due.

    Show the answer: Question 2 of 2

    Answer: 700 ms

    A request passes when it arrives no earlier than the theoretical arrival time minus the tolerance: 1,000 − 300 = 700 ms. One at 650 ms is refused and leaves the time at 1,000 ms; one at 700 ms passes and moves it to 1,100 ms.

A fixed window lets twice the limit through at its edge

A fixed window counts the requests of the current window, such as the current clock second or minute, refuses once the count reaches the limit, and starts again at zero when the next window begins. It is the cheapest algorithm to run on a shared store: one counter per key and window, increased once per request and thrown away with its window.

Twenty requests at the edge of a window Python · limiters/fixed_window.py
# Fixed window: one counter per window of `window_ms` (each starts at a multiple of window_ms, the way
# "per minute" usually means "per clock minute"). Up to `limit` requests pass in each window.


class FixedWindow:
    def __init__(self, limit, window_ms):
        self.limit = limit
        self.window = window_ms
        self.current = None              # which window the count belongs to
        self.count = 0                   # requests allowed in it

    def allow(self, now_ms):
        w = now_ms // self.window
        if w != self.current:            # a new window: start counting again
            self.current, self.count = w, 0
        if self.count < self.limit:
            self.count += 1
            return True
        return False


if __name__ == "__main__":
    limiter = FixedWindow(limit=10, window_ms=1000)
    times = list(range(900, 1000, 10)) + list(range(1000, 1100, 10))   # 10 just before 1 s, 10 just after
    allowed = [t for t in times if limiter.allow(t)]
    print("A limit of 10 a second, counted in fixed windows of 1,000 ms")
    print(f"{len(times)} requests from {times[0]} to {times[-1]} ms: {len(allowed)} allowed")
    print(f"So {len(allowed)} requests passed within {allowed[-1] - allowed[0]} ms, twice the limit")

Output

A limit of 10 a second, counted in fixed windows of 1,000 ms
20 requests from 900 to 1090 ms: 20 allowed
So 20 requests passed within 190 ms, twice the limit

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 fixed_window.py

Its weakness is the edge. A client that spends its whole allowance at the end of one window and again at the start of the next gets twice the limit through in a moment: here, 20 requests within 190 ms against a limit of 10 a second. A second weakness affects every client at once. All windows start again at the same instant, so clients that were refused, and jobs scheduled for the start of a minute, all come back together.

Cron Expression Generator & Explainer Scheduling your own batch jobs against someone else's API? Pick an odd minute rather than the hour or a round number, and let each job wait a few random seconds before it starts.

A sliding log is exact and keeps a time per request

A sliding log keeps the time of every request it allowed during the last window. Before it decides, it drops the times that are older than one window; then it allows the request if fewer than the limit remain. No span of one window ever holds more than the limit, wherever the span starts, so the edge problem cannot happen.

The same twenty requests against a log Python · limiters/sliding_log.py
# Sliding log: keep the time of every request allowed in the last `window_ms`. A request passes while fewer than
# `limit` are in the log, so no span of `window_ms` ever holds more than `limit` allowed requests. Exact, and the
# memory grows with the limit: one timestamp for every request it allows.
from collections import deque


class SlidingLog:
    def __init__(self, limit, window_ms):
        self.limit = limit
        self.window = window_ms
        self.log = deque()               # times of the allowed requests still inside the window, oldest first

    def allow(self, now_ms):
        while self.log and self.log[0] <= now_ms - self.window:
            self.log.popleft()           # older than the window: it no longer counts
        if len(self.log) < self.limit:
            self.log.append(now_ms)
            return True
        return False


if __name__ == "__main__":
    limiter = SlidingLog(limit=10, window_ms=1000)
    times = list(range(900, 1000, 10)) + list(range(1000, 1100, 10))   # the same 20 requests
    allowed = [t for t in times if limiter.allow(t)]
    print("A limit of 10 in any 1,000 ms, kept as a log of timestamps")
    print(f"{len(times)} requests from {times[0]} to {times[-1]} ms: {len(allowed)} allowed")
    print(f"The log holds {len(limiter.log)} timestamps; the oldest, {limiter.log[0]} ms, leaves the window"
          f" at {limiter.log[0] + 1000} ms")
    print(f"A request at 1,899 ms: {'allowed' if limiter.allow(1899) else 'refused'};"
          f" at 1,900 ms: {'allowed' if limiter.allow(1900) else 'refused'}")

Output

A limit of 10 in any 1,000 ms, kept as a log of timestamps
20 requests from 900 to 1090 ms: 10 allowed
The log holds 10 timestamps; the oldest, 900 ms, leaves the window at 1900 ms
A request at 1,899 ms: refused; at 1,900 ms: allowed

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 sliding_log.py

The same 20 requests now get 10 through, and the next request must wait until the oldest time leaves the window: it is refused at 1,899 ms and allowed at 1,900 ms. The price is memory. The log holds a timestamp for every request in the window, so a limit of 1,000 an hour means up to 1,000 timestamps for each busy key. A double-ended queue keeps the work per request small, because a deque appends and pops at either end in roughly constant time (Python documentation), but it does not make the log any smaller.

Step through the same 20 requests against both counters, and watch what each one remembers when the clock reaches 1,000 ms:

Interactive · step by step Twenty requests at a window edge, two counters Step through the same 20 requests against a fixed window and a sliding log, both allowing 10 a second.
Twenty requests at a window edge, two counters, step 7 of 7. Showing One client, Fixed window (window 1: 10 of 10), Sliding log (10 times kept). In focus: Fixed window, Sliding log.One client900 to 1,090 msFixed windowwindow 1: 10 of 10Sliding log10 times kept

The drawing shows the whole scene; its 7 steps are listed below.

Every step as text
  1. Twenty requests. One client sends ten requests from 900 to 990 ms and ten from 1,000 to 1,090 ms. Both limiters allow 10 a second; the fixed window counts per clock second, the log counts any 1,000 ms.
  2. The first ten, fixed. The first ten all fall in the window that started at 0 ms. The fixed window allows them all, and its count reaches 10 of 10.
  3. The first ten, log. The log allows the same ten and keeps their ten times. So far both counters agree, 10 in the last 1,000 ms.
  4. A new window. At 1,000 ms a new clock second begins, and the fixed window's count starts again at 0, although the ten requests it just allowed are only 10 to 100 ms old.
  5. The next ten, fixed. The next ten, from 1,000 to 1,090 ms, all pass the fixed window. Twenty requests got through within 190 ms, twice the limit.
  6. The next ten, log. The log still holds ten times from the last 1,000 ms, so it refuses all ten. Its oldest time, 900 ms, leaves the window at 1,900 ms, and only then can another request pass.
  7. What each remembers. The same limit and the same requests let 20 through one counter and 10 through the other. The difference is what each one remembers, a count per window or a time per request.

Checkpoint

Check: The fixed window and its edge · The sliding log

  1. Question 1 of 2 Your API counts each customer's requests in fixed windows of one clock minute. Forty seconds into a minute, hundreds of customers have used their allowance and are refused. What happens at the start of the next minute?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Every refused customer's count starts again at 0 at the same instant, so their retries and their scheduled jobs arrive together

    A fixed window forgets its count at the boundary, and every customer's window has the same boundary. Clients that were refused, and jobs scheduled for the start of a minute, all come back together, which is why scheduled jobs do better on an odd minute with a random wait.

  2. Question 2 of 2 A sliding log allows 5 requests in any 10 seconds. It allowed requests at 2.0, 3.5, 4.0, 9.0 and 9.5 s and refused one at 10.0 s. At what time, in seconds, can the next request pass?

    Type a number.

    A hint

    The log frees a place when its oldest time leaves the window.

    Show the answer: Question 2 of 2

    Answer: 12 s

    The oldest allowed request, at 2.0 s, leaves the 10-second window at 12.0 s; until then the log holds 5 times. The refused request at 10.0 s was never added to the log, so it delays nobody.

A sliding window counter estimates the last window from two counts

A sliding window counter keeps the counts of only two fixed windows, the current one and the one before. To estimate how many requests the last full window held, it assumes that the previous window’s requests were spread evenly across it, and counts the share of that window that still overlaps:

estimate=previous×W−eW+current\text{estimate} = \text{previous} \times \frac{W - e}{W} + \text{current}

Here W is the window’s length and e is how far into the current window the request arrives. A request passes while the estimate stays below the limit, so half-way through the current window, half of the previous window still counts.

That weight changes every millisecond, which surprises people who test the limiter. Suppose the limit is 10 in 10 seconds, the previous window allowed 10, and a burst of 10 starts half-way through the next window. Half of 10 still counts, so it looks as if 5 should pass:

One program · 14 languages Five or six? A burst half-way through a window O(1) a request, three numbers per key

Python 3.14 · main.py

class SlidingWindowCounter:
    """This window's count and the last one's, weighted into an estimate."""

    def __init__(self, limit: int, window_ms: int) -> None:
        self.limit = limit
        self.window = window_ms
        self.current = 0
        self.count = 0
        self.previous = 0

    def allow(self, now_ms: int) -> bool:
        w = now_ms // self.window
        if w != self.current:
            # The old count becomes "previous" only if its window is the one just before.
            self.previous = self.count if w == self.current + 1 else 0
            self.current, self.count = w, 0
        elapsed = now_ms - w * self.window
        # previous x (window - elapsed) / window + count < limit, times the window.
        weighted = self.previous * (self.window - elapsed) + self.count * self.window
        if weighted < self.limit * self.window:
            self.count += 1
            return True
        return False


def burst_after_full_window(spacing_ms: int) -> int:
    """10 requests fill the window 0-10 s; 10 more start half-way through the next."""
    limiter = SlidingWindowCounter(limit=10, window_ms=10_000)
    for t in range(0, 10_000, 1000):
        limiter.allow(t)
    return sum(limiter.allow(15_000 + i * spacing_ms) for i in range(10))


print(
    "A limit of 10 in 10 s; the previous window allowed 10; a burst of 10 starts at 15.000 s"
)
print("Half the previous window still counts, so you might expect 10 - 5 = 5 to pass.")
print(f"Burst sent in the same millisecond: {burst_after_full_window(0)} allowed")
print(f"Burst sent 1 ms apart:              {burst_after_full_window(1)} allowed")
print(
    "At 15.005 s the previous window counts 10 x 4,995 / 10,000 = 4.995,"
    " and 4.995 + 5 is below 10."
)

In Python: sum() counts the requests that passed, because True is 1, and the comparison multiplies both sides by the window, so no fraction is ever computed.

Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py

JavaScript Node 24 · main.mjs

// This window's count and the last one's, weighted into an estimate.
class SlidingWindowCounter {
  constructor(limit, windowMs) {
    this.limit = limit;
    this.window = windowMs;
    this.current = 0;
    this.count = 0;
    this.previous = 0;
  }

  allow(nowMs) {
    const w = Math.trunc(nowMs / this.window);
    if (w !== this.current) {
      // The old count becomes "previous" only if its window is the one just before.
      this.previous = w === this.current + 1 ? this.count : 0;
      this.current = w;
      this.count = 0;
    }
    const elapsed = nowMs - w * this.window;
    // previous x (window - elapsed) / window + count < limit, times the window.
    const weighted = this.previous * (this.window - elapsed) + this.count * this.window;
    if (weighted < this.limit * this.window) {
      this.count++;
      return true;
    }
    return false;
  }
}

function burstAfterFullWindow(spacingMs) {
  const limiter = new SlidingWindowCounter(10, 10_000);
  for (let t = 0; t < 10_000; t += 1000) limiter.allow(t);
  let allowed = 0;
  for (let i = 0; i < 10; i++) if (limiter.allow(15_000 + i * spacingMs)) allowed++;
  return allowed;
}

console.log(
  "A limit of 10 in 10 s; the previous window allowed 10; a burst of 10 starts at 15.000 s",
);
console.log("Half the previous window still counts, so you might expect 10 - 5 = 5 to pass.");
console.log(`Burst sent in the same millisecond: ${burstAfterFullWindow(0)} allowed`);
console.log(`Burst sent 1 ms apart:              ${burstAfterFullWindow(1)} allowed`);
console.log(
  "At 15.005 s the previous window counts 10 x 4,995 / 10,000 = 4.995," +
    " and 4.995 + 5 is below 10.",
);

In JavaScript: Math.trunc gives the window number, because JavaScript has no integer division; every product here stays far below 2⁵³, so it is exact.

Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs

Java 25 LTS · Main.java

public class Main {
  /** This window's count and the last one's, weighted into an estimate. */
  static final class SlidingWindowCounter {
    private final int limit;
    private final int window;
    private int current;
    private int count;
    private int previous;

    SlidingWindowCounter(int limit, int windowMs) {
      this.limit = limit;
      this.window = windowMs;
    }

    boolean allow(int nowMs) {
      int w = nowMs / window;
      if (w != current) {
        // The old count becomes "previous" only if its window is the one just before.
        previous = w == current + 1 ? count : 0;
        current = w;
        count = 0;
      }
      int elapsed = nowMs - w * window;
      // previous x (window - elapsed) / window + count < limit, times the window.
      int weighted = previous * (window - elapsed) + count * window;
      if (weighted < limit * window) {
        count++;
        return true;
      }
      return false;
    }
  }

  static int burstAfterFullWindow(int spacingMs) {
    SlidingWindowCounter limiter = new SlidingWindowCounter(10, 10_000);
    for (int t = 0; t < 10_000; t += 1000) {
      limiter.allow(t);
    }
    int allowed = 0;
    for (int i = 0; i < 10; i++) {
      if (limiter.allow(15_000 + i * spacingMs)) {
        allowed++;
      }
    }
    return allowed;
  }

  public static void main(String[] args) {
    System.out.println(
        "A limit of 10 in 10 s; the previous window allowed 10; a burst of 10 starts at 15.000 s");
    System.out.println(
        "Half the previous window still counts, so you might expect 10 - 5 = 5 to pass.");
    System.out.println(
        "Burst sent in the same millisecond: " + burstAfterFullWindow(0) + " allowed");
    System.out.println(
        "Burst sent 1 ms apart:              " + burstAfterFullWindow(1) + " allowed");
    System.out.println(
        "At 15.005 s the previous window counts 10 x 4,995 / 10,000 = 4.995,"
            + " and 4.995 + 5 is below 10.");
  }
}

In Java: The products stay below 2³¹, so int is enough; a limit in the millions, times a window in milliseconds, would need long.

Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java

C++23 · main.cpp

#include <print>

// This window's count and the last one's, weighted into an estimate.
class SlidingWindowCounter {
public:
  SlidingWindowCounter(int limit, int window_ms)
      : limit_(limit), window_(window_ms) {}

  bool allow(int now_ms) {
    const int w = now_ms / window_;
    if (w != current_) {
      // The old count becomes "previous" only if its window is the one just
      // before.
      previous_ = w == current_ + 1 ? count_ : 0;
      current_ = w;
      count_ = 0;
    }
    const int elapsed = now_ms - w * window_;
    // previous x (window - elapsed) / window + count < limit, times the window.
    const int weighted = previous_ * (window_ - elapsed) + count_ * window_;
    if (weighted < limit_ * window_) {
      ++count_;
      return true;
    }
    return false;
  }

private:
  int limit_;
  int window_;
  int current_ = 0;
  int count_ = 0;
  int previous_ = 0;
};

int burst_after_full_window(int spacing_ms) {
  SlidingWindowCounter limiter(10, 10'000);
  for (int t = 0; t < 10'000; t += 1000) {
    limiter.allow(t);
  }
  int allowed = 0;
  for (int i = 0; i < 10; ++i) {
    if (limiter.allow(15'000 + i * spacing_ms)) {
      ++allowed;
    }
  }
  return allowed;
}

int main() {
  std::println(
      "A limit of 10 in 10 s; the previous window allowed 10; a burst of "
      "10 starts at 15.000 s");
  std::println(
      "Half the previous window still counts, so you might expect 10 - 5 "
      "= 5 to pass.");
  std::println("Burst sent in the same millisecond: {} allowed",
               burst_after_full_window(0));
  std::println("Burst sent 1 ms apart:              {} allowed",
               burst_after_full_window(1));
  std::println("At 15.005 s the previous window counts 10 x 4,995 / 10,000 = "
               "4.995, and 4.995 + 5 is below 10.");
}

In C++: 10'000 uses the digit separator of C++14, and the members are given their starting values where they are declared.

Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main

C# 14 · .NET 10 · app.cs

Console.WriteLine(
    "A limit of 10 in 10 s; the previous window allowed 10; a burst of 10 starts at 15.000 s");
Console.WriteLine("Half the previous window still counts, so you might expect 10 - 5 = 5 to pass.");
Console.WriteLine($"Burst sent in the same millisecond: {BurstAfterFullWindow(0)} allowed");
Console.WriteLine($"Burst sent 1 ms apart:              {BurstAfterFullWindow(1)} allowed");
Console.WriteLine(
    "At 15.005 s the previous window counts 10 x 4,995 / 10,000 = 4.995,"
    + " and 4.995 + 5 is below 10.");

static int BurstAfterFullWindow(int spacingMs)
{
    var limiter = new SlidingWindowCounter(10, 10_000);
    for (int t = 0; t < 10_000; t += 1000)
    {
        limiter.Allow(t);
    }
    int allowed = 0;
    for (int i = 0; i < 10; i++)
    {
        if (limiter.Allow(15_000 + i * spacingMs))
        {
            allowed++;
        }
    }
    return allowed;
}

// This window's count and the last one's, weighted into an estimate.
sealed class SlidingWindowCounter(int limit, int windowMs)
{
    private int _current;
    private int _count;
    private int _previous;

    public bool Allow(int nowMs)
    {
        int w = nowMs / windowMs;
        if (w != _current)
        {
            // The old count becomes "previous" only if its window is the one just before.
            _previous = w == _current + 1 ? _count : 0;
            _current = w;
            _count = 0;
        }
        int elapsed = nowMs - w * windowMs;
        // previous x (window - elapsed) / window + count < limit, times the window.
        int weighted = _previous * (windowMs - elapsed) + _count * windowMs;
        if (weighted < limit * windowMs)
        {
            _count++;
            return true;
        }
        return false;
    }
}

In C#: The primary constructor's limit and windowMs are used inside Allow, so the compiler keeps them as fields of the class.

Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs

C23 · main.c

#include <stdbool.h>
#include <stdio.h>

// This window's count and the last one's, weighted into an estimate.
typedef struct {
  int limit;
  int window;
  int current;
  int count;
  int previous;
} SlidingWindowCounter;

static bool allow(SlidingWindowCounter *c, int now_ms) {
  const int w = now_ms / c->window;
  if (w != c->current) {
    // The old count becomes "previous" only if its window is the one just
    // before.
    c->previous = w == c->current + 1 ? c->count : 0;
    c->current = w;
    c->count = 0;
  }
  const int elapsed = now_ms - w * c->window;
  // previous x (window - elapsed) / window + count < limit, times the window.
  const int weighted =
      c->previous * (c->window - elapsed) + c->count * c->window;
  if (weighted < c->limit * c->window) {
    c->count++;
    return true;
  }
  return false;
}

static int burst_after_full_window(int spacing_ms) {
  SlidingWindowCounter limiter = {.limit = 10, .window = 10000};
  for (int t = 0; t < 10000; t += 1000) {
    allow(&limiter, t);
  }
  int allowed = 0;
  for (int i = 0; i < 10; i++) {
    if (allow(&limiter, 15000 + i * spacing_ms)) {
      allowed++;
    }
  }
  return allowed;
}

int main(void) {
  printf("A limit of 10 in 10 s; the previous window allowed 10; a burst of 10 "
         "starts at 15.000 s\n");
  printf(
      "Half the previous window still counts, so you might expect 10 - 5 = 5 "
      "to pass.\n");
  printf("Burst sent in the same millisecond: %d allowed\n",
         burst_after_full_window(0));
  printf("Burst sent 1 ms apart:              %d allowed\n",
         burst_after_full_window(1));
  printf("At 15.005 s the previous window counts 10 x 4,995 / 10,000 = 4.995, "
         "and 4.995 + 5 is below 10.\n");
  return 0;
}

In C: A designated initializer sets the limit and the window, and every field it does not name starts at 0.

Recorded with Apple clang 21.0.0 (C23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang -std=c23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.c -o main && ./main

PHP 8.5 · main.php

<?php

declare(strict_types=1);

/** This window's count and the last one's, weighted into an estimate. */
final class SlidingWindowCounter
{
    private int $current = 0;
    private int $count = 0;
    private int $previous = 0;

    public function __construct(private int $limit, private int $window) {}

    public function allow(int $nowMs): bool
    {
        $w = intdiv($nowMs, $this->window);
        if ($w !== $this->current) {
            // The old count becomes "previous" only if its window is the one just before.
            $this->previous = $w === $this->current + 1 ? $this->count : 0;
            $this->current = $w;
            $this->count = 0;
        }
        $elapsed = $nowMs - $w * $this->window;
        // previous x (window - elapsed) / window + count < limit, times the window.
        $weighted = $this->previous * ($this->window - $elapsed) + $this->count * $this->window;
        if ($weighted >= $this->limit * $this->window) {
            return false;
        }
        $this->count++;
        return true;
    }
}

function burstAfterFullWindow(int $spacingMs): int
{
    $limiter = new SlidingWindowCounter(10, 10_000);
    for ($t = 0; $t < 10_000; $t += 1000) {
        $limiter->allow($t);
    }
    $allowed = 0;
    for ($i = 0; $i < 10; $i++) {
        if ($limiter->allow(15_000 + $i * $spacingMs)) {
            $allowed++;
        }
    }
    return $allowed;
}

echo "A limit of 10 in 10 s; the previous window allowed 10; a burst of 10 starts at 15.000 s\n";
echo "Half the previous window still counts, so you might expect 10 - 5 = 5 to pass.\n";
printf("Burst sent in the same millisecond: %d allowed\n", burstAfterFullWindow(0));
printf("Burst sent 1 ms apart:              %d allowed\n", burstAfterFullWindow(1));
echo "At 15.005 s the previous window counts 10 x 4,995 / 10,000 = 4.995,"
    . " and 4.995 + 5 is below 10.\n";

In PHP: Constructor property promotion declares limit and window, and intdiv gives the window number, where / could return a float.

Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. It runs in your browser with php-wasm 0.2.0 (PHP 8.5.2). To run it yourself: php main.php

Rust 1.99 · main.rs

/// This window's count and the last one's, weighted into an estimate.
struct SlidingWindowCounter {
    limit: u32,
    window: u32,
    current: u32,
    count: u32,
    previous: u32,
}

impl SlidingWindowCounter {
    fn new(limit: u32, window_ms: u32) -> Self {
        Self {
            limit,
            window: window_ms,
            current: 0,
            count: 0,
            previous: 0,
        }
    }

    fn allow(&mut self, now_ms: u32) -> bool {
        let w = now_ms / self.window;
        if w != self.current {
            // The old count becomes "previous" only if its window is the one just before.
            self.previous = if w == self.current + 1 { self.count } else { 0 };
            self.current = w;
            self.count = 0;
        }
        let elapsed = now_ms - w * self.window;
        // previous x (window - elapsed) / window + count < limit, times the window.
        let weighted = self.previous * (self.window - elapsed) + self.count * self.window;
        if weighted < self.limit * self.window {
            self.count += 1;
            true
        } else {
            false
        }
    }
}

fn burst_after_full_window(spacing_ms: u32) -> usize {
    let mut limiter = SlidingWindowCounter::new(10, 10_000);
    for t in (0..10_000).step_by(1000) {
        limiter.allow(t);
    }
    (0..10)
        .filter(|i| limiter.allow(15_000 + i * spacing_ms))
        .count()
}

fn main() {
    println!(
        "A limit of 10 in 10 s; the previous window allowed 10; a burst of 10 starts at 15.000 s"
    );
    println!("Half the previous window still counts, so you might expect 10 - 5 = 5 to pass.");
    println!(
        "Burst sent in the same millisecond: {} allowed",
        burst_after_full_window(0)
    );
    println!(
        "Burst sent 1 ms apart:              {} allowed",
        burst_after_full_window(1)
    );
    println!(
        "At 15.005 s the previous window counts 10 x 4,995 / 10,000 = 4.995, \
         and 4.995 + 5 is below 10."
    );
}

In Rust: u32 is enough because every product stays below 2³², and the burst is counted with filter and count on a range.

Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main

TypeScript 6.0 · main.ts

// This window's count and the last one's, weighted into an estimate.
class SlidingWindowCounter {
  readonly limit: number;
  readonly window: number;
  private current = 0;
  private count = 0;
  private previous = 0;

  constructor(limit: number, windowMs: number) {
    this.limit = limit;
    this.window = windowMs;
  }

  allow(nowMs: number): boolean {
    const w = Math.trunc(nowMs / this.window);
    if (w !== this.current) {
      // The old count becomes "previous" only if its window is the one just before.
      this.previous = w === this.current + 1 ? this.count : 0;
      this.current = w;
      this.count = 0;
    }
    const elapsed = nowMs - w * this.window;
    // previous x (window - elapsed) / window + count < limit, times the window.
    const weighted = this.previous * (this.window - elapsed) + this.count * this.window;
    if (weighted < this.limit * this.window) {
      this.count++;
      return true;
    }
    return false;
  }
}

function burstAfterFullWindow(spacingMs: number): number {
  const limiter = new SlidingWindowCounter(10, 10_000);
  for (let t = 0; t < 10_000; t += 1000) limiter.allow(t);
  let allowed = 0;
  for (let i = 0; i < 10; i++) if (limiter.allow(15_000 + i * spacingMs)) allowed++;
  return allowed;
}

console.log(
  "A limit of 10 in 10 s; the previous window allowed 10; a burst of 10 starts at 15.000 s",
);
console.log("Half the previous window still counts, so you might expect 10 - 5 = 5 to pass.");
console.log(`Burst sent in the same millisecond: ${burstAfterFullWindow(0)} allowed`);
console.log(`Burst sent 1 ms apart:              ${burstAfterFullWindow(1)} allowed`);
console.log(
  "At 15.005 s the previous window counts 10 x 4,995 / 10,000 = 4.995," +
    " and 4.995 + 5 is below 10.",
);

In TypeScript: The counters start at 0 in their declarations, and limit and window are readonly, so only allow can change the limiter's state.

Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts

Go 1.27 · main.go

package main

import "fmt"

// SlidingWindowCounter weights this window's count and the last one's into an estimate.
type SlidingWindowCounter struct {
	limit, window            int
	current, count, previous int
}

func (c *SlidingWindowCounter) Allow(nowMs int) bool {
	w := nowMs / c.window
	if w != c.current {
		// The old count becomes "previous" only if its window is the one just before.
		if w == c.current+1 {
			c.previous = c.count
		} else {
			c.previous = 0
		}
		c.current, c.count = w, 0
	}
	elapsed := nowMs - w*c.window
	// previous x (window - elapsed) / window + count < limit, times the window.
	weighted := c.previous*(c.window-elapsed) + c.count*c.window
	if weighted < c.limit*c.window {
		c.count++
		return true
	}
	return false
}

func burstAfterFullWindow(spacingMs int) int {
	limiter := &SlidingWindowCounter{limit: 10, window: 10_000}
	for t := 0; t < 10_000; t += 1000 {
		limiter.Allow(t)
	}
	allowed := 0
	for i := range 10 {
		if limiter.Allow(15_000 + i*spacingMs) {
			allowed++
		}
	}
	return allowed
}

func main() {
	fmt.Println("A limit of 10 in 10 s; the previous window allowed 10;" +
		" a burst of 10 starts at 15.000 s")
	fmt.Println("Half the previous window still counts, so you might expect 10 - 5 = 5 to pass.")
	fmt.Printf("Burst sent in the same millisecond: %d allowed\n", burstAfterFullWindow(0))
	fmt.Printf("Burst sent 1 ms apart:              %d allowed\n", burstAfterFullWindow(1))
	fmt.Println("At 15.005 s the previous window counts 10 x 4,995 / 10,000 = 4.995," +
		" and 4.995 + 5 is below 10.")
}

In Go: Fields of one type share a line, and the composite literal leaves current, count and previous at their zero value.

Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go

Swift 6.4 · main.swift

/// This window's count and the last one's, weighted into an estimate.
struct SlidingWindowCounter {
  let limit: Int
  let window: Int
  private var current = 0
  private var count = 0
  private var previous = 0

  init(limit: Int, windowMs: Int) {
    self.limit = limit
    self.window = windowMs
  }

  mutating func allow(_ nowMs: Int) -> Bool {
    let w = nowMs / window
    if w != current {
      // The old count becomes "previous" only if its window is the one just before.
      previous = w == current + 1 ? count : 0
      current = w
      count = 0
    }
    let elapsed = nowMs - w * window
    // previous x (window - elapsed) / window + count < limit, times the window.
    let weighted = previous * (window - elapsed) + count * window
    guard weighted < limit * window else { return false }
    count += 1
    return true
  }
}

func burstAfterFullWindow(spacingMs: Int) -> Int {
  var limiter = SlidingWindowCounter(limit: 10, windowMs: 10_000)
  for t in stride(from: 0, to: 10_000, by: 1000) {
    _ = limiter.allow(t)
  }
  var allowed = 0
  for i in 0..<10 {
    if limiter.allow(15_000 + i * spacingMs) {
      allowed += 1
    }
  }
  return allowed
}

print("A limit of 10 in 10 s; the previous window allowed 10; a burst of 10 starts at 15.000 s")
print("Half the previous window still counts, so you might expect 10 - 5 = 5 to pass.")
print("Burst sent in the same millisecond: \(burstAfterFullWindow(spacingMs: 0)) allowed")
print("Burst sent 1 ms apart:              \(burstAfterFullWindow(spacingMs: 1)) allowed")
print(
  "At 15.005 s the previous window counts 10 x 4,995 / 10,000 = 4.995,"
    + " and 4.995 + 5 is below 10.")

In Swift: The result of allow is discarded with _ = while the first window fills, because Swift warns about an unused result.

Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main

Ruby 4.0 · main.rb

# frozen_string_literal: true

# This window's count and the last one's, weighted into an estimate.
class SlidingWindowCounter
  def initialize(limit, window_ms)
    @limit = limit
    @window = window_ms
    @current = 0
    @count = 0
    @previous = 0
  end

  def allow(now_ms)
    window = now_ms / @window
    start_window(window) if window != @current
    elapsed = now_ms - (window * @window)
    # previous x (window - elapsed) / window + count < limit, times the window.
    weighted = (@previous * (@window - elapsed)) + (@count * @window)
    return false unless weighted < @limit * @window

    @count += 1
    true
  end

  private

  def start_window(window)
    # The old count becomes "previous" only if its window is the one just before.
    @previous = window == @current + 1 ? @count : 0
    @current = window
    @count = 0
  end
end

def burst_after_full_window(spacing_ms)
  limiter = SlidingWindowCounter.new(10, 10_000)
  0.step(9_999, 1000) { |t| limiter.allow(t) }
  10.times.count { |i| limiter.allow(15_000 + (i * spacing_ms)) }
end

puts 'A limit of 10 in 10 s; the previous window allowed 10; a burst of 10 starts at 15.000 s'
puts 'Half the previous window still counts, so you might expect 10 - 5 = 5 to pass.'
puts "Burst sent in the same millisecond: #{burst_after_full_window(0)} allowed"
puts "Burst sent 1 ms apart:              #{burst_after_full_window(1)} allowed"
puts 'At 15.005 s the previous window counts 10 x 4,995 / 10,000 = 4.995, ' \
     'and 4.995 + 5 is below 10.'

In Ruby: A new window is started in a private helper, so allow stays within RuboCop's method length, and the parentheses around products are RuboCop's style.

Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb

Kotlin 2.4 · Main.kt

// This window's count and the last one's, weighted into an estimate.
class SlidingWindowCounter(
    private val limit: Int,
    private val window: Int,
) {
    private var current = 0
    private var count = 0
    private var previous = 0

    fun allow(nowMs: Int): Boolean {
        val w = nowMs / window
        if (w != current) {
            // The old count becomes "previous" only if its window is the one just before.
            previous = if (w == current + 1) count else 0
            current = w
            count = 0
        }
        val elapsed = nowMs - w * window
        // previous x (window - elapsed) / window + count < limit, times the window.
        val weighted = previous * (window - elapsed) + count * window
        if (weighted >= limit * window) return false
        count++
        return true
    }
}

fun burstAfterFullWindow(spacingMs: Int): Int {
    val limiter = SlidingWindowCounter(10, 10_000)
    for (t in 0 until 10_000 step 1000) limiter.allow(t)
    return (0 until 10).count { limiter.allow(15_000 + it * spacingMs) }
}

fun main() {
    println(
        "A limit of 10 in 10 s; the previous window allowed 10; a burst of 10 starts at 15.000 s",
    )
    println("Half the previous window still counts, so you might expect 10 - 5 = 5 to pass.")
    println("Burst sent in the same millisecond: ${burstAfterFullWindow(0)} allowed")
    println("Burst sent 1 ms apart:              ${burstAfterFullWindow(1)} allowed")
    println(
        "At 15.005 s the previous window counts 10 x 4,995 / 10,000 = 4.995," +
            " and 4.995 + 5 is below 10.",
    )
}

In Kotlin: (0 until 10).count with a lambda counts the requests that passed, and it names the lambda's single argument.

Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar

Dart 3.13 · main.dart

/// This window's count and the last one's, weighted into an estimate.
class SlidingWindowCounter {
  final int limit;
  final int window;
  int _current = 0;
  int _count = 0;
  int _previous = 0;

  SlidingWindowCounter(this.limit, this.window);

  bool allow(int nowMs) {
    final w = nowMs ~/ window;
    if (w != _current) {
      // The old count becomes "previous" only if its window is the one just before.
      _previous = w == _current + 1 ? _count : 0;
      _current = w;
      _count = 0;
    }
    final elapsed = nowMs - w * window;
    // previous x (window - elapsed) / window + count < limit, times the window.
    final weighted = _previous * (window - elapsed) + _count * window;
    if (weighted >= limit * window) return false;
    _count++;
    return true;
  }
}

int burstAfterFullWindow(int spacingMs) {
  final limiter = SlidingWindowCounter(10, 10000);
  for (var t = 0; t < 10000; t += 1000) {
    limiter.allow(t);
  }
  var allowed = 0;
  for (var i = 0; i < 10; i++) {
    if (limiter.allow(15000 + i * spacingMs)) allowed++;
  }
  return allowed;
}

void main() {
  print(
    'A limit of 10 in 10 s; the previous window allowed 10; a burst of 10 starts at 15.000 s',
  );
  print(
    'Half the previous window still counts, so you might expect 10 - 5 = 5 to pass.',
  );
  print(
    'Burst sent in the same millisecond: ${burstAfterFullWindow(0)} allowed',
  );
  print(
    'Burst sent 1 ms apart:              ${burstAfterFullWindow(1)} allowed',
  );
  print(
    'At 15.005 s the previous window counts 10 x 4,995 / 10,000 = 4.995, '
    'and 4.995 + 5 is below 10.',
  );
}

In Dart: ~/ is integer division, and the private fields start at 0 where they are declared.

Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart

What every language printed

A limit of 10 in 10 s; the previous window allowed 10; a burst of 10 starts at 15.000 s
Half the previous window still counts, so you might expect 10 - 5 = 5 to pass.
Burst sent in the same millisecond: 5 allowed
Burst sent 1 ms apart:              6 allowed
At 15.005 s the previous window counts 10 x 4,995 / 10,000 = 4.995, and 4.995 + 5 is below 10.

Five pass when the whole burst arrives within one millisecond, and six when its requests come 1 ms apart, because by the sixth request the previous window counts for only 4.995. Neither answer is a bug. A test that expects one number has to fix the time of every request, which is what an injected clock is for.

Step through the burst sent 1 ms apart, and watch the two parts of the estimate move in opposite directions:

Interactive · step by step Five or six? The estimate, request by request Step through a burst sent 1 ms apart and watch the previous window's share fall while the current count rises.
Five or six? The estimate, request by request, step 7 of 7. Showing Burst, 1 ms apart, Window counter (estimate 4.994 + 6), Service (received 6). In focus: Window counter, Service.Burst, 1 ms apartfrom 15.000 sWindow counterestimate 4.994 + 6Servicereceived 6

The drawing shows the whole scene; its 7 steps are listed below.

Every step as text
  1. The setting. The window is 10 s and the limit 10. The window from 0 to 10 s allowed 10 requests, and at 15.000 s, half-way through the next window, a burst of 10 starts, one request every millisecond.
  2. Request 1. Half of the previous window still overlaps, so it counts 10 × 5,000 / 10,000 = 5.000, plus 0 from this window. 5.000 is below 10, so the request passes.
  3. Request 2. One millisecond later the previous window counts 4.999, plus the 1 just allowed, 5.999. The request passes.
  4. Requests 3 to 5. Each millisecond takes 0.001 off the previous window's share while the current count grows by 1. Request 5's estimate is 4.996 + 4 = 8.996, and it passes.
  5. Request 6. At 15.005 s the estimate is 4.995 + 5 = 9.995, still below 10, so the sixth request passes. Sent within one millisecond, the burst would have stopped here, because 5.000 + 5 is exactly 10.
  6. Requests 7 to 10. Request 7 sees 4.994 + 6 = 10.994, over the limit, and so do the three after it. Six passed, not five.
  7. Time decides. Five or six depends on a few milliseconds, because the estimate moves with time as well as with requests. A test that expects one number must fix the time of every request.

Key idea

A sliding window counter weighs the previous window by how much of it still overlaps, so its estimate changes with every millisecond as well as with every request.

Checkpoint

Check: The sliding window counter's estimate

  1. Question 1 of 2 A sliding window counter allows 100 in 60 s. The previous window allowed 80 and the current one 30 so far. A request arrives 15 s into the current window. What estimate does the counter compare with the limit?

    Type a number.

    A hint

    previous × (W − e) / W + current.

    Show the answer: Question 1 of 2

    Answer: 90 requests

    80 × (60 − 15) / 60 + 30 = 80 × 0.75 + 30 = 60 + 30 = 90. That is below 100, so the request passes and the current count becomes 31.

  2. Question 2 of 2 The previous window's 10 requests all arrived in its first second. Half-way through the current window, the counter still counts 5 of them. Which is true?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: The counter may refuse a request that an exact limiter would allow, because those 10 requests have already left the real window

    The estimate assumes that the previous window's requests were spread evenly. Bunched early, they have already left the real window but are still half counted, so the counter can refuse a request that an exact limiter would allow; bunched late, the error runs the other way.

On the same traffic, the five differ in what reaches the service

Each algorithm looks reasonable on its own; the differences show when they all see the same requests. The traffic is 20 seconds of one client: random requests at about 4 a second, a burst of 30 at 3 seconds, ten requests on each side of the window edge at 8 seconds, and four seconds at 15 a second from 12 seconds on. Its random part is seeded, so it is the same on every run (Python documentation). Every limiter is set to about 10 a second: the token bucket holds 10 and gains 10 a second, the leaky bucket lets 10 a second out and holds 10, and the three window limiters allow 10 in 1,000 ms.

The traffic: 20 seconds of one client Python · limiters/traffic.py
# The traffic every limiter in the playground sees: 20 seconds of one client's requests, as whole milliseconds.
# The random part is seeded, so every run (and every Python) builds the same trace.
import random


def bursty_trace(seed=7):
    rng = random.Random(seed)
    times, t = [], 0
    while True:                                          # background: random gaps of 1-499 ms, about 4 a second
        t += rng.randrange(1, 500)
        if t >= 20_000:
            break
        times.append(t)
    times += [3000 + 2 * i for i in range(30)]           # 3 s: a burst of 30 within 60 ms
    times += [7900 + 10 * i for i in range(10)]          # 7.9 s: 10 just before a window edge ...
    times += [8000 + 10 * i for i in range(10)]          # ... and 10 just after it
    times += [12_000 + 1000 * i // 15 for i in range(60)]  # 12-16 s: 15 a second, more than the limit
    return sorted(times)
The rate-limiter playground: five limiters, one trace

limiters/playground.py

# The rate-limiter playground: five limiters, each set to about 10 requests a second, on the same 20 seconds of
# traffic (traffic.py). Each column counts the requests that reached the service in that second; for the leaky
# bucket that is when a request left the bucket, which can be later than when it arrived.
from fixed_window import FixedWindow
from leaky_bucket import LeakyBucket
from sliding_counter import SlidingWindowCounter
from sliding_log import SlidingLog
from token_bucket import TokenBucket
from traffic import bursty_trace


def busiest_second(times):
    """The most requests in any span of 1,000 ms (times sorted)."""
    best, start = 0, 0
    for end, t in enumerate(times):
        while t - times[start] >= 1000:
            start += 1
        best = max(best, end - start + 1)
    return best


trace = bursty_trace()
limiters = {
    "token": TokenBucket(rate=10, capacity=10),
    "fixed": FixedWindow(limit=10, window_ms=1000),
    "log": SlidingLog(limit=10, window_ms=1000),
    "counter": SlidingWindowCounter(limit=10, window_ms=1000),
}
served = {name: [t for t in trace if limiter.allow(t)] for name, limiter in limiters.items()}
leaky = LeakyBucket(rate=10, size=10)
offers = [(t, leaky.offer(t)) for t in trace]
served["leaky"] = sorted(leave for _, leave in offers if leave is not None)
waits = [leave - t for t, leave in offers if leave is not None]

columns = ["token", "leaky", "fixed", "log", "counter"]
print("second  sent " + "".join(f"{c:>8}" for c in columns))
for s in range(20):
    def in_second(times):
        return sum(s * 1000 <= t < (s + 1) * 1000 for t in times)
    print(f"{s:>6}{in_second(trace):>6} " + "".join(f"{in_second(served[c]):>8}" for c in columns))

print()
print(f"{'':<22}" + "".join(f"{c:>8}" for c in columns))
print(f"{'served':<22}" + "".join(f"{len(served[c]):>8}" for c in columns))
print(f"{'refused':<22}" + "".join(f"{len(trace) - len(served[c]):>8}" for c in columns))
print(f"{'busiest 1,000 ms':<22}" + "".join(f"{busiest_second(served[c]):>8}" for c in columns))
print(f"{'longest wait (ms)':<22}" + "".join(f"{(max(waits) if c == 'leaky' else 0):>8}" for c in columns))
print(f"{len(trace)} requests in 20 s; every limiter is set to 10 a second")

Output

second  sent    token   leaky   fixed     log counter
     0     4        4       4       4       4       4
     1     4        4       4       4       4       4
     2     5        5       5       5       5       5
     3    38       17      10      10      10      10
     4     5        5      10       5       5       5
     5     4        4       7       4       4       4
     6     4        4       4       4       4       4
     7    13       13       4      10       9      10
     8    16        6      10      10       2       6
     9     6        6      10       6       6       6
    10     4        4       6       4       4       4
    11     5        5       5       5       5       5
    12    20       18      10      10       9      10
    13    20       10      10      10      10      10
    14    19       10      10      10      10      10
    15    18       10      10      10      10      10
    16     3        3      10       3       3       3
    17     5        5       7       5       5       5
    18     3        3       3       3       3       3
    19     6        6       6       6       6       6

                         token   leaky   fixed     log counter
served                     142     145     128     118     124
refused                     60      57      74      84      78
busiest 1,000 ms            19      10      20      10      15
longest wait (ms)            0     997       0       0       0
202 requests in 20 s; every limiter is set to 10 a second

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 playground.py

limiters/token_bucket.py

# Token bucket: a burst of up to `capacity` requests passes at once, then `rate` requests a second.
# Time is passed in as whole milliseconds from a clock that only moves forward, so a test or a simulation decides
# what "now" is. Tokens are counted in thousandths, so every number stays whole and no rounding error can let a
# request through or turn one away.


class TokenBucket:
    def __init__(self, rate, capacity, now_ms=0):
        self.rate = rate                  # tokens added every second (a whole number)
        self.capacity = capacity          # the most tokens the bucket holds: the largest burst
        self.milli = capacity * 1000      # tokens now, in thousandths; a new bucket starts full
        self.at = now_ms                  # when `milli` was last brought up to date

    def _refill(self, now_ms):
        # No timer runs. Each call adds what the time since the last call earned, up to the capacity.
        if now_ms > self.at:
            earned = (now_ms - self.at) * self.rate     # 1 ms earns `rate` thousandths of a token
            self.milli = min(self.capacity * 1000, self.milli + earned)
            self.at = now_ms

    def allow(self, now_ms, cost=1):
        """Take `cost` tokens and return True, or take nothing and return False."""
        self._refill(now_ms)
        if self.milli >= cost * 1000:
            self.milli -= cost * 1000
            return True
        return False

    def retry_after_ms(self, now_ms, cost=1):
        """How long until a request of `cost` tokens would pass: 0 if it would pass now."""
        if cost > self.capacity:
            raise ValueError("the request needs more tokens than the bucket can ever hold")
        self._refill(now_ms)
        missing = cost * 1000 - self.milli
        return max(0, -(-missing // self.rate))         # rounded up to a whole millisecond

    def tokens(self):
        return self.milli / 1000

limiters/sliding_counter.py

# Sliding window counter: two counters, this fixed window's and the previous one's. It estimates the requests in
# the last `window_ms` as if the previous window's requests had been spread evenly over it:
#     estimate = previous × (window − elapsed) / window + current
# and lets a request pass while the estimate is below `limit`. The comparison is done in whole numbers
# (both sides multiplied by the window), so no rounding error can change a decision.


class SlidingWindowCounter:
    def __init__(self, limit, window_ms):
        self.limit = limit
        self.window = window_ms
        self.current = 0                 # index of the current fixed window
        self.count = 0                   # requests allowed in it
        self.previous = 0                # requests allowed in the window before it

    def allow(self, now_ms):
        w = now_ms // self.window
        if w != self.current:
            # The old count becomes "previous" only if that window is the one just before this one.
            self.previous = self.count if w == self.current + 1 else 0
            self.current, self.count = w, 0
        elapsed = now_ms - w * self.window
        if self.previous * (self.window - elapsed) + self.count * self.window < self.limit * self.window:
            self.count += 1
            return True
        return False

Its other two tabs hold the two classes it imports: the limiters of the blocks above, with a cost per request added to the token bucket.

Read the row “busiest 1,000 ms” first, because it is what the service behind the limiter must survive. The sliding log and the leaky bucket held to 10. The token bucket let 19 through within a second when the heavy traffic began at 12 seconds: the 10 tokens it had saved and the 9 it earned in the next 0.9 seconds, its b + r × T bound at work. The fixed window let 20 through around the edge at 8 seconds, and the sliding window counter 15 in the same place.

The row “served” shows what the client got. The leaky bucket served the most, 145, because it delays requests instead of refusing them; its longest wait was 997 ms. The sliding log served the fewest, 118, because being exact means refusing everything over the line. From 12 to 16 seconds every limiter settles at 10 a second, but the token bucket first spends its saved tokens (18 in the first of those seconds), and the leaky bucket goes on sending 10 a second after the heavy traffic has stopped, until its queue is empty (second 16).

The five side by side, with what each lets through and what it keeps for every key:

Algorithm Lets through Keeps
Token bucket b at once; b + r × T in any T seconds Tokens and a time
Leaky bucket An even r a second; bursts wait A time and a queue
Fixed window Up to 2 × the limit at an edge A window and a count
Sliding log Never more than the limit A time per request
Sliding window counter Near the limit; up to 2 × at worst A window and two counts

What each one costs in memory

That last column, in bytes: the next program counts what each algorithm keeps for 10 million keys, with a limit of 1,000 requests an hour.

State for 10 million keys Python · sizing/sizing.py
# What each algorithm keeps per key, and what that costs for 10 million keys with a limit of 1,000 requests an hour.
# Counted at 8 bytes a number (a 64-bit count or timestamp) and nothing else: a real store adds its own overhead
# per key, about the same for every algorithm, so compare the rows rather than read the totals as exact.
KEYS = 10_000_000
LIMIT = 1_000
NUMBER = 8

STATE = [
    ("GCRA", "the theoretical arrival time", 1),
    ("token bucket", "tokens and the last refill time", 2),
    ("fixed window", "the window and its count", 2),
    ("sliding window counter", "the window and two counts", 3),
    ("sliding log", "one timestamp per request in the window", LIMIT),
]


def size(n_bytes):
    for unit, scale in [("GB", 10**9), ("MB", 10**6), ("KB", 10**3)]:
        if n_bytes >= scale:
            return f"{n_bytes / scale:,.1f} {unit}"
    return f"{n_bytes} B"


print(f"{KEYS:,} keys, a limit of {LIMIT:,} requests an hour, {NUMBER} bytes a number")
print(f"{'algorithm':<24}{'per key':>10}{'all keys':>12}  what it keeps")
for name, what, numbers in STATE:
    print(f"{name:<24}{size(numbers * NUMBER):>10}{size(numbers * NUMBER * KEYS):>12}  {what}")

busy = 0.01
log_bytes = KEYS * busy * LIMIT * NUMBER + KEYS * (1 - busy) * 50 * NUMBER
print(f"\nThe log's total is its worst case: every key at its limit. If 1% of keys are at the limit and the rest"
      f"\nsend 50 requests an hour, the log holds {size(log_bytes)}.")

Output

10,000,000 keys, a limit of 1,000 requests an hour, 8 bytes a number
algorithm                  per key    all keys  what it keeps
GCRA                           8 B     80.0 MB  the theoretical arrival time
token bucket                  16 B    160.0 MB  tokens and the last refill time
fixed window                  16 B    160.0 MB  the window and its count
sliding window counter        24 B    240.0 MB  the window and two counts
sliding log                 8.0 KB     80.0 GB  one timestamp per request in the window

The log's total is its worst case: every key at its limit. If 1% of keys are at the limit and the rest
send 50 requests an hour, the log holds 4.8 GB.

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 sizing.py

Counting only the numbers themselves, GCRA needs 80 MB for 10 million keys and the sliding window counter 240 MB, small enough for one cache server. The sliding log needs up to 80 GB, five hundred times the token bucket, when every key is at its limit; even with only 1 % of keys busy it holds 4.8 GB. A real store adds an overhead per key that is much the same for every algorithm, so the comparison holds even where the totals do not.

Checkpoint

Check: The five on one trace, and their memory

  1. Question 1 of 2 On the lesson's trace, the token bucket let 19 requests through within one second, although it is set to 10 a second. Where did the 19 come from?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The 10 tokens it had saved while traffic was light, and the 9 it earned in the next 0.9 seconds

    When the heavy traffic began at 12 seconds, the bucket held its full 10 tokens, and in the next 0.9 seconds it earned 9 more. So 19 passed within one second, exactly what b + r × T allows, and the service behind it must survive 19, not 10.

  2. Question 2 of 2 A sliding log stores an 8-byte time for every allowed request. How many bytes does it keep for one key at a limit of 1,000 requests an hour, when the key is at its limit?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 8000 bytes

    1,000 times × 8 bytes = 8,000 bytes, against 16 bytes for a token bucket: five hundred times as much. For 10 million keys at their limit, that is the 80 GB of the sizing program.

The counter is close on steady traffic, not on shaped traffic

One trace proves little. The next script gives the three window limiters an hour of traffic in three shapes, with a limit of 100 requests in any 60 seconds, and measures two things: the most requests each one let through in any 60 seconds, and how many it served in the hour.

An hour of traffic against three window limiters Python · limiters/accuracy.py
# How close do the window limiters come to the exact rule "at most 100 requests in any 60 seconds"? Each one gets
# an hour of the same traffic, in three shapes: steady single requests, bursts at random moments, and a pattern
# built to fool them (a burst at the end of one window, then requests spread evenly over the next).
import random

from fixed_window import FixedWindow
from sliding_counter import SlidingWindowCounter
from sliding_log import SlidingLog

LIMIT, WINDOW, HOUR = 100, 60_000, 3_600_000


def steady(load, rng):
    times, t, mean_gap = [], 0, WINDOW // (LIMIT * load)
    while (t := t + rng.randrange(1, 2 * mean_gap)) < HOUR:
        times.append(t)
    return times


def bursty(load, rng):
    """Single requests and bursts of 2-29 (about 7 requests an event on average), 0-9 ms apart in a burst."""
    times, t, mean_gap = [], 0, WINDOW * 7 // (LIMIT * load)
    while (t := t + rng.randrange(1, 2 * mean_gap)) < HOUR:
        for _ in range(1 if rng.random() < 0.6 else rng.randrange(2, 30)):
            times.append(t)
            t += rng.randrange(10)
    return times


def edge_pattern(load, rng):
    """Even windows: 100 requests in their last 100 ms. Odd windows: 100 requests spread evenly."""
    times = []
    for w in range(0, HOUR // WINDOW, 2):
        start = w * WINDOW
        times += [start + WINDOW - 100 + i for i in range(LIMIT)]
        times += [start + WINDOW + i * (WINDOW // LIMIT) for i in range(LIMIT)]
    return times


def busiest(times):
    """The most requests in any span of 60 s (times sorted)."""
    best, start = 0, 0
    for end, t in enumerate(times):
        while t - times[start] >= WINDOW:
            start += 1
        best = max(best, end - start + 1)
    return best


rows = []
for shape, load in [(steady, 1), (steady, 2), (bursty, 1), (bursty, 2), (edge_pattern, 1)]:
    times = shape(load, random.Random(load))
    limiters = [FixedWindow(LIMIT, WINDOW), SlidingWindowCounter(LIMIT, WINDOW), SlidingLog(LIMIT, WINDOW)]
    served = [[t for t in times if limiter.allow(t)] for limiter in limiters]
    label = "edge pattern" if shape is edge_pattern else f"{shape.__name__} {load}x"
    rows.append((label, len(times), [busiest(s) for s in served], [len(s) for s in served]))

print(f"Limit: {LIMIT} requests in any {WINDOW // 1000} s; each row is one hour of traffic")
print("fixed: fixed window; counter: sliding window counter; log: sliding log")
for title, column in [("Busiest 60 s", 2), ("Served", 3)]:
    print()
    print(f"{title:<14}{'sent':>7}{'fixed':>8}{'counter':>9}{'log':>7}")
    for label, sent, *values in rows:
        v = values[column - 2]
        print(f"{label:<14}{sent:>7}{v[0]:>8}{v[1]:>9}{v[2]:>7}")

Output

Limit: 100 requests in any 60 s; each row is one hour of traffic
fixed: fixed window; counter: sliding window counter; log: sliding log

Busiest 60 s     sent   fixed  counter    log
steady 1x        5964     118      108    100
steady 2x       12036     120      101    100
bursty 1x        5589     150      129    100
bursty 2x       11629     169      124    100
edge pattern     6000     200      199    100

Served           sent   fixed  counter    log
steady 1x        5964    5854     5778   5709
steady 2x       12036    6000     6000   5996
bursty 1x        5589    4989     4656   4449
bursty 2x       11629    5959     5569   5457
edge pattern     6000    6000     5970   3000

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 accuracy.py

On steady traffic the counter is close: its busiest minute held 108 requests when the traffic came at the limit’s own rate and 101 at twice that rate, against 118 and 120 for the fixed window. Bursts make it worse, 129 and 124, because a burst breaks the assumption that the previous window’s requests were spread evenly. The last row is traffic built to defeat it: 100 requests in the last 100 ms of one window, then 100 spread evenly over the next. The fixed window let 200 through within a minute and the counter 199, and over the hour the counter served 5,970 requests where the exact log served 3,000. The estimate treats the burst as if it had been spread across its window, so as time moves on it counts less and less of a burst that is still inside the last 60 seconds.

The error runs the other way too. When the previous window’s requests came early in it, they have already left the real window, but the estimate still counts part of them, so the counter can refuse a request that an exact limiter would have allowed. So the sliding window counter is an estimate: close on ordinary traffic, and wrong by up to about a factor of two on traffic shaped against it. That is good enough for sharing capacity fairly, and not for limits whose number is a promise, such as how many password guesses an attacker gets or how many text messages, each one charged for, a client can trigger.

Checkpoint

Check: How far the window counters stray

  1. Question 1 of 2 Traffic sends 100 requests in the last 100 ms of one window and then 100 spread evenly over the next, against a limit of 100 in any 60 seconds. What did the sliding window counter let through within one minute?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: 199

    The fixed window let 200 through within a minute and the counter 199, while the exact log held 100. On traffic shaped against it, the counter's estimate is wrong by almost a factor of two.

  2. Question 2 of 2 A team wants a sliding window counter for a limit of 5 failed logins per 15 minutes, because it needs only three numbers per account. What is wrong with that choice?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: The limit is a promise about an attacker, and the counter can let up to about twice the limit through on traffic shaped against it

    Small limits that are promises, such as how many guesses an attacker gets, need an exact limiter. A sliding log of a handful of failure times per account is exact and costs little; the counter is good enough for sharing capacity fairly, not for this.

The purpose of a limit chooses its algorithm, key and numbers

Start from what the limit protects, then choose the key, the algorithm and the numbers.

  • A public API sold by plan. Use a token bucket per API key. The rate is what the plan promises, and the bucket size is the largest burst you are willing to absorb, such as the requests one page load or one batch makes at once. A daily or monthly quota on top can be a fixed window, because a burst at the edge matters little against a day’s total.
  • Logins, one-time codes and password resets. The limits are small, and they are promises about an attacker: five guesses must mean five. Use a sliding log of failed attempts, which is a handful of timestamps per key, keyed by the account and by the account and address together. Keep any limit on the address alone generous: RFC 6269 notes that when many subscribers share one address, an address shut out after failed logins shuts out everyone behind it (RFC 6269, section 13.1).
  • Calls to a partner with a hard limit. Pace them, with a leaky bucket in front of the partner or pacing in the caller. Microsoft’s Rate Limiting pattern gives the example of releasing 20 operations every 200 ms instead of 100 at once, so that the partner sees an even flow (Azure Architecture Center).
  • Expensive endpoints. Searches and reports that take seconds need a limit on how many run at once, as well as on how many start each second: at 3 seconds each, 20 a second keep 60 running. Stripe’s limiter on requests in progress is this kind of limit (Stripe).
  • Millions of keys where a close answer is enough, such as limits per address at the edge: a sliding window counter, at three numbers a key, or a fixed window when even that is too much.

Two habits help, whichever you choose. Give each request a cost, so that an expensive call takes several tokens and a cheap one takes one. And run a new limiter in a watching mode first: Stripe’s post advises Running a new piece of a system on real traffic without letting it act: a limiter that only records what it would have refused, so its numbers can be checked before it refuses anything. each limiter, watching the traffic it would have blocked and adjusting it before it refuses anything (Stripe).

Three questions about a limit of your own narrow the choice. As you answer, the table rules out the algorithms that cannot keep that limit and says why, with this lesson’s numbers in every cell:

Interactive · answer and compare Which limiter fits your limit? Answer three questions about a limit of your own. The table marks the algorithms that fit and says why the others do not.
Is the limit's number a promise, such as the guesses an attacker gets or the messages you pay for?
Can the work wait a little, as calls to a partner with a hard limit can?
How many keys does the limiter track at once?

Answer the questions above: the table then marks what fits your case and says why the rest does not.

Six rate-limiting algorithms against the four things that decide between them, with this lesson's numbers
Algorithm Bursts at the service Holds the number State per key Adds waiting
Token bucket Keeps per key: tokens and a time Mixed up to b at once: 19 in one second on the trace Good never more than b + r × T in any T seconds Good 2 numbers: 160 MB for 10 million keys Good passes or refuses at once
GCRA Keeps per key: one theoretical arrival time Mixed the same burst as a token bucket of b tokens Good the same decisions as the token bucket: 5,000 of 5,000 Good 1 number: 80 MB for 10 million keys Good passes or refuses at once
Leaky bucket Keeps per key: a time and a queue Good none: an even 10 a second on the trace Good an even r a second; requests over the queue are refused Mixed a time and a queue of up to b requests Poor bursts wait: up to 997 ms on the trace
Fixed window Keeps per key: a window and a count Poor 2 × the limit at an edge: 20 in 190 ms Poor busiest minute 118 to 200 against 100 Good 2 numbers: 160 MB for 10 million keys Good no waiting, but every client resets at once
Sliding log Keeps per key: a time per allowed request Good never more than the limit in any window Good busiest minute 100 on every traffic shape Poor a time per request: up to 80 GB Good passes or refuses at once
Sliding window counter Keeps per key: a window and two counts Mixed 15 in one second on the trace, against 10 Mixed 108 on steady traffic, 199 on shaped traffic Good 3 numbers: 240 MB for 10 million keys Good passes or refuses at once
How the answers decide
  • “Is the limit's number a promise, such as the guesses an attacker gets or the messages you pay for?” Yes, it must hold exactly: rules out Fixed window and Sliding window counter. Neither keeps a promise: the fixed window let 20 through in 190 ms against 10, and the counter 199 against 100 on shaped traffic.
  • “Is the limit's number a promise, such as the guesses an attacker gets or the messages you pay for?” Yes, it must hold exactly: adds a caveat to Token bucket and GCRA. They hold b + r × T exactly, so the burst counts against the promise: keep b small.
  • “Can the work wait a little, as calls to a partner with a hard limit can?” No, a person is waiting: rules out Leaky bucket. A waiting request holds a connection open and keeps a person waiting: up to 997 ms on the lesson's trace.
  • “Can the work wait a little, as calls to a partner with a hard limit can?” Yes, it can wait: adds a caveat to Token bucket, GCRA, Fixed window, Sliding log and Sliding window counter. These refuse a burst instead of pacing it; put a leaky bucket or pacing in front of work that must arrive evenly.
  • “How many keys does the limiter track at once?” Millions: adds a caveat to Sliding log. Only for small limits: a time per request is up to 80 GB for 10 million keys at 1,000 an hour, but 40 bytes a key at a limit of 5.
  • “How many keys does the limiter track at once?” Thousands: With thousands of keys memory decides nothing; even a sliding log's times fit easily.

In short: a token bucket, or GCRA when memory counts, for most limits; a sliding log for small limits that are promises; a leaky bucket where the work can wait; and the window counters where a close answer for millions of keys is enough.

Checkpoint

Check: Choosing an algorithm and a key

  1. Question 1 of 2 An endpoint sends a one-time code by text message, and every message is charged for. Which limit fits best?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: A sliding log per phone number and per account, with a small limit such as 3 codes in 10 minutes

    Limits that cap a cost per request are promises: the number must mean what it says. A sliding log keyed by the phone number and by the account holds exactly, at a handful of times per key.

  2. Question 2 of 2 A plan includes 50,000 requests a day per API key on top of a rate of 20 a second. Which algorithm suits the daily quota?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: A fixed window of one day, because a burst at the edge matters little against a day's total

    The rate limit, a token bucket, handles bursts; the daily quota only needs a total, and a fixed window per key and day is the cheapest total. Its edge can let at most two days' quota through within a short time, which matters little against a plan's daily total.

A refused request gets 429 and the time to wait

A refused request should get an answer that the client can act on. The status code for it is 429 Too Many Requests, defined in RFC 6585: the response should explain the condition, it may include a An HTTP response field that tells a client how long to wait before trying again, as a number of seconds or an HTTP date. field that says how long to wait, and a cache must not store it (RFC 6585). Retry-After carries either a number of seconds or an HTTP date (RFC 9110). Round the wait up to a whole second, so that a client which waits exactly that long is not refused again for the same reason.

Many APIs also describe the limit on every response, so that well-behaved clients slow down before they are refused. The IETF’s HTTPAPI working group is standardising two fields for this: RateLimit-Policy for the quota and its window, and RateLimit for what is left and within how many seconds. It is still an Internet-Draft, so the details may change. The draft does not mandate any algorithm, tells clients not to treat the numbers as a guarantee, and gives Retry-After precedence when both are present (draft-ietf-httpapi-ratelimit-headers).

The responses one client sees JavaScript · http/respond.mjs
// What a client sees from a limited API: at most 5 requests in any 10 seconds per key (a sliding log), and the
// response to each request with Retry-After (RFC 9110) and the RateLimit-Policy and RateLimit fields of the IETF
// draft. Time is passed in as whole milliseconds, so every run prints the same.
const LIMIT = 5;
const WINDOW_MS = 10_000;

class SlidingLog {
  constructor(limit, windowMs) {
    this.limit = limit;
    this.windowMs = windowMs;
    this.log = []; // times of the requests allowed in the last window, oldest first
  }

  allow(nowMs) {
    while (this.log.length && this.log[0] <= nowMs - this.windowMs) this.log.shift();
    if (this.log.length >= this.limit) return false;
    this.log.push(nowMs);
    return true;
  }

  /** Whole seconds, rounded up, until the oldest request leaves the window and one more unit is available. */
  secondsUntilOldestLeaves(nowMs) {
    if (!this.log.length) return this.windowMs / 1000;
    return Math.ceil((this.log[0] + this.windowMs - nowMs) / 1000);
  }
}

function respond(limiter, nowMs) {
  const allowed = limiter.allow(nowMs);
  const remaining = limiter.limit - limiter.log.length;
  const t = limiter.secondsUntilOldestLeaves(nowMs);
  const lines = [`${String(nowMs).padStart(6)} ms  ${allowed ? '200 OK' : '429 Too Many Requests'}`];
  if (!allowed) lines.push(`Retry-After: ${t}`);
  lines.push(`RateLimit: "per-key";r=${remaining};t=${t}`);
  return lines.join(`\n${' '.repeat(11)}`);
}

const limiter = new SlidingLog(LIMIT, WINDOW_MS);
console.log(`Every response carries\n           RateLimit-Policy: "per-key";q=${LIMIT};w=${WINDOW_MS / 1000}`);
for (const nowMs of [0, 1000, 2000, 2500, 3000, 3100, 9000, 10_500, 10_600]) console.log(respond(limiter, nowMs));

Output

Every response carries
           RateLimit-Policy: "per-key";q=5;w=10
     0 ms  200 OK
           RateLimit: "per-key";r=4;t=10
  1000 ms  200 OK
           RateLimit: "per-key";r=3;t=9
  2000 ms  200 OK
           RateLimit: "per-key";r=2;t=8
  2500 ms  200 OK
           RateLimit: "per-key";r=1;t=8
  3000 ms  200 OK
           RateLimit: "per-key";r=0;t=7
  3100 ms  429 Too Many Requests
           Retry-After: 7
           RateLimit: "per-key";r=0;t=7
  9000 ms  429 Too Many Requests
           Retry-After: 1
           RateLimit: "per-key";r=0;t=1
 10500 ms  200 OK
           RateLimit: "per-key";r=0;t=1
 10600 ms  429 Too Many Requests
           Retry-After: 1
           RateLimit: "per-key";r=0;t=1

Recorded with Node.js 24.21.0 on macOS 26 arm64. To run it yourself: mise exec node@24.21.0 -- node respond.mjs

Read the responses from the top. Each success says how much quota is left (r) and the seconds (t) within which no more than that is available, here the time until the oldest request leaves the 10-second window. The sixth request, at 3.1 seconds, is refused with Retry-After: 7, because the first request leaves the window at 10 seconds. At 10.5 seconds a request passes, and the one 100 ms later is refused again: a sliding window gives back one unit at a time, not the whole quota at once.

Two more choices matter for the rest of the system. Answer 429 when a client is over its own allowance, and 503 Service Unavailable when the server is overloaded whatever the client did: clients should react differently to the two, and so should your monitoring. And expect retries. A client that honours Retry-After and adds a small random delay spreads its retries out, while one that retries at once, in a loop, turns a limit into extra load.

REST API Tester (Online API Client) Send requests to your own API and read the status codes and the Retry-After and RateLimit fields it answers with.

Checkpoint

Check: Telling a client it was limited

  1. Question 1 of 2 A sliding log allows 5 requests in any 10 seconds. A client's oldest request in the window was at 4.2 s, and a sixth request at 9.0 s is refused. What Retry-After, in whole seconds, should the response carry?

    Type a number.

    A hint

    When does the oldest request leave the window? Then round up.

    Show the answer: Question 1 of 2

    Answer: 6 s

    The oldest request leaves the window at 4.2 + 10 = 14.2 s, which is 5.2 s after 9.0 s; rounded up to a whole second, that is Retry-After: 6. Rounding down to 5 would bring the client back 0.2 s too early, to be refused again.

  2. Question 2 of 2 After a database failover your service is overloaded and turns away requests from every client, including those far below their limits. Which status should those responses carry?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: 503 Service Unavailable

    Answer 429 when a client is over its own allowance, and 503 when the server is overloaded whatever the client did. Clients should react differently to the two, and so should your alarms.

A safe limiter injects its clock and plans for failure

  • Inject the clock, and make it monotonic. Passing the time in, as every example here does, makes tests exact, and lets production pass a clock that never jumps backwards when the system time is corrected.
  • Choose the key with care. Use the authenticated identity whenever there is one. A network address is the only key for anonymous traffic, but many people can share one address, so limits on it must be loose.
  • Decide where the state lives. In one process it is a dictionary. Envoy’s local rate limit applies its limits per Envoy process by default (Envoy documentation), so ten proxies let through ten times the limit. One limit across a whole fleet needs a shared store, or a way to divide the limit between servers, which is the subject of the next lesson.
  • Decide what a broken limiter does. If the limiter itself fails, most APIs should let traffic through and raise an alarm rather than refuse everything; Stripe’s post describes catching every error in the limiter so that it fails open (Stripe). A limit that guards against abuse or cost may justify the opposite choice.

Step through ten proxies that each keep one customer’s limit in their own memory:

Interactive · step by step Ten proxies, ten copies of one limit Step through one customer's traffic as a load balancer spreads it over ten proxies that each count on their own.
Ten proxies, ten copies of one limit, step 6 of 6. Showing Customer, Load balancer, Proxy 1 (100 a second, all pass), Proxies 2 to 10 (900 a second, all pass), Service (receives 1,000 a second). In focus: Proxy 1, Proxies 2 to 10, Service.Customerlimit 100 a secondLoad balancerProxy 1100 a second, all passProxies 2 to 10900 a second, all passServicereceives 1,000 a second

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. One limit, ten copies. The customer may send 100 requests a second. Each proxy keeps that limit in its own memory, as a local rate limit does by default, so there are ten buckets of 100 a second.
  2. The customer sends 1,000. The customer sends 1,000 requests a second, ten times its limit, and the load balancer spreads them evenly over the ten proxies.
  3. Proxy 1 sees 100. Proxy 1 receives a tenth of the traffic, 100 requests a second. That is exactly its limit, so it passes every one.
  4. The other nine. Each of the other nine proxies sees 100 a second as well, and passes them all. Every proxy is enforcing the limit exactly.
  5. The service. The service receives 1,000 requests a second from one customer whose limit is 100. Ten correct local limits added up to ten times the limit.
  6. One count for the fleet. One limit across a fleet needs one count that every proxy consults, or a share of the limit for each proxy, which works only while traffic is spread evenly.

Every proxy enforced its limit exactly, and the service still received ten times what the customer was allowed.

Checkpoint

Check: Running a limiter safely

  1. Question 1 of 2 A customer may send 200 requests a second. Each of 8 proxies keeps that limit in its own memory, and the load balancer spreads the customer's requests evenly. At most how many requests a second can reach the service?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 1600 requests a second

    Each proxy allows up to 200 a second of what it sees, so 8 proxies allow 8 × 200 = 1,600 a second, eight times the limit. A shared count, or a split of the limit between the proxies, keeps it at 200.

  2. Question 2 of 2 A token bucket like this lesson's reads the time of day, and the server's clock is corrected 2 seconds backwards. What happens?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: It earns nothing until the clock passes its last update again, so clients are refused for up to 2 seconds longer than they should be

    A bucket computes what the time since its last update earned. When the time of day is corrected backwards, the lesson's code earns nothing until the clock passes its last update again, and code without that check would take tokens away. A monotonic clock never moves backwards, so neither can happen.

Practise: a token bucket with its clock passed in

Write the token bucket of this lesson with its clock passed in, in Python or JavaScript. The sample tests run in your browser and include a clock that goes backwards:

Exercise · Medium · Python, JavaScript

Build a token bucket that takes the time as an argument

Write a token bucket whose clock is injected: every method is given the current time now, in seconds, instead of reading a clock itself. Tests can then move time exactly, and a service can pass in a monotonic clock.

In Python, write the class TokenBucket in bucket.py; in JavaScript, export the class TokenBucket from bucket.mjs. The two versions behave the same:

  • TokenBucket(rate, capacity, now) (JavaScript: new TokenBucket(rate, capacity, now)) makes a full bucket at time now. It gains rate tokens a second (a rate may be a fraction, such as 0.5) and never holds more than capacity tokens.
  • allow(now, cost=1) first adds the tokens earned since the last call, rate × (now − last), without going above capacity. If the bucket then holds at least cost tokens, it takes them and returns true; otherwise it takes nothing and returns false.
  • retry_after(now, cost=1) (JavaScript: retryAfter(now, cost = 1)) returns how many seconds must pass before a request of cost tokens would be allowed: 0 if it would be allowed now. A request that costs more than capacity can never pass: raise ValueError (JavaScript: throw a RangeError).
  • Time that goes backwards (a now earlier than the last call) adds no tokens and changes nothing that a later call depends on.

For example, a bucket with rate=2 and capacity=3 allows three requests at 0 s, refuses a fourth, refuses one at 0.25 s (half a token) and allows one at 0.5 s. The sample tests import the class from your file and run in your browser.

Python · Starter code · bucket.py

class TokenBucket:
    def __init__(self, rate, capacity, now):
        """A full bucket at time `now` (seconds) that gains `rate` tokens a second and holds at most `capacity`."""
        # Replace this line with your code.
        pass

    def allow(self, now, cost=1):
        """Take `cost` tokens and return True, or take nothing and return False."""
        # Replace this line with your code.
        return False

    def retry_after(self, now, cost=1):
        """Seconds until a request of `cost` tokens would pass: 0 if it would pass now."""
        # Replace this line with your code.
        return 0
The sample tests · test_bucket.py
from bucket import TokenBucket


def test_starts_full():
    """a new bucket lets a burst of `capacity` requests through, then refuses"""
    bucket = TokenBucket(rate=2, capacity=3, now=0)
    assert [bucket.allow(0) for _ in range(4)] == [True, True, True, False]


def test_refills_at_the_rate():
    """tokens come back at `rate` a second, and a fraction of a token is not enough"""
    bucket = TokenBucket(rate=2, capacity=3, now=0)
    for _ in range(3):
        bucket.allow(0)
    assert bucket.allow(0.25) is False
    assert bucket.allow(0.5) is True
    assert bucket.allow(0.5) is False


def test_slow_rate():
    """a rate below one token a second works too"""
    bucket = TokenBucket(rate=0.5, capacity=1, now=0)
    assert bucket.allow(0) is True
    assert bucket.allow(1) is False
    assert bucket.allow(2) is True


def test_never_above_capacity():
    """a long pause never fills the bucket beyond its capacity"""
    bucket = TokenBucket(rate=2, capacity=3, now=0)
    assert [bucket.allow(100) for _ in range(4)] == [True, True, True, False]


def test_cost():
    """a request may cost several tokens, and a refused request takes none"""
    bucket = TokenBucket(rate=1, capacity=4, now=0)
    assert bucket.allow(0, cost=3) is True
    assert bucket.allow(0, cost=2) is False
    assert bucket.allow(0, cost=1) is True
    assert bucket.allow(0, cost=1) is False


def test_retry_after():
    """says how many seconds until a request would pass"""
    bucket = TokenBucket(rate=4, capacity=2, now=0)
    assert bucket.retry_after(0) == 0
    bucket.allow(0)
    bucket.allow(0)
    assert bucket.retry_after(0) == 0.25
    assert bucket.retry_after(0.125) == 0.125
    assert bucket.retry_after(0.125, cost=2) == 0.375


def test_retry_after_impossible():
    """a request that costs more than the bucket holds can never pass"""
    bucket = TokenBucket(rate=4, capacity=2, now=0)
    try:
        bucket.retry_after(0, cost=3)
    except ValueError:
        return
    assert False, "expected a ValueError"


def test_clock_going_back():
    """a time earlier than the last call earns nothing, now or later"""
    bucket = TokenBucket(rate=2, capacity=3, now=10)
    for _ in range(3):
        bucket.allow(10)
    assert bucket.allow(9) is False
    assert [bucket.allow(10.5) for _ in range(2)] == [True, False]

JavaScript · Starter code · bucket.mjs

export class TokenBucket {
  /** A full bucket at time `now` (seconds) that gains `rate` tokens a second and holds at most `capacity`. */
  constructor(rate, capacity, now) {
    // Replace this line with your code.
  }

  /** Take `cost` tokens and return true, or take nothing and return false. */
  allow(now, cost = 1) {
    // Replace this line with your code.
    return false;
  }

  /** Seconds until a request of `cost` tokens would pass: 0 if it would pass now. */
  retryAfter(now, cost = 1) {
    // Replace this line with your code.
    return 0;
  }
}
The sample tests · bucket.test.mjs
import { test, assert } from 'mysmartcopilot:test';
import { TokenBucket } from './bucket.mjs';

const burst = (bucket, now, n) => Array.from({ length: n }, () => bucket.allow(now));

test('a new bucket lets a burst of capacity requests through, then refuses', () => {
  assert.deepEqual(burst(new TokenBucket(2, 3, 0), 0, 4), [true, true, true, false]);
});

test('tokens come back at rate a second, and a fraction of a token is not enough', () => {
  const bucket = new TokenBucket(2, 3, 0);
  burst(bucket, 0, 3);
  assert.equal(bucket.allow(0.25), false);
  assert.equal(bucket.allow(0.5), true);
  assert.equal(bucket.allow(0.5), false);
});

test('a rate below one token a second works too', () => {
  const bucket = new TokenBucket(0.5, 1, 0);
  assert.equal(bucket.allow(0), true);
  assert.equal(bucket.allow(1), false);
  assert.equal(bucket.allow(2), true);
});

test('a long pause never fills the bucket beyond its capacity', () => {
  assert.deepEqual(burst(new TokenBucket(2, 3, 0), 100, 4), [true, true, true, false]);
});

test('a request may cost several tokens, and a refused request takes none', () => {
  const bucket = new TokenBucket(1, 4, 0);
  assert.equal(bucket.allow(0, 3), true);
  assert.equal(bucket.allow(0, 2), false);
  assert.equal(bucket.allow(0, 1), true);
  assert.equal(bucket.allow(0, 1), false);
});

test('says how many seconds until a request would pass', () => {
  const bucket = new TokenBucket(4, 2, 0);
  assert.equal(bucket.retryAfter(0), 0);
  burst(bucket, 0, 2);
  assert.equal(bucket.retryAfter(0), 0.25);
  assert.equal(bucket.retryAfter(0.125), 0.125);
  assert.equal(bucket.retryAfter(0.125, 2), 0.375);
});

test('a request that costs more than the bucket holds can never pass', () => {
  assert.throws(() => new TokenBucket(4, 2, 0).retryAfter(0, 3), RangeError);
});

test('a time earlier than the last call earns nothing, now or later', () => {
  const bucket = new TokenBucket(2, 3, 10);
  burst(bucket, 10, 3);
  assert.equal(bucket.allow(9), false);
  assert.deepEqual(burst(bucket, 10.5, 2), [true, false]);
});
A hint

Keep two numbers besides the settings: the tokens, and the time you last brought them up to date. Write one helper that every method calls first: if now is later than that time, add (now - last) * rate tokens, cap them at capacity and set last = now; if it is not later, do nothing at all. After that, allow is a comparison and a subtraction, and retry_after is the missing tokens divided by the rate.

The sample tests run on this device, in your browser (Pyodide, QuickJS): nothing is sent to mysmartcopilot.com. The first run of each language downloads it: Python (about 13.5 MB) or JavaScript (about 0.6 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

Then test yourself on the lesson’s eleven ideas, starting where your answers have been weakest:

Practice that adapts to you

Practise this lesson

18 questions about 11 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 18 Which of these are reasons the lesson gives for rate limits? Choose every one.

    Choose every answer that is right.

    Show the answer: Question 1 of 18

    Answer:

    • To share capacity fairly between clients who pay for the same service
    • To slow abuse such as password guessing and scraping
    • To cap costs that grow with every request
    • To protect capacity that all clients share

    Limits protect shared capacity, share it fairly, cap costs that grow with every request and slow abuse. The reason decides the algorithm: costs and abuse need exact numbers, fairness can live with an estimate.

  2. Question 2 of 18 In a token bucket of size b that gains r tokens a second, what does b decide?

    Choose one answer.

    Show the answer: Question 2 of 18

    Answer: The largest burst that can pass at once

    b is the bucket's size: what a quiet client can save and spend at once. r is what it earns each second, and any T seconds carry at most b + r × T requests.

  3. Question 3 of 18 A token bucket holds at most 20 tokens, gains 5 tokens a second and starts full. What is the largest number of requests it can allow in any 10 seconds?

    Type a number.

    Show the answer: Question 3 of 18

    Answer: 70 requests

    At most b + r × T: the 20 tokens the bucket holds at the start, plus the 5 × 10 = 50 it earns during the 10 seconds. A client that saved up its tokens can spend all 70 in that time, so the service behind the bucket must cope with 70, not with the 50 the rate alone suggests.

  4. Question 4 of 18 A plan promises 100 requests a second with bursts of up to 500. What is the most that one key's bucket can send to the service in any 2 seconds?

    Type a number.

    A hint

    Size and rate both count, over the whole 2 seconds.

    Show the answer: Question 4 of 18

    Answer: 700 requests

    b + r × T = 500 + 100 × 2 = 700. Sizing the service for the plan's 100 a second alone would leave it 500 requests short at the worst moment.

  5. Question 5 of 18 What does a leaky bucket used as a queue do with a burst that a token bucket would let through at once?

    Choose one answer.

    Show the answer: Question 5 of 18

    Answer: It queues the burst and releases it at an even pace, so the requests wait

    A token bucket limits how much passes and adds no delay; a leaky bucket decides when work reaches the service. In the lesson's run, the tenth request of the burst waited 1.8 seconds.

  6. Question 6 of 18 Why does GCRA need half the state of the lesson's token bucket for the same decisions?

    Choose one answer.

    Show the answer: Question 6 of 18

    Answer: It keeps one number per key, the theoretical arrival time, instead of the tokens and the time of the last refill

    GCRA's theoretical arrival time moves forward one interval with every request it allows, and a request may come early by up to the tolerance. That single number makes the same decisions as a token bucket's two, which matters for millions of keys.

  7. Question 7 of 18 What does a fixed window keep for each key?

    Choose one answer.

    Show the answer: Question 7 of 18

    Answer: The current window and its count

    A fixed window keeps the window it is counting and the count, and starts again at zero when the next window begins. That makes it cheap on a shared store and blind at the edge.

  8. Question 8 of 18 An API allows 100 requests a minute, counted in fixed windows that start at each clock minute. What is the most a client can get through in the last second of one minute and the first second of the next?

    Choose one answer.

    Show the answer: Question 8 of 18

    Answer: 200

    The count starts again at zero when the new minute begins. A client that sends 100 requests in the last second of a minute and 100 more in the first second of the next gets all 200 through in two seconds, twice the limit. A sliding log would have refused the second hundred.

  9. Question 9 of 18 Which algorithm needs more memory per key as the limit grows?

    Choose one answer.

    Show the answer: Question 9 of 18

    Answer: Sliding log

    A sliding log keeps one timestamp for every request it allowed in the last window, so a limit of 1,000 an hour means up to 1,000 timestamps per busy key. The others keep two or three numbers per key whatever the limit.

  10. Question 10 of 18 Which statements about the sliding window counter are true?

    Choose every answer that is right.

    Show the answer: Question 10 of 18

    Answer:

    • It keeps two counts and the current window for each key.
    • It can refuse a request even though fewer than the limit got through in the last full window.
    • It assumes the previous window's requests were spread evenly across that window.

    The estimate weighs the previous window's count by how much of that window still overlaps the last full window, as if its requests were spread evenly. When they were not, it is wrong either way: a burst at the end of the previous window is under-counted (the lesson's run let 199 through in 60 seconds against a limit of 100), and requests early in it are still counted after they have left the real window, so it can also refuse too early.

  11. Question 11 of 18 A sliding window counter allows 10 per 10 s, and the previous window allowed 10. A test sends 10 requests 1 ms apart from half-way through the next window, expects 5 to pass and sees 6. Why?

    Choose one answer.

    Show the answer: Question 11 of 18

    Answer: The previous window's weight falls with every millisecond, so its estimated share drops below 5 during the burst

    At 15.005 s the previous window counts 10 × 4,995 / 10,000 = 4.995, and 4.995 + 5 is still below 10, so the sixth request passes. Sent within the same millisecond, the burst gets exactly 5. Tests of time-based limiters need an injected clock that fixes every request's time.

  12. Question 12 of 18 On the lesson's 20-second trace, which limiter served the most requests, and why?

    Choose one answer.

    Show the answer: Question 12 of 18

    Answer: The leaky bucket, 145, because it delays requests instead of refusing them

    The leaky bucket served 145 of the 202 requests, because it turns bursts into waiting; the token bucket served 142, the fixed window 128, the sliding window counter 124 and the sliding log 118.

  13. Question 13 of 18 A sliding log stores an 8-byte timestamp for each allowed request. With a limit of 500 requests an hour and 1 million keys all at their limit, how many megabytes does it hold (1 MB = 1,000,000 bytes)?

    Type a number.

    Show the answer: Question 13 of 18

    Answer: 4000 MB

    500 timestamps × 8 bytes × 1,000,000 keys = 4,000,000,000 bytes, which is 4,000 MB or 4 GB. A token bucket for the same keys would hold 2 numbers each: 16 MB.

  14. Question 14 of 18 On steady traffic at the limit's own rate, how close did the sliding window counter come to its limit of 100 requests in any 60 seconds?

    Choose one answer.

    Show the answer: Question 14 of 18

    Answer: 108 in its busiest minute

    On steady traffic the counter's busiest minute held 108 requests at the limit's rate and 101 at twice that rate, against 118 and 120 for the fixed window. Bursts made it worse, 129 and 124, and shaped traffic 199.

  15. Question 15 of 18 For a public API sold by plan, which key and algorithm does the lesson recommend?

    Choose one answer.

    Show the answer: Question 15 of 18

    Answer: A token bucket per API key, with the plan's rate and a burst size the service can absorb

    A public API sold by plan uses a token bucket per API key: the rate from the plan and a burst size from what the service can absorb. A daily or monthly quota on top can be a fixed window.

  16. Question 16 of 18 Your service calls a partner API whose contract allows at most 50 requests a second; calls can wait up to a second, but bursts above 50 a second are rejected by the partner. What do you put in front of the partner?

    Choose one answer.

    Show the answer: Question 16 of 18

    Answer: A leaky bucket (or pacing) that sends at most 50 a second, evenly, and queues the rest briefly

    The partner cannot take bursts, and the work can wait, which is exactly what a queue that drains at a steady rate provides. A token bucket of 500 would release a burst of 500 at once, and a fixed window could send 100 within a moment around the edge of a second. Retrying rejected calls adds load to a partner that is already at its limit.

  17. Question 17 of 18 A client gets 429 Too Many Requests with the field Retry-After set to 7. What should it do?

    Choose one answer.

    Show the answer: Question 17 of 18

    Answer: Wait at least 7 seconds, adding a little random delay, before sending the request again

    Retry-After gives the delay in seconds (or an HTTP date). Waiting at least that long and adding a small random delay keeps clients that were refused together from all returning together. Retrying at once only adds load, and rotating keys to get around a limit breaks the API's terms.

  18. Question 18 of 18 The store behind your limiter stops answering. What should the plan limits of a public API do, and which limits might choose the opposite?

    Choose one answer.

    Show the answer: Question 18 of 18

    Answer: Let requests through and raise an alarm; a limit that guards against abuse or cost may refuse instead

    Most APIs should fail open, letting traffic through and raising an alarm, as Stripe's post describes; a limit that guards against abuse or cost may justify failing closed. Decide it per limit before the store fails.

Interview questions

What is the difference between a token bucket and a leaky bucket? In a token bucket, tokens drip in at a steady rate up to a capacity, and each request takes one: requests pass at once while tokens last, so bursts up to the capacity go through and the long-run rate is the refill rate. In a leaky bucket used as a queue, the requests themselves wait and leave at a steady rate: the service sees an even stream, a burst turns into waiting time, and requests that find the bucket full are refused. So a token bucket limits how much passes and adds no delay, while a leaky bucket decides when work reaches the service. Used as a meter without a queue, a leaky bucket makes the same decisions as a token bucket; ITU-T I.371 defines that meter, the generic cell rate algorithm, in two equivalent forms.

How does an HTTP API tell a client that it is being rate limited, and when it may try again? With status 429 Too Many Requests, defined in RFC 6585, which should explain the condition and may carry a Retry-After field. Retry-After, defined in RFC 9110, gives a number of seconds or an HTTP date; the client should wait at least that long and add a small random delay, so that many clients do not return at the same instant. Many APIs also describe the quota on every response; the RateLimit-Policy and RateLimit fields of an IETF Internet-Draft do this in a standard form, but they are not a standard yet. Caches must not store a 429 response, and an overload that has nothing to do with one client’s allowance is better reported as 503 Service Unavailable.

An interviewer will usually push on one of these answers. Choose your reply to each of three likely follow-ups:

Checkpoint

Interview round: three follow-up questions

  1. Question 1 of 3 Follow-up: your token bucket holds 20 tokens and gains 5 a second. After 10 quiet seconds, how many requests can a client send in the next second, and does it matter?

    Choose one answer.

    Show the answer: Question 1 of 3

    Answer: 25, the 20 it saved and 5 earned, and the service behind it must be sized for that burst

    Quiet time fills the bucket up to its size and no further, so the next second carries b + r × 1 = 20 + 5 = 25 requests. Choose b from the largest burst the service can absorb.

  2. Question 2 of 3 Follow-up: a leaky bucket in front of a partner holds 50 requests and releases 10 a second. During a spike it is full. What do new requests get, and what should the caller do?

    Choose one answer.

    Show the answer: Question 2 of 3

    Answer: They are refused at once, and the caller should back off with a random delay or drop the work, not retry at once

    A full leaky bucket refuses new requests, and its size bounds the wait of the accepted ones: 50 at 10 a second is 5 seconds. Callers should back off with a random delay, or drop work that can no longer be useful.

  3. Question 3 of 3 Follow-up: 2,000 clients receive 429 with Retry-After: 3 in the same second. What should each of them do, and why?

    Choose one answer.

    Show the answer: Question 3 of 3

    Answer: Wait at least 3 seconds plus a small random delay, so that the 2,000 do not all return in the same instant

    Retry-After gives the shortest wait. A small random delay on top spreads the clients' returns, so they do not arrive as one burst that is refused again.

Key takeaways

  • A token bucket allows bursts up to its size b and r a second after that, so any T seconds carry at most b + r × T requests; GCRA makes the same decisions with one number per key.
  • A leaky bucket queues requests and releases them at an even rate: no burst reaches the service, and requests wait instead.
  • A fixed window is the cheapest and lets twice the limit through at a window’s edge, and every client starts again at the same instant.
  • A sliding log is exact and stores a timestamp per request: use it for small limits that must hold.
  • A sliding window counter estimates from two counts: close on steady traffic, but up to about twice the limit on traffic shaped against it.
  • Refuse with 429 and a Retry-After rounded up to a whole second, describe limits with the RateLimit fields (still a draft), and keep 503 for overload.

That was a complete case study. 67 more case studies have in-depth parts that open with any pass.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.