10.2 Rate Limiting: RPM Token Buckets and TPM Reserve/Settle
After API keys and scopes, the gateway knows who is calling, but every caller can still send as fast as its network allows. One tenant’s batch job at 50 requests per second fills the engine’s queue (the scheduler from Continuous batching scheduler with priority and preemption in AI Engineering), and every other tenant’s time to first token goes from milliseconds to seconds. That is the noisy-neighbor incident you will meet in the noisy neighbor drill in Systems Engineering.
Concepts from other sections (8)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- time to first token (TTFT): the time until the first body byte of an answer is ready to send to the client. Read more: 25.3 The SSE streaming proxy in AI Engineering
- Little’s law: for any stable system. Read more: 13.12 Probability problem set, part d: hypothesis tests, regression, queueing, balls into bins in Mathematics
- composition root: the one place (here
main) where independent components are constructed and wired together. Read more: 25.2 The server skeleton in AI Engineering - chat template: the byte-level protocol that renders a list of role-tagged messages into one token sequence. Read more: 18.1 Supervised fine-tuning: chat rendering, assistant-only loss, packing in AI Engineering
- Exactly-once: the guarantee that each record affects state exactly once. Read more: Chapter 3: Batch and Streaming Processing in Data Engineering
- goroutine: a function running concurrently, scheduled by the Go runtime. Read more: 1.6 Go: packages, interfaces, goroutines, channels, context, net/http, testing in Programming and Algorithms
- Data race: two accesses to the same memory from different goroutines, at least one a write, with no happens-before order between them. Read more: 6.2 Code review
- Service Level Objective (SLO): a target for a defined measure of service behavior over a specified window. Read more: Chapter 13: Engineering Acronyms
Counting requests is not enough for an LLM, either. One request with a 4000-token prompt and max_tokens: 2000 costs a hundred times a short chat turn. This section gives each key two budgets, requests per minute (RPM) and tokens per minute (TPM), enforced before the request reaches the cache or an engine, and tells the client exactly when to come back. The hard part is that a request’s token cost is not known until its response ends, which leads to a two-phase reserve-and-settle protocol.
This section builds on The server skeleton (the chain and the Exchange) and on API keys and scopes (the Principal and its limits). Useful background is the queueing and Little’s law problems in Probability problem set, part d: hypothesis tests, regression, queueing, balls into bins in Mathematics, and the token bucket warm-up in the practice drill go/07. The full solution is go/gateway/limit/limit.go: Limiter (New, Reserve), Reservation (Settle, Cancel, Status), RejectError, EstimateCost, PromptText, TokenizeCounter, SetHeaders, RetryAfterSeconds, and Middleware. The contract is the 429 rate_limit_error / rate_limit_exceeded, Retry-After, and the x-ratelimit-* headers in openai-subset.v1.yaml, plus rpm and tpm of KeyCreate in admin.v1.yaml.
In the finished system, gateway.Deps (go/gateway/gateway.go), from the usage ledger and admin API section, wraps limit.Middleware(limiter, counter) into the chain’s Limiter slot, and the composition root (entry/go/cmd/gateway/compose.go) builds the limiter with limit.New(nil), which uses the wall clock. It sets no Counter, so the shipped gateway estimates prompt tokens as bytes / 4 and relies on Settle for the exact count; a limit.TokenizeCounter{BaseURL: engineURL} makes the estimate exact.
Learning objectives
- Derive the token bucket, compute its admission decision and wait time by hand, and explain why it beats fixed windows and sliding logs.
- Enforce RPM and TPM as two buckets per key under one lock, so concurrent requests can never overspend.
- Reserve an estimated token cost before a request runs and settle the actual usage exactly once afterwards.
- Emit
Retry-Afterand thex-ratelimit-*headers correctly, rounding waits up.- Decide when a failed request should be cancelled rather than charged.
The token bucket
Section titled “The token bucket”A token bucket needs only a few quantities:
| Symbol | Meaning | Type |
|---|---|---|
bucket capacity: the per-minute limit (rpm or tpm of the key) | integer | |
| the bucket’s level at time | real, may go negative after an overrun | |
| refill rate per second | real | |
| the cost of a request in this bucket | integer | |
| the wait before tokens are available | seconds |
The bucket starts full, . Between decisions it refills continuously and is capped: . A request costing is admitted when , and then . Otherwise it must wait
which is the Retry-After the client receives, in whole seconds, rounded up.
Two properties follow. Because of the cap, a key idle for an hour can burst at most at once: a full bucket allows a burst of one minute’s budget, never more. And over any long window, the admitted rate approaches , which is the limit. Each key has its own pair of buckets, so keys never spend each other’s budget. A key with limit 0 has no bucket at all; it is unlimited, per admin.v1.yaml.
Why not a fixed window, “at most 60 per calendar minute”? It admits 120 in two seconds across a minute boundary. Why not a sliding log of timestamps? It is exact but costs memory per request. The bucket is O(1) per key and smooth.
Reserve and settle
Section titled “Reserve and settle”The bucket handles requests easily, because a request’s cost in the request bucket is always 1. Tokens are harder. A request’s token cost is prompt tokens plus completion tokens, and the completion length is known only when the stream ends. So the stage splits the decision in two:
- Estimate the cost: prompt tokens counted by the engine’s tokenizer (
POST /v1/tokenize, on the engine tier) over the prompt text, plusmax_completion_tokensormax_tokens, or 256 when neither is set. The prompt text is the completionsprompt, or the chat contents joined by newlines; the chat template adds a few tokens this leaves out. If the tokenizer is unreachable, the estimate falls back to rather than failing the request. - Reserve that estimate in both buckets (1 request, tokens), or reject with 429.
- Run the rest of the chain.
- Settle with the actual usage that the SSE streaming proxy put on the
Exchange. The difference between reserved and actual goes back into the bucket (capped at ) or, for an overrun, is taken from it, possibly below zero. A negative level is a debt the key’s next requests wait off.
A reservation is settled or cancelled once. If the code settles and then a deferred cleanup cancels, the second call must do nothing, or the key gets a refund it never earned. And if the request failed with a 5xx and no usage (no engine had capacity), the stage cancels, so the request and the tokens both come back: clients do not pay for our outages.
What the client sees
Section titled “What the client sees”The limiter is only useful if clients can pace themselves, so every authenticated response carries five headers, defined in openai-subset.v1.yaml:
| Header | Value |
|---|---|
x-ratelimit-limit-requests / -tokens | of each bucket |
x-ratelimit-remaining-requests / -tokens | after this request’s reservation, at least 0 |
x-ratelimit-reset-tokens | time until the token bucket is full again, as a Go duration (18s) |
A 429 carries the same headers plus Retry-After: ⌈w⌉ seconds. Rounding down would invite the client back before the budget exists, and a of 0.4 s would become Retry-After: 0, which means “retry now”. So the value is and at least 1.
Working it by hand
Section titled “Working it by hand”Key k has RPM 3 and TPM 1000, and the clock starts at .
- A request reserves 300 tokens (prompt 60,
max_tokens240). The request bucket goes and the token bucket . The headers say remaining requests 2, remaining tokens 700, and reset-tokens s. - It finishes having used 120 tokens. Settle refunds , so the token bucket is .
- Still at , a request needs 900 tokens. Since , it must wait s. The answer is 429 with
Retry-After: 2and remaining tokens 880. - At s the token bucket has refilled tokens to exactly 900, so the request is admitted and leaves 0. The request bucket has refilled to 2.06, and after this request holds 1.06: remaining requests 1.
Designing the package
Section titled “Designing the package”The API keeps the limiter ignorant of HTTP; the middleware and helpers handle the protocol:
package limit // import "tinyllm/gateway/limit"
type Cost struct{ Requests, Tokens int }type Limits struct{ RPM, TPM int } // 0 = unlimitedtype Status struct { LimitRequests, RemainingRequests, LimitTokens, RemainingTokens int ResetTokens time.Duration}type RejectError struct { RetryAfter time.Duration; Status Status }type Reservation interface { Settle(actual Cost); Cancel(); Status() Status }
func New(clock server.Clock) *Limiterfunc (l *Limiter) Reserve(ctx context.Context, key string, lim Limits, c Cost) (Reservation, error)
type Counter interface { CountPrompt(ctx context.Context, model string, body []byte) (int, error) }type TokenizeCounter struct { BaseURL string; Client *http.Client } // the engine's /v1/tokenizefunc PromptText(body []byte) stringfunc EstimateCost(ctx context.Context, counter Counter, req *server.Request) Costfunc SetHeaders(h http.Header, s Status)func RetryAfterSeconds(d time.Duration) intfunc Middleware(l *Limiter, counter Counter) server.MiddlewareThe catalog sketched Reserve(ctx, key, c). This one also takes the key’s Limits, because limits live on the key record and change when an admin edits the key, so the limiter holds buckets, not key metadata. Time comes only from the Clock, so a fake clock drives refill exactly.
Building it step by step
Section titled “Building it step by step”The design follows from seven observations:
- The state per key must be O(1). The limiter sees every request of every key, so it cannot keep a log of timestamps. A token bucket summarizes the whole history in two numbers: the level and the time it was last brought up to date.
- Refill can be computed lazily. Because refill is linear in time and capped, there is no need for a timer: on each decision, add and cap at . That makes the bucket correct at whatever moments the clock is read, and lets a fake clock drive it exactly.
- Two budgets, one decision. A request must fit both the request bucket and the token bucket. If either is short, it waits for the slower one, so the wait is the maximum of the two. Taking from one bucket and then failing the other would leak budget, so the check happens first and the take after, under one lock.
- The cost is unknown up front, so split the decision in two. Reserve an upper-ish estimate before the request runs (prompt tokens plus
max_tokens), then settle the difference with the real usage when it ends. The bucket may go negative after an overrun, and that debt is what makes requests withoutmax_tokenspay. - A reservation is a one-shot. Settle or Cancel, whichever comes first, wins; the other is a no-op.
sync.Onceis exactly that. - A request larger than can never fit. Waiting for tokens is waiting forever, so it is rejected outright, with the time to a full bucket as a hint, rather than admitted when the bucket happens to be full.
- Time comes only from an injected clock. Then the hand example is reproducible to the nanosecond, and refill is testable without sleeping.
The bucket
Section titled “The bucket”Levels are float64, so fractional refill (the 0.06 of a request in step 4 of the hand example) is kept rather than rounded away:
type bucket struct { capacity float64 // C: the per-minute limit level float64 // L(t_last); may be negative after an overrun last time.Time}
// refill brings the bucket up to now: L <- min(C, L + C * minutes elapsed).func (b *bucket) refill(now time.Time) { if dt := now.Sub(b.last); dt > 0 { // a clock that steps back adds nothing b.level = math.Min(b.capacity, b.level+b.capacity*dt.Minutes()) } b.last = now}
// wait is w = (n - L) / C minutes, rounded up to the next nanosecond so that// at now + w the bucket really holds n.func (b *bucket) wait(n float64) time.Duration { if b.level >= n { return 0 } return time.Duration(math.Ceil((n - b.level) / b.capacity * float64(time.Minute)))}Per-key state
Section titled “Per-key state”A key’s buckets are created full the first time it is seen. Because limits live on the key record and an admin may edit them, state resizes the buckets when the limits change, keeping the same fraction of capacity. Raising a limit therefore does not hand out a fresh burst, and lowering it does not leave the key over its new budget:
func (l *Limiter) state(key string, lim Limits, now time.Time) *keyState { st, ok := l.keys[key] if !ok { // first sight: both buckets full st = &keyState{ req: bucket{capacity: float64(lim.RPM), level: float64(lim.RPM), last: now}, tok: bucket{capacity: float64(lim.TPM), level: float64(lim.TPM), last: now}, lim: lim, } l.keys[key] = st return st } if st.lim != lim { // limits edited: keep L/C, change C // ... resize each bucket: level = level / old capacity * new capacity } st.req.refill(now) st.tok.refill(now) return st}Reserve: check both, then take both
Section titled “Reserve: check both, then take both”A zero limit skips its bucket entirely (unlimited). The min(c.Tokens, lim.TPM) keeps the wait finite for an oversize request, and the explicit c.Tokens > lim.TPM test rejects it even when the bucket is full:
func (l *Limiter) Reserve(ctx context.Context, key string, lim Limits, c Cost) (Reservation, error) { now := l.clock.Now() l.mu.Lock() // one lock around read-refill-decide-take: no two requests spend the same token defer l.mu.Unlock() st := l.state(key, lim, now) var wait time.Duration if lim.RPM > 0 { wait = max(wait, st.req.wait(float64(min(c.Requests, lim.RPM)))) } if lim.TPM > 0 { wait = max(wait, st.tok.wait(float64(min(c.Tokens, lim.TPM)))) } if wait > 0 || (lim.TPM > 0 && c.Tokens > lim.TPM) || (lim.RPM > 0 && c.Requests > lim.RPM) { if wait == 0 { // oversize with a full bucket: point at "full again" as the hint wait = st.tok.wait(st.tok.capacity) } return nil, &RejectError{RetryAfter: wait, Status: st.status()} // nothing taken } if lim.RPM > 0 { st.req.level -= float64(c.Requests) } if lim.TPM > 0 { st.tok.level -= float64(c.Tokens) } return &reservation{l: l, key: key, cost: c, status: st.status()}, nil}Settle and Cancel
Section titled “Settle and Cancel”Both are a signed adjustment of the buckets. Settle returns reserved - actual, which is negative for an overrun and so takes more; Cancel returns everything. The cap at capacity means a refund never pushes a bucket above , and sync.Once makes the pair exactly-once:
func (r *reservation) Settle(actual Cost) { r.once.Do(func() { // reserved 300, used 120: +180 back; reserved 100, used 700: -600 more r.l.adjust(r.key, r.cost.Requests-actual.Requests, r.cost.Tokens-actual.Tokens) })}
func (r *reservation) Cancel() { r.once.Do(func() { r.l.adjust(r.key, r.cost.Requests, r.cost.Tokens) })}adjust takes the lock, refills both buckets to now, and adds the deltas with math.Min(capacity, level + d).
The estimate
Section titled “The estimate”Prompt tokens come from the engine’s tokenizer when it answers, otherwise from . Completion tokens come from max_tokens (the Exchange has already resolved max_completion_tokens over max_tokens into MaxTokens), or 256:
func EstimateCost(ctx context.Context, counter Counter, req *server.Request) Cost { prompt := -1 if counter != nil { if n, err := counter.CountPrompt(ctx, req.Model, req.Body); err == nil { prompt = n } } if prompt < 0 { // tokenizer down: estimate, never 0 and never fail the request prompt = (len(PromptText(req.Body)) + 3) / 4 } completion := req.MaxTokens if completion <= 0 { completion = DefaultCompletionReserve // 256; Settle charges the truth afterwards } return Cost{Requests: 1, Tokens: prompt + completion}}
func RetryAfterSeconds(d time.Duration) int { s := int(math.Ceil(d.Seconds())) // 1.2 s -> 2: never invite the client back early if s < 1 { s = 1 // "0" would mean "retry now" } return s}The middleware
Section titled “The middleware”The middleware reserves before next and settles after it, with a deferred Cancel as a safety net if the rest of the chain panics:
p, ok := auth.PrincipalFrom(r.Context())if !ok { // no authn stage in front: nothing to key by, so do not limit next.ServeHTTP(w, r) return}// ... cost = EstimateCost(...) for POSTs, Cost{Requests: 1} otherwiseres, err := l.Reserve(r.Context(), p.KeyID, Limits{RPM: p.RPM, TPM: p.TPM}, cost) // keyed by key, not tenantvar rej *RejectErrorif errors.As(err, &rej) { SetHeaders(w.Header(), rej.Status) w.Header().Set("Retry-After", strconv.Itoa(RetryAfterSeconds(rej.RetryAfter))) // ... 429 rate_limit_error / rate_limit_exceeded return}// ...SetHeaders(w.Header(), res.Status()) // on every admitted response, not only on 429settled := falsedefer func() { if !settled { res.Cancel() // a panic below: nothing ran to completion }}()next.ServeHTTP(w, r)st := ex.Snapshot() // the usage the proxy recordedswitch {case st.Usage.TotalTokens > 0 || st.Usage.PromptTokens+st.Usage.CompletionTokens > 0: // ... tokens = TotalTokens, or prompt + completion when the total is missing res.Settle(Cost{Requests: 1, Tokens: tokens})case st.Status >= 500: res.Cancel() // our failure, no usage: the client pays nothingdefault: res.Settle(Cost{Requests: 1}) // ran but produced no usage: the request counts, the tokens come back}settled = trueThe full code is in limit.go. PromptText (the completions prompt, chat contents joined by \n, or embeddings input) and TokenizeCounter (a POST /v1/tokenize of {model, text} that counts the returned ids) are in the same file.
Why this design
Section titled “Why this design”Reserve, Settle, and Cancel are O(1) under one mutex, and memory is two buckets per key ever seen. The tokenizer call is one HTTP round trip per POST, outside the lock.
Why one global mutex and not one per key? The critical section is a handful of float operations, far shorter than any request; contention is negligible at gateway rates, and one lock makes the map and the buckets trivially consistent. Per-key locks would add a second map and lock ordering for no measurable gain. Why reject instead of delaying requests until budget exists? Holding a request open ties up a connection and a goroutine per throttled request and hides back-pressure from the client, while a 429 with an exact Retry-After lets well-behaved clients pace themselves. Why reserve an estimate instead of charging only afterwards? Charging only after the response lets a key start many expensive requests at once before any of them is counted. Reserving first bounds what can be in flight, and settling afterwards keeps the long-run total exact.
One tradeoff is accepted: buckets are per process. With gateway replicas and no stickiness, a key can get up to times its budget. A shared store (Redis GCRA, Envoy’s global rate limit service) fixes that at the price of a network hop per request, as discussed at the end of this section.
What can go wrong
Section titled “What can go wrong”A correct solution must pass these checks:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| the hand example | unit | every number: remaining counts, reset 18 s, the settle refund, RetryAfter 1.2 s and Retry-After 2, admission at 1.2 s | one exact definition of the bucket |
| burst, then refill | unit | 60 at once, the 61st waits 1 s, one per second after, 10 idle minutes bank only 60 | the burst limit in the load report |
| settle charges an overrun | unit | reserve 100, use 700: the next 10 tokens wait 11 s | requests without max_tokens cannot dodge TPM |
| cancel and settle count once | unit | cancel returns everything; a second cancel and a cancel after settle do nothing | no double refunds |
| zero means unlimited | boundary | limits of 0 never reject | the admin API’s “0 = unlimited” |
| oversize cost rejected | boundary | 1001 tokens against TPM 1000 is rejected even when the bucket is full; 1000 fits | one request cannot exceed a minute’s budget |
| keys are independent | unit | key a exhausted, key b untouched | the noisy-neighbor drill |
| concurrent reserve | property | 1000 goroutines, RPM 100: exactly 100 admitted, no data race | correctness under load |
Retry-After rounding | boundary | 0, 1 ms, 1.2 s, 59 s, 59.001 s | clients come back when the budget exists |
| the cost estimate | unit | prompt + max_tokens; max_completion_tokens wins; 256 default; bytes / 4 when the tokenizer fails | reservations close to the truth |
| the prompt text | unit | prompt, chat contents, embeddings input | the text that is tokenized |
| the tokenizer counter | unit | posts {model, text} to /v1/tokenize and counts the ids | the production counter |
| headers and the 429 | conformance | headers on every 200; the third request at RPM 2 is 429 with Retry-After: 30 and the error shape | the contract’s ratelimit.429 behaviour |
| the middleware settles actual usage | unit | the next response’s remaining tokens reflect the actual usage, not the estimate | TPM tracks real cost |
| the middleware cancels on a 5xx | unit | after a 503 without usage the one-request budget is back | our outages are free |
| no principal passes through | boundary | no principal: no headers, no limit | the stage is safe before authentication is plugged in |
| buckets keyed by key id | unit | two keys of one tenant have separate budgets | a CI key cannot starve a developer’s |
Most of the bugs people write here are arithmetic. Refill without the cap lets a key idle overnight send a day’s budget at once; refill takes math.Min(capacity, ...), and refunds in adjust are capped too. Refilling per second instead of per minute makes limits 60 times too loose, and rounding Retry-After down makes clients retry straight into another 429; refill multiplies by dt.Minutes(), and RetryAfterSeconds uses math.Ceil with a floor of 1.
Settlement has its own family. Refunding the whole reservation, never charging an overrun, letting both settle and cancel count, or settling the estimate instead of the actual usage all make TPM drift from real usage, in one direction or the other. Settle adjusts by reserved - actual (negative for overruns), guarded by sync.Once, and the middleware settles with the usage from ex.Snapshot(). Treating 0 as an empty budget locks unlimited keys out, and charging requests that failed with a 5xx makes clients pay for our outages; every bucket operation is guarded by lim.RPM > 0 or lim.TPM > 0, and a 5xx without usage calls Cancel. Admitting a request larger than the limit because the bucket happens to be full lets one request take more than a minute’s tokens; Reserve rejects c.Tokens > lim.TPM explicitly.
Warning: Without a lock around each decision, more requests than the limit are admitted under load; with one bucket per tenant instead of per key, keys drain each other. The solution uses one mutex around refill-decide-take and keys buckets by
p.KeyID.
Two more affect what clients experience. Sending headers only on 429 means clients cannot pace themselves before they are throttled; SetHeaders runs on the admitted path as well as the 429 path. And a bad estimate, 0 tokens when the tokenizer fails or max_tokens ignored, lets huge requests pass the reservation and overdraw afterwards; EstimateCost falls back to and adds MaxTokens or 256.
Where this leads
Section titled “Where this leads”Looking back, the limiter fills the Limiter slot of the chain from the server skeleton and reads the usage the proxy records on the Exchange, and its buckets are keyed by Principal.KeyID with the key’s RPM and TPM from API keys and scopes. Looking forward, gateway.Deps in the usage ledger and admin API section calls limit.Middleware between policy and cache, so a cached answer still spends the key’s RPM. Two other places exercise this code over HTTP through the gateway rather than calling it: running the load generator with --rate 50 against a low-tier key shows 429s at the configured rate, and the noisy neighbor drill floods one tenant while the limits keep the others inside their SLO.
Each piece has a production counterpart:
| Solution piece | Production equivalent | What it adds | Where to look |
|---|---|---|---|
| per-process buckets | Envoy global rate limit service, Redis GCRA | one budget shared by every gateway replica | Envoy global rate limiting (free), GCRA (free) |
| reserve and settle | saige’s shared Budget | request, token, and cost capacity reserved under one lock and settled once | saige budget package |
| two buckets per key | OpenAI and Anthropic API rate limits | per-model and per-organization tiers, daily caps | OpenAI rate limits (free) |
429 and Retry-After | client-side backoff with jitter | clients that spread their retries instead of synchronizing | AWS: Exponential backoff and jitter (free) |
Further reading
Section titled “Further reading”- Tanenbaum, Computer Networks, on the token bucket.
- The GCRA in the ATM Forum’s traffic management specification.
- Stripe, Scaling your API with rate limiters (free).
Key terms
Section titled “Key terms”- Token bucket: a counter capped at that refills at per minute and admits a request when it holds the request’s cost.
- RPM / TPM: requests per minute and tokens per minute, the two per-key budgets.
- Reservation: an estimated cost taken from the buckets before a request runs, to be settled or cancelled once.
- Settle: adjusting a reservation by
reserved - actualonce the real usage is known, refunding or charging the difference. - Overrun debt: a negative bucket level left by a request that used more than it reserved, paid off by waiting.
Retry-After: the whole number of seconds, rounded up and at least 1, after which the budget will exist.
Summary
Section titled “Summary”- A token bucket holds at most tokens and refills at per minute; a request takes tokens if they are there, otherwise it waits exactly as long as the refill needs, and a full bucket allows a burst of one minute’s budget, never more.
- RPM and TPM are two buckets per key. Token cost is unknown when a request starts, so the limiter reserves an estimate (prompt tokens plus
max_tokens) and settles the actual usage when the response ends: unused tokens come back, overruns are charged. - A 429 carries
Retry-Afterin whole seconds rounded up, and every authenticated response carries the fivex-ratelimit-*headers. - Exactly one of
SettleandCancelcounts, and a request that failed with a 5xx before any usage is cancelled, so clients do not pay for our outages. - One mutex guards every bucket decision: 1000 goroutines against a budget of 100 admit exactly 100.
Review questions
Section titled “Review questions”- In step 4 of the hand example, why are remaining requests 1 and not 2, given that 3 requests per minute were allowed and only 2 have been made?
Answer
The bucket was at 2 after the first request, refilled only $3 \cdot 1.2 / 60 = 0.06$ in 1.2 s (the 429 at step 3 took nothing), so it held 2.06 and the new request leaves 1.06. The header is $\lfloor 1.06 \rfloor = 1$. The bucket counts budget earned over time, not requests left in a calendar minute. - Why does
Reservecompute the wait withmin(c.Tokens, lim.TPM)and then rejectc.Tokens > lim.TPMseparately?Answer
Without the `min`, the wait for $n > C$ would be finite but meaningless: the bucket is capped at $C$ and never reaches $n$. Clamping keeps the arithmetic sane, and the explicit test rejects the request even when the bucket is full, so one request can never take more than a minute's budget. - A request reserves 300 tokens; the proxy panics before recording usage. What does the key get back, and which line makes that happen?
Answer
Everything: the deferred function sees `settled == false` and calls `res.Cancel()`, which returns 1 request and 300 tokens. Had `Settle` already run, `sync.Once` would make that `Cancel` a no-op, so no double refund is possible. - Why does a 5xx without usage cancel, while a 4xx without usage settles with one request?
Answer
A 5xx without usage means the gateway or the engines failed before doing work: charging the client would make it pay for our outage. A 4xx is the client's own bad request: it still consumed a request slot, so the request counts, but no tokens were generated, so the token reservation comes back. - Why are buckets keyed by
Principal.KeyIDrather than by tenant?Answer
Limits are set per key (`rpm`, `tpm` on the key record), and one tenant often has several keys with different jobs, such as CI and a developer. Keying by tenant would let a CI job's burst starve the developer's key, the noisy-neighbor problem inside one tenant.