Walkthrough: in-process rate limiter
What you will learn on this page
Section titled “What you will learn on this page”- How to turn “stop one client from flooding us” into questions whose answers change the design, and how to keep the product owner’s answers apart from your own assumptions.
- How to compare three well-known rate-limiting algorithms (fixed window, sliding log, token bucket) on what they allow at the edges, how much memory they need per client, and how precise they are, and how to pick one for a stated need rather than by name.
- How to represent fractions of a token with whole numbers so that the limiter never drifts, and how to round a “retry after” hint so that it is never too early.
- How to bound memory without letting a client get a second burst, what one mutex protects, and why the clock is read while holding it.
- How an injected clock makes timing tests exact, what ThreadSanitizer proves about the threaded tests and what it does not, and how a later change (tiers that change at run time) lands in the design.
How to use this walkthrough
Section titled “How to use this walkthrough”The page is a series of stages, in the order a designer meets them. Each stage starts with a question for you. Stop and answer it, on paper or in your head, before you open the stage. Then compare. At most stages more than one answer is reasonable, and the stage says which parts are judgement.
Each stage opens with its “Show stage” button. It is a normal disclosure control: it works with the keyboard (Tab to it, then Enter or Space) and without JavaScript. Nothing is saved; the stages are closed again when you reload the page.
This walkthrough assumes you know what a mutex and a data race are, as covered in Thread safety. If you have not done the coffee kiosk walkthrough, it introduces the same stages on a simpler, single-threaded problem.
The code is the example examples/practice/walkthroughs/rate-limiter, in
two steps. Step 1 is the design chosen at stage 6. Step 2 is the same
program after the changed requirement in stage 8.
Stage 1: the problem statement
Section titled “Stage 1: the problem statement”Think first. The product owner of an internal service is about to describe a problem. What will you listen for, and what will you write down?
Show stage 1: what the product owner says
“Last week one customer’s script went wrong and sent us thousands of requests a second. Everyone else’s requests slowed to a crawl. We need to stop one client from flooding us. It should go inside the service itself, not in some new box in front of it. Normal customers should never notice it.”
Things worth writing down, because they are nouns and verbs you will need: client, request, stop (refuse), flooding (too many, too fast), inside the service. And one quality: normal use must not be affected.
Things that are missing, because the owner does not think of them as decisions:
- What is “one client”? An account, an API key, an IP address, a user? The limiter cannot decide this; it has to be told.
- What is “flooding”? A number of requests in what time? Is a short burst flooding, or only a sustained rate?
- What does a refused client get? An error, a delay, a queue?
- How many clients are there? Memory per client matters if there are millions.
- “Inside the service” means one process with many request threads, which makes thread safety a requirement from the start. It also means each copy of the service limits on its own.
“Normal customers should never notice it” is not testable as written. It is a hint that the limit must allow ordinary bursts (a page that loads and makes ten calls at once) and must cost little per request.
Stage 2: clarifying questions
Section titled “Stage 2: clarifying questions”Think first. Write five questions you would ask before designing anything. For each, say how the answer would change the design. Then open the stage.
Show stage 2: the questions and the answers
In the table, Owner means the product owner gave that answer. Assumption means the designer chose it and the owner did not object; it is written down so that it can be checked later, as described in Assumptions.
| Question | Answer | Kind |
|---|---|---|
| Is the limit per client or for the whole service? | Per client. A global limit would let the flooding client use up everyone’s share. | Owner |
| What identifies a client? | The service passes in a key (today, the account id). The limiter treats it as an opaque string and compares it exactly. | Owner, then design |
| Is it a steady rate, or are bursts allowed? | Both: a client may make a short burst (a page making several calls at once), then must slow to a steady rate. | Owner |
| Does every client get the same limit? | Yes, for now: one setting for everyone, chosen at start-up. | Owner |
| Do all requests count the same? | Yes. One request is one unit. | Owner |
| What does a refused caller get? | An answer, not an exception: “refused”, with a hint of when to retry. The service turns it into an HTTP 429 with a Retry-After header. The limiter itself knows nothing about HTTP. | Owner, then design |
| Should a refused request wait in a queue instead? | No. Refuse at once; the caller decides whether to retry. | Owner |
| How exact must the retry hint be? | Whole milliseconds, never too early: a retry at exactly the hint must succeed if nobody else spent the token. | Assumption, accepted |
| How many clients? | Usually hundreds, but a bug or an attack could invent new keys without end. Memory must stay bounded. | Owner |
| When the bound is reached and a new client arrives? | Refuse the new client rather than give an existing client a fresh burst. | Assumption, accepted |
| Which clock? | A steady clock, which never goes back when someone changes the date. Injected, so tests control time. | Assumption |
| How many threads call it? | Many: every request thread asks before doing work. | Owner |
| Several copies of the service? | Today there is one. If there are more later, each limits on its own; a shared limit is out of scope. | Owner |
| After a restart? | Every client starts with a full allowance. Nothing is saved. | Assumption, accepted |
| What are sensible ranges for the settings? | A burst and a rate from 1 to 1,000,000. A setting outside that is a configuration mistake, found at start-up. | Assumption |
Three questions did most of the work. “Steady rate or bursts?” picks the family of algorithm. “How many clients?” forces a bound on memory and a rule for what happens at the bound. “How many threads?” makes the limiter’s thread safety part of its contract, not an afterthought. For more on asking questions that change the design, see Clarification questions.
Stage 3: requirement choices
Section titled “Stage 3: requirement choices”Think first. From the answers, write two functional requirements and two non-functional ones. Then write one acceptance criterion precise enough that a test could check it, including the numbers.
Show stage 3: requirements and acceptance criteria
Functional requirements
- FR-1 Burst, then a steady rate. Each client key may make up to
capacityrequests at once, thentokens_per_secondmore each second. One setting, aLimit, applies to every key. - FR-2 An answer, with a reason and a hint. Every request gets a decision: allowed (with the tokens left), refused because this client has no tokens, or refused because the limiter is tracking as many clients as it may. A refusal says how long to wait, rounded up to a whole millisecond.
- FR-3 Bounded clients. At most
max_clientsclients are tracked at once. Reaching the bound must never give any client more than its burst. - FR-4 Settings checked at start-up. A
Limitoutside 1 to 1,000,000, or a bound of 0, is refused when the limiter is built.
Non-functional requirements
- NFR-1 Exact. Fractions of a token are never lost or invented, however often the limiter is asked. No drift over time.
- NFR-2 Thread safe, exactly. Any number of threads may call it at once. With time standing still, a client with 10 tokens gets exactly 10 allowed requests, whatever the interleaving.
- NFR-3 Cheap per request. No background thread and no timer. A request costs a lookup and a little arithmetic; only reaching the bound costs a pass over all tracked clients.
- NFR-4 Testable without waiting. Tests control time through an injected clock, so none of them sleeps and each gives the same result on every run.
Acceptance criteria. Each is one test in step 1, named after it (for
example prc_rate_s1_ac_2_1_a_client_may_burst_to_capacity_then_is_told_when_to_retry).
| Id | Criterion |
|---|---|
| AC-1.1 | A new bucket is full, and earns whole tokens at its rate. |
| AC-1.2 | Part-earned tokens are carried, so small steps do not drift: ten steps of 100 ms at 1 token a second make exactly one token. |
| AC-1.3 | A full bucket stops at capacity and drops its part token; a long idle at the largest settings does not overflow. |
| AC-1.4 | The time until a token is rounded up and exact to the millisecond: at 3 tokens a second, 334 ms, and at 333 ms the token is not there yet. |
| AC-1.5 | A time that goes back earns nothing and changes nothing. |
| AC-1.6 | Limits out of range, and a bound of 0, are refused when the limiter is built. |
| AC-2.1 | With a burst of 3 and 2 tokens a second, a client may make 3 requests at once; the 4th is refused with a hint of 500 ms; 499 ms later is too early, 500 ms is enough. |
| AC-2.2 | Each key has its own bucket, and keys are compared exactly (case matters). |
| AC-2.3 | Refill is lazy, and looking at a client’s tokens changes nothing. |
| AC-2.4 | A refused request spends nothing and keeps the part token. |
| AC-2.5 | A limiter on the real steady clock allows a new client its first burst. |
| AC-3.1 | When the table is full, buckets that are full again are dropped, and a dropped client comes back to the same full bucket. |
| AC-3.2 | If no bucket is full, a new client is refused with too_many_clients and the time until the soonest bucket is full, rather than a burst leaked. |
| AC-3.3 | Every full bucket is dropped in one sweep. |
| AC-4.1 | 32 threads racing for one client’s 10 tokens get exactly 10. |
| AC-4.2 | 32 new clients arriving at once with room for 8: exactly 8 are admitted and 24 refused. |
| AC-4.3 | Requests and reads together, with time standing still, spend exactly the tokens there are, and no read sees an impossible value. |
The criteria name numbers on purpose. “Allows bursts” cannot fail a test; “3 at once, then the 4th is refused for 500 ms” can.
Stage 4: consequences of those choices
Section titled “Stage 4: consequences of those choices”Think first. Pick two of the choices above. For each, what does it force the code to do, and what does it rule out?
Show stage 4: what each choice forces and rules out
| Choice | Forces | Rules out, or makes harder |
|---|---|---|
| Burst, then a steady rate (FR-1) | Two numbers per limit, not one; an algorithm that can say both. | “100 per minute” counters, which cannot say how fast the 100 may come. |
| Exact, no drift (NFR-1) | Whole-number arithmetic with the fraction kept, not thrown away. | double tokens, and rounding at every refill. |
| A refusal is an answer (FR-2) | A small value type with a verdict, the tokens left, and the wait. | Exceptions for refusals; a bool that cannot say why or for how long. |
| Retry hint never too early | Rounding the wait up, never down. | A hint of “about half a second” that sends a retry back one millisecond too soon. |
| Bounded clients, no extra burst (FR-3) | A rule for which client can be forgotten without changing any later answer. | “Evict the least recently used”, which can forget a client that has just used its burst. |
| Many threads, exact counts (NFR-2) | “Refill, check, spend” as one step that no other thread can see half done. | Checking under one lock and spending under another; per-field atomics that are each safe but not safe together. |
| No background thread (NFR-3) | Lazy refill: a bucket is brought up to date only when someone asks. | A timer thread that adds tokens to every bucket, which costs time even for idle clients and needs a shutdown. |
| Testable without waiting (NFR-4) | The clock is passed in; the limiter never calls steady_clock::now() itself. |
Tests that sleep, and tests whose result depends on how fast the machine is. |
| One process, nothing saved | Plain in-memory data and one lock. | A limit shared by several copies of the service, which would need a shared store and a redesign, not a tweak. |
Two rows are easy to skip and expensive to miss. “No extra burst at the bound” decides the eviction rule, and the obvious rule breaks it. “Exact counts with many threads” decides where the lock goes, and a lock in the wrong place passes every single-threaded test.
Stage 5: candidate designs
Section titled “Stage 5: candidate designs”Think first. You may know the names fixed window, sliding log, and token bucket. For each, ask: with a limit of “3 at once, then 2 a second”, what is the most a client can do in a short moment, and how much does the limiter remember per client?
Show stage 5: three candidates and their trade-offs
Candidate A: fixed window. Count requests per client in windows of one second that start on whole seconds; refuse once the count reaches the limit; reset the count when a new window starts. Memory is one counter and one window start per client.
Its weakness is the window edge. With a limit of 3 a second, a client can make 3 requests at 999 ms and 3 more at 1000 ms, because the second three are in a new window: 6 requests in 2 ms, twice the stated limit. It also cannot say “a burst of 3, then 2 a second”: it has only one number.
Candidate B: sliding log. Keep, per client, the time of every allowed request in the last second; allow a request if fewer than the limit are in the log. This is exact: in any one-second span there are never more than the limit. The cost is memory: a client at its limit holds one timestamp per allowed request, so a limit of 1,000 a second means up to 1,000 timestamps per busy client, and each request does work to drop old entries. It also has a single number, not a burst and a rate.
Candidate C: token bucket. Each client has a bucket that holds up to
capacity tokens and fills at tokens_per_second. A request takes one
token; with none left, it is refused. A full bucket is a burst waiting
to be used; an empty one admits requests only as fast as tokens arrive.
Memory is a few numbers per client, whatever the limit. Over any span of
time, a client gets at most capacity plus the rate times the span.
| Property | Fixed window | Sliding log | Token bucket |
|---|---|---|---|
| Burst at a window edge | Up to twice the limit | None | None beyond capacity; the burst is a setting |
| Burst and steady rate separately | No | No | Yes |
| Memory per client | Two numbers | One timestamp per request in the window | Three numbers |
| Precision | Coarse, by window | Exact for the window | Exact, if the arithmetic keeps fractions |
| Retry hint | Time until the next window | Time until the oldest entry expires | Time until the next token |
Why token bucket fits here. The owner asked for a burst, then a steady rate (FR-1), which is exactly the token bucket’s two numbers. Memory per client is small and fixed, which matters when keys can be invented without end. The retry hint is a simple calculation.
When another would be better. If the rule is a contract such as “no more than 1,000 calls in any rolling hour”, and the limit is small enough to keep a log, the sliding log enforces it exactly and the token bucket does not say it directly. If the counts must be shared by several servers through a store with only “increment and expire”, a fixed window is often the one that store can do cheaply, and its edge burst is accepted. If refused requests should wait rather than be refused, that is a queue that drains at a fixed rate (often called a leaky bucket), and it brings its own questions about how long the queue may grow; see Backpressure.
The name settles nothing on its own. “Use a token bucket” still leaves open how fractions are counted, how the wait is rounded, what happens at the memory bound, and where the lock goes. Those are the next stage.
Stage 6: the chosen design
Section titled “Stage 6: the chosen design”Think first. Before opening: what does one client’s bucket need to remember? Which object owns the buckets, and which object does it only borrow? And at the memory bound, which buckets could be forgotten without changing any later answer?
Show stage 6: the entities, the classes, a bucket’s states, and the code
The entities. Before classes, the things and how many of each.
Text description of the diagram
- The service’s request threads ask the
RateLimiter, giving a client key. - The limiter keeps one
Bucketper tracked key, at mostmax_clientsof them. A bucket holds three numbers: whole tokens, the part-earned next token (credit), and the time it was last brought up to date (last_ms). - One
Limit(a capacity and a rate) applies to every key. - The limiter reads the time from a
Clockit does not own. - Each request is answered with a
Decision: a verdict, the tokens left, and how long to wait.
Diagram source (Mermaid)
flowchart LR
Caller["Request thread (the service)"] -->|"asks with a client key"| Limiter[RateLimiter]
Limiter -->|"one per tracked key, at most max_clients"| Bucket["Bucket: tokens, credit, last_ms"]
Limiter -->|"one, shared by every key"| Limit["Limit: capacity, tokens_per_second"]
Limiter -->|"reads the time from, does not own"| Clock
Limiter -->|"answers with"| Decision["Decision: verdict, remaining, retry_after"]The classes. Plain value types for the numbers, free functions for the arithmetic, one class that owns the table and the lock, and one small interface, for the clock, because tests need a second kind of it.
Text description of the diagram
Limitis two whole numbers:capacityandtokens_per_second.Bucketis three whole numbers:tokens,credit, andlast_ms.- Four free functions do the arithmetic on these values:
validatechecks aLimit;full_bucketmakes a new bucket;refilledreturns a bucket brought up to date at a given time;time_untilsays how long until a bucket holds a given number of tokens. Verdictis an enumeration:allowed,no_tokens,too_many_clients.Decisionholds aVerdict, the tokens left, andretry_after, and hasallowed().RateLimiterowns itsLimit, its bound, its mutex, and a map from key toBucket. It keeps a pointer to aClockit does not own. Its public members aretry_acquire,tokens, andtracked_clients; two private helpers deal with a full table. It calls the free functions and returnsDecisionvalues.Clockis an interface with one function,now.SteadyClockandManualClockimplement it;ManualClockalso hasadvance.
Diagram source (Mermaid)
classDiagram
class Limit {
+int64 capacity
+int64 tokens_per_second
}
class Bucket {
+int64 tokens
+int64 credit
+int64 last_ms
}
class BucketFunctions {
<<free functions>>
+validate(Limit) void
+full_bucket(Limit, int64 now_ms) Bucket
+refilled(Bucket, Limit, int64 now_ms) Bucket
+time_until(Bucket, Limit, int64 wanted) milliseconds
}
class Verdict {
<<enumeration>>
allowed
no_tokens
too_many_clients
}
class Decision {
+Verdict verdict
+int64 remaining
+milliseconds retry_after
+allowed() bool
}
class RateLimiter {
-Limit limit_
-size_t max_clients_
-const Clock pointer clock_
-mutex mutex_
-unordered_map~string, Bucket~ buckets_
+try_acquire(string key) Decision
+tokens(string key) optional~int64~
+tracked_clients() size_t
-drop_full_buckets(int64 now) void
-time_until_a_bucket_is_full(int64 now) milliseconds
}
class Clock {
<<interface>>
+now() time_point
}
class SteadyClock {
+now() time_point
}
class ManualClock {
-time_point now_
+now() time_point
+advance(milliseconds step) void
}
Clock <|-- SteadyClock
Clock <|-- ManualClock
RateLimiter *-- Limit : limit_
RateLimiter *-- Bucket : buckets_
RateLimiter o-- Clock : clock_, not owned
RateLimiter ..> BucketFunctions : calls
RateLimiter ..> Decision : returns
Decision --> VerdictKeeping the arithmetic in free functions on plain values is a deliberate
split. refilled and time_until can be tested with no limiter, no
clock, and no threads (the AC-1 tests do exactly that), and the class
that holds the lock has little to do besides lookup and locking.
One bucket’s life. A bucket’s state is not stored as a name; it follows from its numbers when someone looks. That is still worth drawing, because the eviction rule depends on it.
Text description of the diagram
A client starts not tracked. Its first request, if there is room in the
table (after dropping any buckets that are full), gets a full bucket, and
the same request then spends one token from it. If the table is full and
no bucket is full, the new client stays not tracked and is refused with
too_many_clients.
From full, a request spends one token, leaving the bucket partly used
(or empty, if the capacity is 1). From partly used, a request spends one
token; the last token leaves it empty. From empty, a request is refused
with no_tokens and a wait, and nothing changes.
As time passes, an empty bucket earns tokens and becomes partly used, and a partly used or empty bucket that earns back its capacity becomes full, dropping any part token. Only a full bucket can be dropped, and only when the table is full and another new client arrives. A dropped client is not tracked again, and its next request gets a full bucket, which is what it had.
Diagram source (Mermaid)
stateDiagram-v2
state "Not tracked" as NotTracked
state "Full" as Full
state "Partly used" as Partly
state "Empty" as Empty
[*] --> NotTracked
NotTracked --> NotTracked : first request [table full, no bucket full] / too_many_clients
NotTracked --> Full : first request [room, after dropping full buckets] / full bucket made
Full --> Partly : request / one token spent
Partly --> Partly : request [2 or more tokens] / one token spent
Partly --> Empty : request [1 token] / one token spent
Empty --> Empty : request / no_tokens with retry_after
Empty --> Partly : time passes / tokens earned
Partly --> Full : time passes [capacity reached] / part token dropped
Empty --> Full : time passes [capacity reached] / part token dropped
Full --> NotTracked : another new client [table full] / bucket droppedThe numbers: a limit and a bucket
Section titled “The numbers: a limit and a bucket”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// How much one client may do: a burst of up to `capacity` requests at the// same moment, and after that `tokens_per_second` more each second.// Both are whole numbers from 1 to max_limit_value. The upper bound keeps// every product in refilled() far inside std::int64_t (see there).struct Limit { std::int64_t capacity = 1; std::int64_t tokens_per_second = 1;
friend bool operator==(const Limit&, const Limit&) = default;};
inline constexpr std::int64_t max_limit_value = 1'000'000;
// Throws std::invalid_argument unless capacity and tokens_per_second are// both from 1 to max_limit_value. The limiter calls it once, when it is// built, so a set-up mistake is found at start-up and not at the first// request.void validate(const Limit& limit);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The part of a token that has been earned but not yet completed is kept// in "units": one unit is what a rate of 1 token per second earns in one// millisecond, so 1000 units make one token. Every rate is a whole number// of tokens per second, so one millisecond at any rate earns a whole// number of units, and no rounding ever happens during a refill.inline constexpr std::int64_t units_per_token = 1000;
// One client's token bucket, as plain numbers. A value type: the limiter// keeps one per client key, and the functions below take and return// buckets by value, so the arithmetic can be tested on its own.struct Bucket { std::int64_t tokens = 0; // whole tokens ready to spend: 0 to capacity std::int64_t credit = 0; // the next token, part earned: 0 to 999 units std::int64_t last_ms = 0; // when the bucket was last brought up to date
friend bool operator==(const Bucket&, const Bucket&) = default;};
// A bucket for a client seen for the first time: full, nothing part// earned, up to date at now_ms. A new client may burst at once.[[nodiscard]] Bucket full_bucket(const Limit& limit, std::int64_t now_ms);
// The same bucket brought up to date at now_ms: it earns// tokens_per_second units for every millisecond since last_ms, every 1000// units become one whole token, and the rest stays in credit for next// time. A bucket never holds more than capacity tokens, and a full bucket// keeps no credit (it is the same as a fresh one). A now_ms that is not// later than last_ms earns nothing and leaves the bucket unchanged.[[nodiscard]] Bucket refilled(Bucket bucket, const Limit& limit, std::int64_t now_ms);
// How long until `bucket` (already up to date) holds at least `wanted`// tokens, if nobody spends any: zero if it already does. Rounded up to a// whole millisecond, so after exactly this long the tokens are there,// and one millisecond earlier they are not. `wanted` must be from 1 to// capacity.[[nodiscard]] std::chrono::milliseconds time_until(const Bucket& bucket, const Limit& limit, std::int64_t wanted);Integer credit for fractional tokens. At 2 tokens a second, 250 ms
earns half a token. The bucket must remember that half, or a client that
asks every 250 ms would never earn anything. Instead of a double, the
bucket counts part tokens in units of one thousandth of a token. One
millisecond at a rate of tokens_per_second earns exactly
tokens_per_second units, a whole number, because every rate is a whole
number of tokens per second. So a refill never needs to round.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
Bucket refilled(Bucket bucket, const Limit& limit, std::int64_t now_ms) { // No time has passed, or the time is earlier than last time (a steady // clock never does this; it is handled so that a wrong clock cannot // hand out tokens). last_ms is not moved back either. if (now_ms <= bucket.last_ms) { return bucket; } std::int64_t elapsed_ms = now_ms - bucket.last_ms; // The bucket now accounts for every millisecond up to now_ms. Moving // last_ms to now_ms, and not "to the moment the last whole token was // earned", is safe because the part-earned token is kept in credit: // nothing is lost and nothing is counted twice, so there is no drift. bucket.last_ms = now_ms;
// An empty bucket at the slowest rate (1 per second) is full after // capacity * 1000 ms. Any longer gap cannot add more, so it is cut to // that length. This keeps elapsed_ms * tokens_per_second at most // 10^9 * 10^6 = 10^15 after a client is idle for a year, well inside // std::int64_t (about 9.2 * 10^18). elapsed_ms = std::min(elapsed_ms, limit.capacity * units_per_token);
bucket.credit += elapsed_ms * limit.tokens_per_second; // earned units bucket.tokens += bucket.credit / units_per_token; // whole tokens out bucket.credit %= units_per_token; // the rest stays
// The rule for a full bucket: it stops earning, and it throws away any // part-earned token, so a full bucket is exactly a fresh one. if (bucket.tokens >= limit.capacity) { bucket.tokens = limit.capacity; bucket.credit = 0; } return bucket;}How this code works: refilled, and why it does not drift
Earn, convert, keep the rest. The function works out the
milliseconds since last_ms, adds elapsed_ms * tokens_per_second
units to credit, turns every 1000 units into a whole token, and keeps
the remainder in credit. Then it moves last_ms to now.
Why that does not drift. Moving last_ms all the way to now looks as
if it might lose the part of a token earned since the last whole one. It
does not, because that part is in credit. The division happens only on
the running total of units, never on each step separately. So however
the time is cut up, the client earns exactly elapsed time multiplied by
rate. Test AC-1.2 checks it: ten refills 100 ms apart at 1 token a second
give exactly one token; at 3 a second, 333 refills of 1 ms each give 999
units and no token, and the 334th millisecond completes it with 2 units
left over, which is the same bucket that one refill of 334 ms gives.
Full means fresh. When the bucket reaches capacity, it stops there
and throws away credit. That is a rule, not an accident: a full bucket
is then exactly what a new client gets from full_bucket, which is what
makes dropping full buckets harmless (below).
Time going back. A steady clock never goes back, but the function
does not trust that: a time not later than last_ms returns the bucket
unchanged, so a wrong clock cannot hand out tokens (AC-1.5).
Overflow. A client idle for a year would multiply a very large
number of milliseconds by the rate. No gap can add more than a full
bucket, so the gap is first cut to capacity * 1000 ms, the time an
empty bucket takes to fill at the slowest rate. With both settings at
most 1,000,000, the product stays at most 10^15, far inside a 64-bit
integer. AC-1.3 checks a gap of 2^53 ms at the largest settings.
Retry after, rounded up.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
std::chrono::milliseconds time_until(const Bucket& bucket, const Limit& limit, std::int64_t wanted) { if (bucket.tokens >= wanted) { return std::chrono::milliseconds{0}; } // Units still to earn: the missing whole tokens, less what is already // part earned. Always at least 1, because credit is below 1000. const std::int64_t units_needed = (wanted - bucket.tokens) * units_per_token - bucket.credit; // Each millisecond earns tokens_per_second units. (a + b - 1) / b is // a / b rounded up, for positive whole numbers: a wait rounded down // would come back a millisecond too early and be refused again. const std::int64_t rate = limit.tokens_per_second; return std::chrono::milliseconds{(units_needed + rate - 1) / rate};}The wait is the units still needed divided by the units earned per millisecond, rounded up. At 3 tokens a second, one token is 1000 units at 3 units per millisecond, 333.3 ms. Rounded down, the hint says 333 ms, but after 333 ms the bucket has 999 units and the retry is refused again. Rounded up, the hint says 334 ms, and a retry then succeeds if nobody else spent the token. AC-1.4 checks both sides of that edge. A caller that retries on the hint, as the advice in Idempotency and retries suggests, should not be sent back one millisecond too early.
The answer, and the limiter
Section titled “The answer, and the limiter”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What try_acquire decided.// allowed the request may go ahead; one token was spent// no_tokens this client has used its burst; try again later// too_many_clients this is a new client and the limiter already tracks// as many clients as it may, none of them idleenum class Verdict { allowed, no_tokens, too_many_clients };
[[nodiscard]] std::string_view to_string(Verdict verdict);
// The answer to one request. A plain value: the caller can copy it, log// it, or turn it into an HTTP 429 with a Retry-After header.struct Decision { Verdict verdict = Verdict::allowed; // Tokens this client has left after this call. 0 when refused. std::int64_t remaining = 0; // 0 when allowed. When refused: how long until a retry can succeed, // if nobody else uses the limiter meanwhile. For no_tokens, the time // until this client's next token; for too_many_clients, the time // until the soonest of the tracked clients' buckets is full again and // so can be dropped. It is a hint: other requests in between can use the token // or the slot first. std::chrono::milliseconds retry_after{0};
[[nodiscard]] bool allowed() const { return verdict == Verdict::allowed; }};A refusal is an ordinary outcome, so it is a value, not an exception.
Exceptions stay for set-up mistakes: a Limit out of range or a bound of
0 throws std::invalid_argument from the constructor (AC-1.6), so it is
found at start-up and not at the first request.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A token-bucket rate limiter for one process: every client key gets its// own bucket with the same Limit.//// Buckets are brought up to date lazily: only when their client makes a// request (or someone asks how many tokens it has). There is no timer and// no background thread, and a client that is not calling costs nothing.//// At most max_clients buckets are kept. When a new client arrives and the// table is full, every bucket that is full by now is dropped first: a full// bucket is exactly what a new client gets, so dropping it changes no// later answer. If every tracked client still has tokens to earn back, the// new client is refused with too_many_clients. The limiter refuses rather// than drop a bucket that is not full, because the dropped client would// come back to a full bucket and get a second burst: the limit would// leak for exactly the clients that are using it hardest.//// Thread safety: safe. Any member may be called from any number of// threads at once. One mutex, mutex_, protects buckets_: every bucket's// numbers and which keys are in the table. Each public member holds it for// the whole call, so "refill, check, spend" is one step that no other// thread can see half done. limit_, max_clients_, and clock_ are set in// the constructor and never change, so they are read without the lock.// The clock is read with the lock held, so each bucket sees time only go// forward; the clock itself must be safe to read from several threads.//// Ownership: the limiter owns its buckets. It does not own the clock; the// caller must keep the clock alive for as long as the limiter.class RateLimiter {public: // Throws std::invalid_argument for a Limit that validate() refuses or // for max_clients of 0. RateLimiter(Limit limit, std::size_t max_clients, const Clock& clock);
// A mutex can be neither copied nor moved, and two limiters sharing // buckets would make no sense, so the limiter cannot be copied either. RateLimiter(const RateLimiter&) = delete; RateLimiter& operator=(const RateLimiter&) = delete;
// Asks for one token for `key`. Spends one and says allowed, or says // why not and how long to wait. A refused request spends nothing and // does not lose the part-earned token. [[nodiscard]] Decision try_acquire(const std::string& key);
// How many tokens `key` would have now, without spending one or // changing anything; nullopt if the key is not tracked (a new client // would get a full bucket). [[nodiscard]] std::optional<std::int64_t> tokens(const std::string& key) const;
[[nodiscard]] std::size_t tracked_clients() const;
private: // Both need mutex_ held by the caller. void drop_full_buckets(std::int64_t now); [[nodiscard]] std::chrono::milliseconds time_until_a_bucket_is_full(std::int64_t now) const;
const Limit limit_; const std::size_t max_clients_; const Clock* clock_; // not owned; never null
// `mutable` so that the const members tokens() and tracked_clients() // can lock it: locking does not change what the limiter holds. mutable std::mutex mutex_; std::unordered_map<std::string, Bucket> buckets_; // guarded by mutex_};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
Decision RateLimiter::try_acquire(const std::string& key) { // One lock for the whole call. Without it, two threads could both see // one token left and both spend it. const std::scoped_lock lock(mutex_); const std::int64_t now = now_ms(*clock_);
auto found = buckets_.find(key); if (found == buckets_.end()) { // A new client. Make room only when the table is full, so the // sweep over every bucket is paid only then. if (buckets_.size() >= max_clients_) { drop_full_buckets(now); } if (buckets_.size() >= max_clients_) { return {Verdict::too_many_clients, 0, time_until_a_bucket_is_full(now)}; } // emplace returns {iterator, inserted}; .first is the iterator to // the new entry. The new client starts with a full bucket. found = buckets_.emplace(key, full_bucket(limit_, now)).first; }
// A reference into the map, used only while the lock is held. Nothing // below inserts or erases, so it stays valid. Bucket& bucket = found->second; bucket = refilled(bucket, limit_, now); // the lazy refill if (bucket.tokens == 0) { // Refused: nothing is spent, and credit is kept, so the wait // below is exact. return {Verdict::no_tokens, 0, time_until(bucket, limit_, 1)}; } --bucket.tokens; return {Verdict::allowed, bucket.tokens, std::chrono::milliseconds{0}};}How this code works: try_acquire on the first requests of the demo
The demo uses a burst of 3, 2 tokens a second, and room for 2 clients.
alice, four times at 0 ms. The first call finds no bucket for
“alice”, and the table has room, so it makes a full bucket of 3 tokens.
refilled at the same time earns nothing. One token is spent: allowed,
2 left. The next two calls leave 1 and then 0. The fourth finds 0 tokens
and returns no_tokens with time_until(bucket, limit, 1): 1000 units
at 2 units per millisecond, 500 ms.
alice at 499 ms, then 500 ms. At 499 ms she has earned 998 units, not a token: refused, with a wait of 1 ms (2 units, at 2 per millisecond). At 500 ms the bucket has 1000 units, which become one token, and the call is allowed with 0 left.
bob, then carol, at 500 ms. bob is new and there is room: allowed,
2 left. carol is new and the table is full (alice and bob). The limiter
sweeps for full buckets; neither is full, so it refuses carol with
too_many_clients and the time until the soonest bucket is full: bob
needs 1 token, 500 ms. alice needs 3, 1500 ms.
carol at 1000 ms. bob’s bucket is full again, so the sweep drops it; alice has 1 token and is kept. carol gets a full bucket and is allowed with 2 left.
Lazy refill. There is no timer. A bucket is brought up to date in
the one place it is needed, at the start of a call for that key. An
idle client costs nothing but its three numbers. tokens() brings a
copy up to date and reports it, so looking never changes a later
answer (AC-2.3).
The key bound, and why only full buckets are dropped.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
void RateLimiter::drop_full_buckets(std::int64_t now) { // std::erase_if (C++20) removes every entry for which the lambda says // true. The lambda takes one map entry, a key and bucket pair, and // captures `this` to reach limit_. It asks whether the bucket would be // full now; it does not store the refill, because the bucket is either // dropped or left exactly as it was. std::erase_if(buckets_, [this, now](const auto& entry) { return refilled(entry.second, limit_, now).tokens == limit_.capacity; });}The obvious rule at a memory bound is “forget the least recently used”. Here it would break the limit. Suppose alice has just used her burst of 3, and two new clients arrive. If alice is forgotten, her next request gets a fresh, full bucket: 3 more at once, 6 in the same moment, twice her burst. The buckets that are not full belong to the clients that have been using the limiter hardest, and least-recently-used eviction can forget exactly those.
A full bucket, on the other hand, can be forgotten without anyone being
able to tell: the client would come back to a full bucket, which is
what it had (AC-3.1). That is why refilled drops the part token of a
full bucket; with credit kept, a “full” bucket would not be the same as
a fresh one. If no bucket is full, the new client is refused, with the
time until the soonest one is (AC-3.2). The table can never hold more than
max_clients buckets, and nobody gets a second burst.
The cost: when the table is full, every new client pays a pass over all tracked buckets, under the lock. Below the bound, a new client costs one insert.
What the one mutex protects. mutex_ guards buckets_: which keys
are in the table and every bucket’s numbers. Each public member holds it
for the whole call, so “refill, check, spend” is one step. Without that,
two threads could both see one token left and both spend it; the second
common mistake below shows that happening. limit_, max_clients_, and
clock_ are set in the constructor and never change, so they need no
lock. Bucket& bucket is a reference into the map; it is used only while
the lock is held, and nothing between finding it and using it inserts or
erases, so it stays valid.
Why the clock is read under the lock. If each thread read the time
first and then waited for the lock, a thread that read 1000 ms could get
the lock after one that read 1001 ms and has already moved last_ms to
1001. Reading the time inside the lock keeps the order of the readings
the same as the order of the updates, so each bucket sees time only go
forward. refilled would ignore an earlier time anyway, but the answer
given to that thread, including its wait, would then be worked out for
a moment that had already passed. Reading a steady clock is usually
cheap, so holding the lock for it costs little; the clock itself must be safe to read from
several threads, which both clocks are.
The injected clock
Section titled “The injected clock”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Where the limiter gets the time. Production code passes SteadyClock; the// tests and the demo pass ManualClock and move time forward by hand, so a// test can say "499 ms later" and check that a request is still refused,// without sleeping and without a result that depends on how fast the// machine is.// The limiter is handed a `const Clock&`, keeps a pointer to it, and never// knows which kind of clock it was given.class Clock {public: // "A moment in time", the steady clock's own type. Both clocks below // return it, so either can stand in for the other. using time_point = std::chrono::steady_clock::time_point;
// Virtual, so that deleting a clock through a Clock pointer runs the // right destructor. virtual ~Clock() = default; // `= 0`: every kind of clock must supply its own answer. `const`: // reading the time does not change the clock. [[nodiscard]] virtual time_point now() const = 0;
protected: // Only a derived clock can create or copy the Clock part, so outside // code cannot slice a clock by copying it through a `Clock&`. Clock() = default; Clock(const Clock&) = default; Clock& operator=(const Clock&) = default;};
// A steady clock never goes back, even when someone changes the computer's// date, so a gap measured with it is never negative. Safe to call from// several threads at once.class SteadyClock final : public Clock {public: [[nodiscard]] time_point now() const override { return std::chrono::steady_clock::now(); }};
// A clock for tests and the demo: time stands still until someone calls// advance. Reading it from several threads at once is safe, because// reading changes nothing; calling advance while another thread reads it// is a data race, so the threaded tests set the time first and only then// start their threads.class ManualClock final : public Clock {public: [[nodiscard]] time_point now() const override { return now_; }
// Moves time forward by `step`, for example clock.advance(500ms). // Throws std::invalid_argument for a negative step, and then leaves the // time unchanged: a steady clock never goes back. void advance(std::chrono::milliseconds step) { if (step.count() < 0) { throw std::invalid_argument("a steady clock never goes back"); } now_ += step; }
private: // `{}` starts at the clock's zero point. The real date does not matter: // the limiter only subtracts one moment from another. time_point now_{};};
// The clock's time as a whole number of milliseconds since its zero point.// The limiter does all of its arithmetic on these plain integers.// std::chrono::floor rounds down to whole milliseconds; any part of a// millisecond is not lost, it simply counts once the next millisecond// starts, because the limiter remembers the time it last looked, not how// much time it added.[[nodiscard]] inline std::int64_t now_ms(const Clock& clock) { return std::chrono::floor<std::chrono::milliseconds>(clock.now().time_since_epoch()).count();}The limiter is given a const Clock& and keeps a pointer to it. It does
not own the clock: the caller must keep the clock alive for as long as
the limiter. Production passes a SteadyClock. Tests and the demo pass
a ManualClock, which stands still until advance is called, so a test
can say “499 ms later” and check that a request is still refused,
without sleeping. This is
dependency injection used for the
one thing that needs it, and ManualClock is a fake in the sense of
Test doubles and seams. The cost is one
virtual call each time the limiter reads the time; nothing else in the
design is virtual.
ManualClock::advance is not safe to call while another thread reads
the clock. The threaded tests therefore set the time before they start
their threads and leave it alone.
Stage 7: tests
Section titled “Stage 7: tests”Think first. Which criteria from stage 3 can be tested with no limiter at all? Which need real threads? And if a threaded test passes under ThreadSanitizer, what exactly have you learned?
Show stage 7: how the criteria map to tests, and a real run
Each acceptance criterion from stage 3 is one test, named after it, 17 tests in all.
| Criteria | What the tests drive | Threads |
|---|---|---|
| AC-1.1 to AC-1.5 | refilled and time_until on plain Bucket values |
No |
| AC-1.6 | The constructor, and ManualClock::advance with -1 ms |
No |
| AC-2.1 to AC-2.4 | RateLimiter with a ManualClock |
No |
| AC-2.5 | RateLimiter with the real SteadyClock |
No |
| AC-3.1 to AC-3.3 | The table bound, with a ManualClock |
No |
| AC-4.1 to AC-4.3 | RateLimiter from 32 or 20 threads at once |
Yes |
Deterministic tests with the manual clock. No test except AC-2.5
reads the real time: the AC-1 tests pass times as plain numbers, and the
rest use a ManualClock, so time moves only when the test says so. The
fraction tests are a good example: they check exact numbers, which a
test on the real clock could not.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The rule for fractions: earned units are carried, never rounded. Ten// refills 100 ms apart at 1 token a second make exactly one token. Rounding// each refill down would make none (0.1 rounds to 0 ten times), and rounding// up would make ten.LLD_TEST(prc_rate_s1_ac_1_2_part_earned_tokens_are_carried_so_small_steps_do_not_drift) { Bucket bucket{0, 0, 0}; for (int step = 1; step <= 9; ++step) { bucket = refilled(bucket, one_per_second, step * 100); LLD_CHECK_EQ(bucket.tokens, 0); } LLD_CHECK_EQ(bucket.credit, 900); bucket = refilled(bucket, one_per_second, 1000); LLD_CHECK_EQ(bucket, (Bucket{1, 0, 1000}));
// Uneven steps, 3 tokens a second: 1 ms at a time for 333 ms gives // 999 units, still no token; the 334th millisecond completes it. const Limit three{.capacity = 10, .tokens_per_second = 3}; Bucket fine{0, 0, 0}; for (int ms = 1; ms <= 333; ++ms) fine = refilled(fine, three, ms); LLD_CHECK_EQ(fine, (Bucket{0, 999, 333})); fine = refilled(fine, three, 334); LLD_CHECK_EQ(fine, (Bucket{1, 2, 334})); // The same 334 ms in one step gives the same bucket: the answer does // not depend on how often anyone looked. LLD_CHECK_EQ(refilled(Bucket{0, 0, 0}, three, 334), fine);}AC-2.5 is the only test on the real clock, and it asks only what is true whatever the time is: a new client gets its full burst. It does not check any wait, because that would depend on how fast the machine is.
Threaded tests with exact counts.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Thirty-two threads race for one client's 10 tokens with time standing// still. Exactly 10 may win, every round, and every loser must be told// no_tokens.LLD_TEST(prc_rate_s1_ac_4_1_threads_racing_for_one_bucket_get_exactly_its_capacity) { constexpr int threads = 32; for (int round = 0; round < 50; ++round) { ManualClock clock; RateLimiter limiter({.capacity = 10, .tokens_per_second = 1}, 4, clock); // Each thread writes only its own element, so the writes do not // race; the joins make them visible here. std::vector<int> won(threads, 0); std::vector<int> wrong(threads, 0); run_together(threads, [&](int t) { const Decision decision = limiter.try_acquire("shared"); const auto slot = static_cast<std::size_t>(t); won[slot] = decision.allowed() ? 1 : 0; wrong[slot] = !decision.allowed() && decision.verdict != Verdict::no_tokens ? 1 : 0; }); LLD_CHECK_EQ(sum(won), 10); LLD_CHECK_EQ(sum(wrong), 0); LLD_CHECK_EQ(tokens_of(limiter, "shared"), 0); }}The threads wait at a std::latch so they start together, which makes
an overlap likely. Time stands still, so the right answer is exact:
10 winners, not “about 10”. Each thread writes only its own element of
won, so the test itself has no data race. Each test repeats its race
50 times (AC-4.3, 20 times). AC-4.2 races 32 new clients for 8 slots;
AC-4.3 mixes 16 requesting threads with 4 threads that keep reading.
What ThreadSanitizer proves, and what it does not. The tests carry
the concurrency label, and the tsan build preset runs both test
programs under ThreadSanitizer; for this example they were run 10 times
over with ctest --repeat until-fail:10, and all passed.
That shows that in the interleavings that happened, no two threads touched the same memory without ordering between them. It does not prove that no other interleaving has a data race. And it cannot see a race that is not a data race: if “check” and “spend” are each done under the lock but separately, every access is ordered and ThreadSanitizer has nothing to report, yet two threads can both spend the last token. That kind of mistake is caught by the exact counts, and only when the threads happen to interleave at the wrong place, which is why the races are repeated. The tests also never move time while threads run, so they do not test refill racing with requests; that relies on the same lock. For more on what concurrency tests can and cannot show, see Testing concurrent code.
The demo. step-1/main.cpp plays the requests traced in stage 6,
then shows a half token being kept across a refusal. This is its real
output, which the build checks against expected_output.txt:
burst 3, then 2 tokens a second; at most 2 clients trackedt=0ms alice allowed, 2 leftt=0ms alice allowed, 1 leftt=0ms alice allowed, 0 leftt=0ms alice no tokens, retry after 500mst=499ms alice no tokens, retry after 1mst=500ms alice allowed, 0 leftt=500ms bob allowed, 2 leftt=500ms carol too many clients, retry after 500mst=1000ms carol allowed, 2 lefttracked clients: 2t=1000ms alice allowed, 0 leftt=1250ms alice no tokens, retry after 250mst=1500ms alice allowed, 0 leftalice has 0 tokensRead the last three requests against the rules. At 1000 ms alice has earned 1 token since 500 ms and spends it. At 1250 ms she has earned half a token: refused, and the half is kept, so the wait is 250 ms, not 500 ms. At 1500 ms the two halves make a whole token.
What was run. Both steps’ tests and demos pass on the gcc-debug,
clang-debug, and asan-ubsan presets, and both test programs pass on the
tsan preset. The example is also built with -Wconversion and
-Wshadow. A mutation check in a scratch copy of step 2 changed the
code in 18 small ways (refill, rounding, eviction, tier change, and
locking); the tests caught 17. The one they missed stored the default
tier for a client instead of erasing it, which changes memory use but no
answer the limiter gives.
Stage 8: a changed requirement
Section titled “Stage 8: a changed requirement”Think first. The owner comes back: “We now sell a paid plan. Paid clients get a bigger burst and a faster rate, and when someone upgrades or downgrades, it should take effect at once, even in the middle of their traffic.” Before opening, list what you would ask, and guess which parts of step 1 will have to change.
Show stage 8: tiers that change at run time (step 2)
The new questions.
| Question | Answer | Kind |
|---|---|---|
| Which tiers, with what limits? | A fixed table of named tiers, set at start-up. The demo uses free (burst 5, then 1 a second) and paid (burst 20, then 10 a second). | Owner |
| Can tiers be added while running? | No. What changes at run time is which tier each client is on. | Owner |
| Which tier is a client on if nobody said? | The default tier, named at start-up. | Owner |
| An unknown tier name? | Refused; the client stays where it was. | Assumption |
| On an upgrade, does a client that used its free burst get a whole paid burst at once? | No: it keeps what it has used. A client never bursts above the largest capacity it held. | Owner, after an example |
| On a downgrade, what if the client has already used more than the smaller burst? | It owes the difference, and is refused until it has earned it back. | Owner, after an example |
| Does the time before the change count at the old rate or the new? | The old rate. | Assumption, accepted |
| Can switching tiers back and forth reset the burst? | No. | Owner |
| A client with no bucket yet? | The tier is recorded; its first request gets a full bucket of that tier. | Assumption |
The two “after an example” rows are worth noticing. Asked in the abstract (“what happens to the tokens on an upgrade?”), the owner had no view. Shown the numbers (“a free client used 5 and upgrades; should it now be able to make 20 more at once, or 15?”), they answered at once.
The rule: keep what has been used. Count what a client has used as its capacity minus its tokens: the requests it has made that the bucket has not yet earned back. A tier change keeps that number and changes only the size of the bucket.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Step 2. The same bucket moved from `old_limit` to `new_limit`, for a// client whose tier changed. `bucket` must already be up to date under// old_limit, so the time before the change was earned at the old rate.//// The rule: the client keeps what it has USED, not what it has LEFT.// used = old capacity - tokens; afterwards tokens = new capacity - used.// free (5) with 0 left, moved to paid (20): 20 - 5 = 15 left// paid (20) with 17 left, moved to free (5): 5 - 3 = 2 left// paid (20) with 3 left, moved to free (5): 5 - 17 = -12, owed// So all the requests a client makes at one moment, across any number of// tier changes, never add up to more than the largest capacity it held// (each one needs used to stay at or below the capacity of the moment).// A full bucket stays full, which keeps dropping full buckets harmless.// Credit, the part-earned token, is kept as it is: a unit is worth the// same under every rate.[[nodiscard]] Bucket with_limit(Bucket bucket, const Limit& old_limit, const Limit& new_limit);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
Bucket with_limit(Bucket bucket, const Limit& old_limit, const Limit& new_limit) { const std::int64_t used = old_limit.capacity - bucket.tokens; // 0 or more bucket.tokens = new_limit.capacity - used; // may be below 0: owed // used is 0 only for a full bucket, which has no credit, so a full // bucket stays exactly a fresh one under the new limit. return bucket;}In plain words:
- An upgrade. alice, on free, has used all 5. She moves to paid, which holds 20. She has used 5 of those 20, so 15 are left. Her burst at that moment adds up to 20, the paid capacity, not 5 + 20.
- A downgrade, within the smaller burst. A paid client has used 3 of 20 and moves to free. Free holds 5; 3 are used, so 2 are left.
- A downgrade, past the smaller burst. bob, on paid, has used 17 of 20 and moves to free. Free holds only 5, and he has used 17, so he is 12 over: his tokens are 5 - 17 = -12. He owes 12 tokens and is refused until he has earned them back, plus one more to spend. At 1 a second that is 13 seconds, which is the wait the limiter tells him (AC-5.4).
Why not the other obvious rules? Keep what is left: an upgraded client with 0 left would still have 0, and a downgraded client with 17 left would hold more than the free capacity. Start full on every change: switching to paid and back would refill the bucket each time, so a client could reset its own limit; AC-5.5 switches three times and checks that nothing is forgiven. Keeping what is used is the simplest rule that gives an upgraded client its larger burst at once while the requests it makes at one moment still never add up to more than the largest capacity it held. (Keeping what is left, cut to the new capacity, is also safe, but gives an upgraded client nothing until it refills.)
Settle at the old rate first.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
bool RateLimiter::set_tier(const std::string& key, std::string_view tier) { // tiers_ never changes, so it is read before taking the lock. const auto new_tier = tiers_.find(tier); if (new_tier == tiers_.end()) { return false; } const std::scoped_lock lock(mutex_); const auto found = buckets_.find(key); if (found != buckets_.end()) { const Limit& old_limit = limit_for(key); // still the old tier here // First the time up to now is earned at the OLD rate: an upgrade // does not pay out backwards for time spent on the free tier. const Bucket settled = refilled(found->second, old_limit, now_ms(*clock_)); // Then keep what was used: see with_limit in bucket.hpp. found->second = with_limit(settled, old_limit, new_tier->second); } // Only clients off the default tier are recorded, so the map holds // just the exceptions. if (new_tier->first == default_tier_) { tiers_of_.erase(key); } else { tiers_of_.insert_or_assign(key, new_tier->first); } return true;}Before converting, set_tier brings the bucket up to date at the
old tier’s rate. Otherwise an upgrade would pay out backwards: time
spent on the free tier would be counted at the paid rate. AC-5.3 checks
it with numbers. alice uses her 5 free tokens and waits 2.5 s, which at
1 a second earns 2 tokens and 500 units. She then upgrades: she has used
3, so she has 20 - 3 = 17. The 500 units go with her, and 50 ms at the
paid rate (500 more units) completes another token, 18.
Tier assignments live outside the buckets.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Step 2: the tiers, by name, for example {"free", {5, 1}} and// {"paid", {20, 10}}. Fixed when the limiter is built; what changes at run// time is which tier each client is on. std::map, so tiers are listed in// name order; std::less<> lets find() take a string_view without first// building a std::string.using TierTable = std::map<std::string, Limit, std::less<>>;VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
const Limit& RateLimiter::limit_for(const std::string& key) const { const auto assigned = tiers_of_.find(key); const std::string& tier = assigned == tiers_of_.end() ? default_tier_ : assigned->second; // Every name in tiers_of_ was checked by set_tier, and default_tier_ // by the constructor, so find() cannot miss. tiers_ never changes, so // the reference stays valid for the limiter's whole life. return tiers_.find(tier)->second;}Which tier a client is on is kept in its own map, tiers_of_, holding
only the clients off the default tier. It is never dropped. A full
bucket can be dropped because it can be rebuilt exactly; a setting
cannot. If the tier lived inside the bucket, dropping a full paid bucket
would quietly move the client back to free. AC-5.6 drops a full paid
bucket and checks that the client’s next request gets a paid bucket. The
same mutex protects both maps, because a bucket’s numbers mean something
only together with its client’s tier.
What else changed. The check in try_acquire became
tokens <= 0 (owing is fewer than none), and refilled caps a long gap
at the time to fill from where the bucket really is, which can be below
zero. The tests grew from 17 to 27: the 17 from step 1 on a one-tier
limiter, plus AC-5.1 to AC-5.7 for tiers on one thread and AC-6.1 to
AC-6.3 for tier changes racing with requests. Those three cannot know
whether the change lands before or after each request, so they check
what must hold either way. In AC-6.1, for example, a client that has
used 1 free token is upgraded while 32 threads race: whenever the
upgrade lands, the wins plus the tokens left come to exactly 19.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// An upgrade keeps what was used: a free client that used its 5 gets// 20 - 5 = 15 more at once, so the burst at that moment is 20, the paid// capacity, and not 5 + 20.LLD_TEST(prc_rate_s2_ac_5_2_an_upgrade_keeps_what_was_used_so_a_burst_never_exceeds_capacity) { ManualClock clock; RateLimiter limiter(free_and_paid(), "free", 10, clock); spend(limiter, "alice", 5); LLD_CHECK_EQ(limiter.try_acquire("alice").verdict, Verdict::no_tokens); LLD_CHECK(limiter.set_tier("alice", "paid")); LLD_CHECK_EQ(tokens_of(limiter, "alice"), 15); spend(limiter, "alice", 15); const Decision refused = limiter.try_acquire("alice"); LLD_CHECK_EQ(refused.verdict, Verdict::no_tokens); LLD_CHECK_EQ(refused.retry_after.count(), 100); // paid: 10 a second}
// The time before the change is earned at the old rate, with its part// token: 2.5 s on free is 2 tokens and 500 units. Paying out at the new// rate instead would fill the paid bucket, which no paid client would have// at that moment.LLD_TEST(prc_rate_s2_ac_5_3_an_upgrade_does_not_pay_out_backwards_and_keeps_the_part_token) { ManualClock clock; RateLimiter limiter(free_and_paid(), "free", 10, clock); spend(limiter, "alice", 5); clock.advance(2500ms); LLD_CHECK(limiter.set_tier("alice", "paid")); LLD_CHECK_EQ(tokens_of(limiter, "alice"), 17); // used 5 - 2 = 3 clock.advance(50ms); // 500 more units at 10 a second completes a token LLD_CHECK_EQ(tokens_of(limiter, "alice"), 18);}The step 2 demo. Its real output:
free: burst 5, then 1 a second; paid: burst 20, then 10 a secondt=0ms alice (free) 6 requests: 5 allowed, then no tokens, retry after 1000ms alice to paid: now 15 tokenst=0ms alice (paid) 16 requests: 15 allowed, then no tokens, retry after 100mst=500ms alice (paid) 5 requests: 5 allowed, 0 left bob to paid: no bucket yet; the first request gets a full onet=500ms bob (paid) 17 requests: 17 allowed, 3 left bob to free: now -12 tokenst=500ms bob (free) 2 requests: 0 allowed, then no tokens, retry after 13000mst=13500ms bob (free) 2 requests: 1 allowed, then no tokens, retry after 1000ms carol to gold: refused, no such tier; still freeRead it against the rule: alice uses 5 on free and upgrades to 15 left, so her burst at 0 ms is 20. 500 ms on paid earns 5 more. bob uses 17 on paid, downgrades to -12, is refused for 13000 ms, and at 13500 ms has earned 13 tokens, which pay back the 12 and leave one to spend. The unknown tier “gold” is refused.
Which step 1 decisions made this cheap, and which made it costly.
- Cheap: lazy refill. There is no timer to re-time for the new rate. A tier change touches one bucket, under the lock every request already takes.
- Cheap: “a full bucket is a fresh one”.
with_limitkeeps a full bucket full, so dropping full buckets is still harmless, as long as the tier is kept outside them. - Cheap: the arithmetic in free functions on values. The new conversion is one more such function, tested the same way.
- Costly: one
Limitfor the whole limiter. Step 1 readlimit_in four member functions. Each now askslimit_for(key), and the sweep that drops full buckets looks up a tier per bucket. Had the bucket arithmetic not already taken theLimitas a parameter, this would have been a larger change.
Common mistakes
Section titled “Common mistakes”Rounding at every refill
Section titled “Rounding at every refill”Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// Flawed: whole tokens only, and last_ms moves on even when nothing was earned.struct WholeTokenBucket { std::int64_t tokens = 0; std::int64_t last_ms = 0;};
void refill(WholeTokenBucket& bucket, const Limit& limit, std::int64_t now_ms) { const std::int64_t earned = (now_ms - bucket.last_ms) * limit.tokens_per_second / 1000; bucket.tokens = std::min(limit.capacity, bucket.tokens + earned); bucket.last_ms = now_ms; // the part token just earned is thrown away}It goes wrong on the last line, together with the division above it.
The division rounds down, and moving last_ms to now throws away what
was rounded off. A client at 1 token a second that is checked every
100 ms earns 0 each time, for ever: in a run of 100 such refills (10
seconds), this bucket stayed at 0 tokens, while the exact version below
filled to its capacity of 5. At 10 tokens a second, checked every 150 ms
for 3 seconds (with a capacity too large to stop it), it earned 20
tokens instead of 30. The more often clients
ask, the less they get, which is backwards.
Using double for the tokens avoids the worst of this but not all of
it: adding 0.1 ten times gives 0.99999999999999989 in a double, not 1,
so “at least one token” is false at exactly the moment it should become
true.
IllustrativeA fragment for explanation; not compiled on its own.
// Carry the part token as credit, in units of 1/1000 token, and never round.void refill_exact(Bucket& bucket, const Limit& limit, std::int64_t now_ms) { if (now_ms <= bucket.last_ms) return; bucket.credit += (now_ms - bucket.last_ms) * limit.tokens_per_second; bucket.last_ms = now_ms; bucket.tokens += bucket.credit / units_per_token; bucket.credit %= units_per_token; if (bucket.tokens >= limit.capacity) { bucket.tokens = limit.capacity; bucket.credit = 0; }}This is the idea of refilled in step 1, without its cap on long gaps,
which protects against overflow.
Checking and spending under two locks
Section titled “Checking and spending under two locks”Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// Flawed: every access holds the lock, but "check" and "spend" are two steps.class SplitLockLimiter {public: SplitLockLimiter(Limit limit, const Clock& clock) : limit_(limit), clock_(&clock) {}
bool try_acquire(const std::string& key) { Bucket copy; { const std::scoped_lock lock(mutex_); const std::int64_t now = now_ms(*clock_); const auto found = buckets_.try_emplace(key, full_bucket(limit_, now)).first; copy = refilled(found->second, limit_, now); } // lock released: another thread can now read the same tokens if (copy.tokens == 0) return false; --copy.tokens; const std::scoped_lock lock(mutex_); buckets_[key] = copy; // overwrites whatever other threads spent meanwhile return true; }
private: const Limit limit_; const Clock* clock_; std::mutex mutex_; std::unordered_map<std::string, Bucket> buckets_;};It goes wrong where the first lock is released. Two threads can both copy a bucket with 10 tokens, both decide yes, and both write back 9: two requests allowed, one token spent. This was run with the AC-4.1 race (32 threads, 10 tokens, time standing still) for 1000 rounds on a 16-core machine. In six runs, three of them built with ThreadSanitizer, between 590 and 999 of the 1000 rounds allowed more than 10 requests, and some rounds allowed all 32. ThreadSanitizer reported no race, because every access to the map holds the lock. This is a race in the logic, not a data race, and only an exact count can see it.
IllustrativeA fragment for explanation; not compiled on its own.
// One lock held for the whole "refill, check, spend".bool try_acquire(const std::string& key) { const std::scoped_lock lock(mutex_); const std::int64_t now = now_ms(*clock_); Bucket& bucket = buckets_.try_emplace(key, full_bucket(limit_, now)).first->second; bucket = refilled(bucket, limit_, now); if (bucket.tokens == 0) return false; --bucket.tokens; return true;}The same member function in the same class, run with the same race for
1000 rounds, never allowed more than 10 in a round. It still has no memory
bound; step 1’s try_acquire adds that.
Forgetting a client that is not full
Section titled “Forgetting a client that is not full”Covered in stage 6: dropping the least recently used bucket at the memory bound hands the client that has just used its burst a fresh one. Drop only buckets that are full, and refuse the new client when none is.
Limitations
Section titled “Limitations”This is a teaching example, not a production rate limiter.
- One process, in memory. Each copy of the service limits on its own, so three copies allow three times the limit. A restart forgives every client. A shared limit across servers needs a shared store, and a different design.
- One mutex for every client. Every request from every client takes the same lock. That is simple and exact, but under heavy load the lock becomes the place where threads wait. Splitting the table into several shards, each with its own lock and bound, is the usual next step; it makes the bound per shard, not global.
- The sweep at the bound. When the table is full, each new client costs a pass over every tracked bucket under the lock. A flood of invented keys against a full table of busy clients makes every one of those requests do that pass.
- Assignments are not bounded. In step 2,
tiers_of_grows with every client put on a non-default tier. The service controls those calls, so it controls that size, but the limiter does not. - No fairness. Which waiting thread gets the next token depends on the scheduler. Nothing queues, and nothing is promised about order.
- Whole milliseconds. Times are floored to milliseconds; a rate needing finer resolution would need smaller units.
- Not tested with time moving under threads. The threaded tests freeze the clock, so concurrent refill is covered by reasoning about the lock, not by a test.
Exercise
Section titled “Exercise”Exercise: Requests that cost more than one token
The owner is back: “Exports are expensive. An export request should count as 5 normal requests.” Starting from step 2:
- Write the declaration and definition of a
try_acquirethat takes a cost. Is it all or nothing, or may it spend some tokens? - What should happen to a cost of 0, and to a cost larger than the client’s capacity? Which of these is a caller’s mistake, and which an ordinary refusal?
- How is the wait worked out, and what changes for a client that owes tokens?
- List the tests you would add, and one new risk this brings.
Show the explained answer
All or nothing. Spending part of a cost and refusing the rest would leave the client poorer with nothing done.
Two kinds of bad cost. A cost below 1 is a bug in the caller, so it
throws std::invalid_argument. A cost above the capacity of the
client’s tier can never succeed, however long the client waits, so it
is refused with a new verdict, cost_above_capacity, and no wait: a
no_tokens with a wait would be a hint that can never come true. Which
capacity? The one of the client’s tier now, so a cost of 6 is refused on
free (5) and allowed on paid (20). The check comes before a new client
is given a slot in the table: a request that can never succeed should
not take room from one that can.
IllustrativeA fragment for explanation; not compiled on its own.
// In limiter.hpp, add cost_above_capacity to Verdict (and to to_string), and:[[nodiscard]] Decision try_acquire(const std::string& key) { return try_acquire(key, 1); }
// Asks for `cost` tokens at once, all or none. Throws// std::invalid_argument for a cost below 1. A cost above the// capacity of the client's tier now is refused with// cost_above_capacity: waiting would never help.[[nodiscard]] Decision try_acquire(const std::string& key, std::int64_t cost);
// In limiter.cpp:Decision RateLimiter::try_acquire(const std::string& key, std::int64_t cost) { if (cost < 1) { throw std::invalid_argument("cost must be at least 1"); } const std::scoped_lock lock(mutex_); const std::int64_t now = now_ms(*clock_); const Limit& limit = limit_for(key); // Checked before a new client is given a slot: a request that can // never succeed should not take room from one that can. if (cost > limit.capacity) { return {Verdict::cost_above_capacity, 0, std::chrono::milliseconds{0}}; }
auto found = buckets_.find(key); if (found == buckets_.end()) { if (buckets_.size() >= max_clients_) { drop_full_buckets(now); } if (buckets_.size() >= max_clients_) { return {Verdict::too_many_clients, 0, time_until_a_bucket_is_full(now)}; } found = buckets_.emplace(key, full_bucket(limit, now)).first; }
Bucket& bucket = found->second; bucket = refilled(bucket, limit, now); if (bucket.tokens < cost) { // All or none: nothing is spent. time_until already takes how // many tokens are wanted, and counts any that are owed. return {Verdict::no_tokens, 0, time_until(bucket, limit, cost)}; } bucket.tokens -= cost; return {Verdict::allowed, bucket.tokens, std::chrono::milliseconds{0}};}This answer was compiled and checked in a scratch copy of step 2, not
in the example itself. The one-token try_acquire now calls the new
one, so the 27 step 2 tests exercise it, and they still passed.
The wait. time_until already takes the number of tokens wanted,
and it already counts owed tokens, so the wait needs no new arithmetic.
On free, a cost of 3 from a full bucket is allowed with 2 left; a
second cost of 3 at once is refused with a wait of 1000 ms (one more
token at 1 a second). A client that used 6 on paid and then moved to
free has 5 - 6 = -1 tokens, so a cost of 2 needs 3 tokens: a wait of
3000 ms. These numbers come from the check program.
Tests to add.
- AC-7.1: a cost is all or nothing; a refused cost spends nothing and keeps the part token.
- AC-7.2: the wait for a cost is exact to the millisecond (refused 1 ms before the hint, allowed at it), including for a client that owes tokens.
- AC-7.3: a cost above the tier’s capacity is refused with
cost_above_capacity, does not take a slot in the table, and becomes allowed after an upgrade to a tier that holds it. - AC-7.4: a cost below 1 throws
std::invalid_argument. - AC-7.5: with time standing still, threads asking for costs of 1 and 5 together never spend more than the capacity.
The new risk. A large request can wait for ever if small requests keep spending each token as it arrives, because nobody holds tokens back for it. Whether that matters is a question for the owner; the limiter does not promise fairness.
Summary
Section titled “Summary”- Turn “stop one client from flooding us” into numbers: per what, how big a burst, how fast after it, how many clients, how many threads. Mark which answers are your assumptions.
- Compare algorithms by what they allow at the edges, their memory per client, and their precision. A token bucket fits “a burst, then a steady rate”; a sliding log or a fixed window fits other needs.
- Keep fractions as whole-number credit and divide only the running total, so nothing drifts. Round a wait up, so a retry on the hint is never early.
- At a memory bound, forget only what can be rebuilt exactly. Here that is a full bucket, and never a tier setting.
- Hold one lock for the whole “refill, check, spend”, and read the clock under it. ThreadSanitizer finds data races in the runs that happen; exact counts are needed to find a check and a spend that are each locked but not together.
- Inject the clock, so timing tests are exact and never sleep.