AlgoViz

Design a rate limiter

medium 75 min

A rate limiter inside one process: token bucket behind an interface, exact under threads, several rules at once, and keys that are safely forgotten.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:49

Theory

Read or listen first. About 2 min.

What it is

A rate limiter decides whether a caller may go on now. It counts for each key against one or more rules, and answers yes, or no with a time to wait.

The classic way of counting is the token bucket: tokens drip in at a steady speed, up to a limit, and each call takes some. Idle time is saved up, but only so far. That allows short bursts and bounds the long run.

As a class design problem it is small and sharp: one public method, two interfaces, one lock in the right place. Nearly everything that can go wrong in concurrent code can go wrong in these fifty lines.

Why it exists

Every service has something that can be used up: a database, a phone line for texts, money. Without a limit one caller, by mistake or on purpose, takes it from all others.

A limit turns an overload into a clear answer. The caller learns that it was too much and when it will work again. Without it, everybody gets slow answers and nobody knows why.

The same code is needed on the other side: a client that must not exceed the limit of somebody else's service uses the same bucket, only with waiting.

A short history

  1. 1986

    Jonathan Turner describes the leaky bucket for communication networks: a counter for each user that drips down at a steady rate.

  2. April 2012

    RFC 6585 gives HTTP the status 429, Too Many Requests.

  3. June 2022

    RFC 9110 describes Retry-After as a date or as a number of seconds.

Words to know

Key
Who or what is counted. A string for the limiter.
Rate
So many in so long, on average.
Burst
How many may come at once after a pause.
Token bucket
Tokens drip in up to the burst, calls take them.
Leaky bucket
As a meter it is the token bucket seen upside down. As a queue it smooths the outflow.
Fixed window
A count for each slot of time.
Sliding window
The window ends now and moves along.
GCRA
A token bucket kept as one time.
Striped lock
A fixed number of locks, a key always meets the same one.
Fail open
If the limiter breaks, calls go through.
Concurrency limit
How many at the same time. Permits must be given back.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

Solve it like an interview

New to it? Start with Approach. Revising? Go straight to the mock.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 4

Find. The key chooses a stripe, the stripe has the meters.

Understand it

Start here

Three cups, and one more every ten minutes

A rate limiter answers one question many times a second: may this caller go on now? It protects a service from too much of anything, be it a mistake, an attack or a success. The question sounds like counting. It is really about time, and about two callers who ask at the same moment.

The dripping barrels at the mountain hut
09:00AshaLeeone cup drips in 10 minutes

Four things to keep apart

  • The key

    Who is counted: user, address, API key, or everybody together. For us it is only a string.

  • The rule

    How many, in how long, how many at once. Shared by all keys, never changed.

  • The meter

    What one key has used under one rule. Small, changing, guarded by a lock.

  • The answer

    Yes or no, what is left, and how long to wait.

The life of one question

Questions

Seven questions, and what each answer changes

AskChanges
One process or many?A lock in memory, or a shared store. We take one process
Counted per what?The key. Also: who may choose keys?
Are bursts welcome?Token bucket if yes, a small burst if not
Refuse or wait?try_acquire returns a wait. Waiting is built on top
Does everything cost the same?A cost with each call
Several limits at once?All must agree before any is charged
How many keys?Forgetting, and memory for each key

Algorithms

Five ways to count, in one table

WayState for a keyPromiseWeak point
Fixed windowSlot and countAt most n in each slotUp to 2n around the edge of a slot
Sliding logA time for each callAt most n in any stretch, exactlyMemory grows with n
Sliding counterTwo counts and a slotAbout n in any stretchAn estimate: assumes even traffic in the last slot
Token bucketCredit and a timeSpeed n, burst b on topIn a stretch as long as the period: up to b more than n
Leaky bucket as a queueWaiting callsA smooth outflowCalls wait, and the queue can be full
We build the first, second and fourth, and add the third as a follow-up. One interface carries all four.

Which one?

Time

Nobody carries water

The picture of a bucket makes people write a thread that adds tokens. It is not needed. Remember how much there was and when that was true. When somebody asks, work out what has dripped in since. A key that nobody uses costs nothing.

Credit at a later time

cnow=min⁡(b⋅P,;cthen+(tnow−tthen)⋅n)c_{now} = \min\bigl(b \cdot P,; c_{then} + (t_{now} - t_{then}) \cdot n\bigr)
n tokens drip in every period P, at most b fit. One token is worth P units of credit, so everything stays a whole number.

One token in 2 s, burst 3. Credit counted in seconds, a token is worth 2

TimeHappensCredit beforeCredit afterAnswer
0 sthree calls60yes, yes, yes
0 sa fourth00no, wait 2 s
1.5 sa call1.51.5no, wait 0.5 s
2 sa call20yes
8 scost 360yes
100 snobody asked6, not 926full is full

First try

The design most people draw first

The design to avoid: kinds as classes, a thread for time

RateLimiter- tokens: Map<Key, double>- refiller: Thread+ allow(key, kind): bool

1/3One map, one thread

A thread walks over all keys each second and adds tokens. Most of the keys sleep.

extends (is a)

A key is a string and a plan is two numbers. Only the way of counting deserves a class.
Python
class RateLimiter:    def __init__(self):        self.tokens = {}                          # only grows        threading.Thread(target=self.refill).start()    def refill(self):        while True:            for key in self.tokens:               # a million keys, every second                self.tokens[key] = min(5.0, self.tokens[key] + 0.1)            time.sleep(1)                         # and 0.1 is not exactly 0.1    def allow(self, key, kind):        if kind == "premium":                     # one if for each kind of customer            return True        if self.tokens.get(key, 5.0) >= 1:        # ask            self.tokens[key] = self.tokens.get(key, 5.0) - 1   # act: too late            return True        return False                              # for how long?
Six problems: a thread for keys nobody uses, a table that only grows, floats, kinds as ifs, asking and acting apart, and a bare no.

Better

The design to reach

The design to reach: shared rules, one meter for each key

answersRateLimiter- rules: List<Rule>- stripes: Stripe[]- clock: Clock+ tryAcquire(key, cost)+ keys(): intDecisionallowed: boolremaining: intwaitNs: long

1/5One question, one answer

May this key do something that costs this much? The answer also says what is left and how long to wait.

owns (dies together)depends onhas (lives on)implements

The table of a stripe holds one list of meters for each key, in the order of the rules.

What each class knows, and does not know

ClassKnowsDoes not know
RuleThe numbers, and how to make a meterAny key
MeterWhat one key usedIts key, locks, the clock
StripeA lock and a tableWhat a limit is
RateLimiterWhich rules must agreeUsers, HTTP, plans
DecisionThe answerHow it came about

How do you fill the buckets?

BreaksA thread that adds tokens each second
How
Walk over all keys.
Limit
Work for keys that sleep, a race with every caller, and steps of a second.
Choose when
Never.
WorksA timer for each key
How
It fires when the next token is due.
Limit
As many timers as keys.
Choose when
Few keys, and somebody waits for each token.
StrongWork it out when asked
How
Credit and the time when it was true.
Limit
Two numbers and one multiplication.
Choose when
Always.

Life

The life of a key

Unknown and full are the same

Because Full and Unknown give the same answers, forgetting a full key can never be noticed.

Threads

Two calls, one token

Without a lock

Ask and spend under one lock

Several rules

All of them, or none

Five a second and a hundred a day. If the first limiter takes its token and the second says no, the caller has paid for nothing. So a meter has two methods and not one: wait asks and changes nothing that matters, spend charges. The limiter asks all, takes the longest wait, and charges only if it is zero.

Ask all, then charge all

  • A refused call is free
  • The answer holds the longest wait
  • The order of the rules does not matter

Try one after another

  • A refused call has paid the first rules
  • Giving back later is another race
  • Callers that retry empty themselves

Summary

The whole topic in one minute.

A key, a rule that all keys share, a meter for each key, an answer with a wait. The meter keeps credit and the time when it was true, and time does the rest. A token is worth one period, so all numbers are whole.

Three things are one step under the lock of a stripe: ask and spend, look and create, decide and delete. Several rules are all asked before any is charged. A meter that is as good as new can be deleted, because a missing key gives the same answer.

  • Key, rule, meter, answer: four things, four types.
  • Time fills the bucket. Store credit and when it was true.
  • One token is worth one period. Then there are no fractions.
  • Ask and spend under one lock, and read the clock inside it.
  • Several rules: ask all, charge all or none.
  • A lock for a group of keys. Other groups do not wait.
  • Full and forgotten are the same, so forgetting is free.
  • A no without a waiting time makes callers hammer.

Sources