AlgoViz

Rate limiter algorithms

medium 30 min

Token bucket, leaky bucket, fixed window, sliding log and sliding counter: how each one counts, what it lets through, what it stores, and which to choose.

Video lesson · Chapter 1 of 5

A ten-token bucket refills by the second

0:00 / 4:34

Five limiter algorithms in 80 seconds

1:20Reel coming soon

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

Token bucket rate limiter

1:17Reel

Theory

Read or listen first. About 1 min.

What it is

A rate limiting algorithm answers one question: may this request pass now, given the earlier ones? It must answer quickly and store little for each caller.

There are two families. Buckets model a supply that fills or drains at a steady rate. Windows count requests in a stretch of time.

In one line: token bucket for bursts, leaky bucket for an even flow, sliding windows for a steady count.

Why it exists

Two limits that both say 100 a minute can behave very differently. One lets 200 through in two seconds, another makes calls wait, a third stores every call.

The choice decides what a caller notices, how much memory ten million callers need, and whether the service behind sees waves or a smooth flow.

A short history

  1. 1986

    Jonathan Turner is credited with the original description of the leaky bucket: a counter that rises with each packet and falls steadily.

  2. 1995

    The ATM Forum publishes its User-Network Interface specification 3.1, which describes the generic cell rate algorithm, a leaky bucket as a meter.

  3. 1999

    RFC 2697 describes a traffic marker built from two token buckets.

  4. 2017

    Cloudflare describes the sliding window counter and measures it on 400 million requests.

Words to know

Token
Permission for one request, or for one unit of work.
Capacity
The most tokens a bucket holds: the largest burst.
Refill rate
Tokens added each second: the lasting average.
Lazy refill
Compute the tokens when a request comes, instead of with a timer.
Shaping
Delaying requests so that they leave evenly.
Policing
Refusing what is too much, without delay.
Boundary problem
Twice the limit around the edge of two fixed windows.
GCRA
A leaky bucket kept as one time: when the next call is expected.

How it works

Step through the idea, or press Play.

Step 1 of 3

Read state. A few numbers for this caller

Understand it

Start here

A carousel and a leaking bucket

Two buckets at the fair
1 a minute

One bucket stores permission, the other stores work.

All five at a glance

AlgorithmBurstsStored for each callerExactnessBest for
Token bucketUp to the capacity2 numbersExact for its own ruleAPIs
Leaky bucket (queue)SmoothedThe waiting requestsExact rate outProtecting something that needs an even rate
Fixed windowDouble at the edge1 numberLow near the edgeLong quotas, simple counts
Sliding logUp to the limit1 time per requestExactSmall strict limits
Sliding counterNearly the limit2 numbersClose estimateGeneral use

Bucket 1

Token bucket

  1. 1

    Fill

    Tokens are added at a fixed rate, for example 2 a second.

  2. 2

    Hold

    At most the capacity, for example 10. The rest is lost.

  3. 3

    Take

    A request takes one token, or more if it costs more. Not enough tokens: refused.

Lazy refill

tokens=min⁡(C,;tokens+(tnow−tlast)×r)min⁡(10,;1.4+0.7×2)=2.8\text{tokens} = \min\big(C,; \text{tokens} + (t_{now} - t_{last}) \times r\big) \qquad \min(10,; 1.4 + 0.7 \times 2) = 2.8
No timer is needed. Two numbers for each caller: tokens and the time of the last update.

The most that can pass

N(t)≤C+r tC=10, r=2/s:N(60)≤10+120=130N(t) \le C + r\,t \qquad C = 10,\ r = 2/\text{s}:\quad N(60) \le 10 + 120 = 130
So a bucket with 100 a minute on average can let more than 100 through in its first minute. To promise at most 100 in any minute, choose C + 60r = 100.

Good

  • Allows honest bursts
  • Two numbers for each caller
  • Little work
  • A costly call can take several tokens

Not so good

  • A burst can hit a weak service
  • Says nothing about gaps between calls
  • Two numbers to choose
  • Needs one atomic step when shared

Bucket 2

Leaky bucket

  1. 1

    Join

    A request joins a queue, the bucket.

  2. 2

    Leak

    Requests leave the queue at a constant rate.

  3. 3

    Overflow

    If the queue is full, a new request is refused.

Token or leaky?

Token bucketLeaky queue
OutputCan come in burstsEven
ControlsThe average, and the largest burstThe exact rate out
Extra waitingNoneUp to queue length divided by rate
Idle timeSaved as tokensNot saved
UseAPI limitsShaping traffic to a fixed-rate system
A queue of 5 that leaks 1 a second makes the last one wait 5 seconds. Is the caller still there?

Window 1

Fixed window

One counter for each caller and minute. It starts again at each full minute. Very cheap, and easy to explain: it suits quotas per day or month.

The boundary problem

100⏟00:59+100⏟01:01=200 in 2 seconds, with a limit of 100 a minute\underbrace{100}_{00:59} + \underbrace{100}_{01:01} = 200 \text{ in 2 seconds, with a limit of 100 a minute}
Both minutes are within their limit. Up to twice the limit passes around the edge.

Window 2

Sliding log

Store the time of each passed request. On a new one, drop those older than 60 seconds and count the rest. Exact, at the price of one entry for each request. Count only what passed: if refused calls are stored as well, a caller who keeps trying is never let in again.

Memory of a log

10 M callers×1,000 calls×8 B=80 GBtwo counters: 10 M×16 B=160 MB10\,\text{M callers} \times 1{,}000\ \text{calls} \times 8\,\text{B} = 80\,\text{GB} \qquad \text{two counters: } 10\,\text{M} \times 16\,\text{B} = 160\,\text{MB}
Bare numbers; a real store adds overhead for each entry and key. The factor of 500 is the point.

Window 3

Sliding counter

Keep two counters: the current window and the one before. Assume the previous requests were spread evenly, and count the part that still lies inside the last 60 seconds.

The estimate

estimate=previous×(1−part of current window)+current=70×0.75+30=82.5\text{estimate} = \text{previous} \times (1 - \text{part of current window}) + \text{current} = 70 \times 0.75 + 30 = 82.5
15 seconds into the minute: 25% has passed, so 75% of the previous minute still counts.

A sliding counter decides

Cloudflare measured it on 400 million requests from 270,000 sources: 0.003% were wrongly allowed or limited, and the estimated rate differed from the real one by 6% on average.

Bonus

GCRA: one number

The generic cell rate algorithm keeps only the theoretical arrival time: when the next call is expected if calls come evenly. A call may be early by at most the burst allowance. One number for each caller, no timer, and the waiting time comes for free.

Python
def gcra(tat, now, T, burst):    """Returns (allowed, new tat, seconds to wait)."""    tat = max(tat, now)    early = tat - now    if early > (burst - 1) * T + 1e-9:        return False, tat, early - (burst - 1) * T    return True, tat + T, 0.0tat = 0.0for now in (0, 0, 0, 0, 1):          # one a second, burst of 3    ok, tat, wait = gcra(tat, now, 1.0, 3)    print(now, ok, wait)
Three lines of logic. T is the time between calls, burst is how many may come at once.
Edit and run it in your browser

Place

Where the state lives

The gateway decides, the store remembers

A client calls the API gateway. The gateway runs one script in Redis. Redis holds the small state for this caller: a token bucket with two numbers. Allowed requests go on to the service. Orange shows the state call.
Read, compute and write in one atomic step. Sharing, failures and regions: design a rate limiter.

A token bucket decides

A leaky queue in time

Compare

The same traffic, four answers

Limit 100 a minute. 100 calls at 00:59, 100 calls at 01:01

AlgorithmFirst 100Second 100Together
Fixed window100 pass100 pass200
Sliding log100 pass0 pass100
Sliding counter100 pass2 pass102
Token bucket, capacity 100, 100 a minute100 pass3 pass103
Sliding counter: at 01:01 the previous minute still counts 100 × 59 / 60 = 98.3, so two more pass (99.3, then 100.3 is over). Token bucket: two seconds refill 3.33 tokens.

Choosing

One sentence each

  • Token bucket

    Save up, then spend.

  • Leaky queue

    Whatever comes in, the same goes out.

  • Fixed window

    A new page each minute.

  • Sliding log

    Remember everything.

  • Sliding counter

    Remember two pages and estimate.

Implement

Details that go wrong

Do

  • Refill lazily
  • Keep the fraction of a token or a leak
  • Use one clock, the store's
  • Expire state of idle callers
  • Return the waiting time

Do not

  • Run a timer for each caller
  • Set the last time to now after rounding down
  • Read and write in two calls
  • Let time go backwards: use a later-of rule
  • Store refused calls in the log

Summary

The whole topic in one minute.

Token bucket is the usual default for APIs: bursts up to the capacity, a steady average, two stored numbers. A leaky queue sends at an even rate and adds waiting.

Fixed windows are the cheapest and allow twice the limit at the edge. A sliding log is exact and large. A sliding counter is nearly as good with two numbers.

  • Token bucket: capacity is the burst, refill is the average, at most C + r × t pass.
  • Leaky queue: even output, extra waiting, refuses when full.
  • Fixed window: cheap, up to double at the edge.
  • Sliding log: exact, one entry for each request. Sliding counter: two numbers and a good estimate.
  • Whatever you choose, one atomic step and one clock.

Sources