Design a rate limiter
medium 75 minA 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
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
1986
Jonathan Turner describes the leaky bucket for communication networks: a counter for each user that drips down at a steady rate.
April 2012
RFC 6585 gives HTTP the status 429, Too Many Requests.
June 2022
RFC 9110 describes
Retry-Afteras 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.
- 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
- 2ScopeAsk what changes the design, then commit to a short list.
- 3API and dataThe contract first, then the data that serves it.
- 4DesignStart with the smallest system that works. Change it only when something breaks.
- 5Deep divesCompare the options before you open them, then say which you would pick.
- 6Explain your choicesAnswer first. Then compare your reasoning.
- 7By levelThe same question is judged differently for mid, senior and staff.
- 8MockAnswer against the clock, then score yourself.
How it works
Step through the idea, or press Play.
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.
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
| Ask | Changes |
|---|---|
| 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
| Way | State for a key | Promise | Weak point |
|---|---|---|---|
| Fixed window | Slot and count | At most n in each slot | Up to 2n around the edge of a slot |
| Sliding log | A time for each call | At most n in any stretch, exactly | Memory grows with n |
| Sliding counter | Two counts and a slot | About n in any stretch | An estimate: assumes even traffic in the last slot |
| Token bucket | Credit and a time | Speed n, burst b on top | In a stretch as long as the period: up to b more than n |
| Leaky bucket as a queue | Waiting calls | A smooth outflow | Calls wait, and the queue can be full |
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
One token in 2 s, burst 3. Credit counted in seconds, a token is worth 2
| Time | Happens | Credit before | Credit after | Answer |
|---|---|---|---|---|
| 0 s | three calls | 6 | 0 | yes, yes, yes |
| 0 s | a fourth | 0 | 0 | no, wait 2 s |
| 1.5 s | a call | 1.5 | 1.5 | no, wait 0.5 s |
| 2 s | a call | 2 | 0 | yes |
| 8 s | cost 3 | 6 | 0 | yes |
| 100 s | nobody asked | 6, not 92 | 6 | full is full |
First try
The design most people draw first
The design to avoid: kinds as classes, a thread for time
1/3One map, one thread
A thread walks over all keys each second and adds tokens. Most of the keys sleep.
extends (is a)
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?Better
The design to reach
The design to reach: shared rules, one meter for each key
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
What each class knows, and does not know
| Class | Knows | Does not know |
|---|---|---|
| Rule | The numbers, and how to make a meter | Any key |
| Meter | What one key used | Its key, locks, the clock |
| Stripe | A lock and a table | What a limit is |
| RateLimiter | Which rules must agree | Users, HTTP, plans |
| Decision | The answer | How 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
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
- Guava: RateLimiter source
- Guava: SmoothRateLimiter source
- Go: golang.org/x/time/rate
- Bucket4j
- Resilience4j: RateLimiter
- nginx: ngx_http_limit_req_module
- Envoy: local rate limit filter
- .NET blog: announcing rate limiting
- AWS: API Gateway request throttling
- Stripe: scaling your API with rate limiters
- Linux manual: tc-tbf
- Cloudflare: counting things, a lot of different things
- RFC 6585: additional HTTP status codes
- RFC 9110: HTTP semantics
- IETF draft: RateLimit header fields
- Python documentation: time.monotonic_ns
- Java SE 21 API: System.nanoTime
- Wikipedia: Leaky bucket
- Wikipedia: Generic cell rate algorithm