Skip to content

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.

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-After and the x-ratelimit-* headers correctly, rounding waits up.
  • Decide when a failed request should be cancelled rather than charged.

A token bucket needs only a few quantities:

SymbolMeaningType
CCbucket capacity: the per-minute limit (rpm or tpm of the key)integer
L(t)L(t)the bucket’s level at time ttreal, may go negative after an overrun
ρ=C/60\rho = C / 60refill rate per secondreal
nnthe cost of a request in this bucketinteger
wwthe wait before nn tokens are availableseconds

The bucket starts full, L=CL = C. Between decisions it refills continuously and is capped: L(t2)=min⁡(C, L(t1)+ρ (t2−t1))L(t_2) = \min(C,\ L(t_1) + \rho\,(t_2 - t_1)). A request costing nn is admitted when L≥nL \ge n, and then L←L−nL \leftarrow L - n. Otherwise it must wait

w=n−Lρ=(n−L)⋅60C seconds,w = \frac{n - L}{\rho} = \frac{(n - L) \cdot 60}{C}\ \text{seconds},

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 CC at once: a full bucket allows a burst of one minute’s budget, never more. And over any long window, the admitted rate approaches ρ\rho, 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.

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:

  1. Estimate the cost: prompt tokens counted by the engine’s tokenizer (POST /v1/tokenize, on the engine tier) over the prompt text, plus max_completion_tokens or max_tokens, or 256 when neither is set. The prompt text is the completions prompt, 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 ⌈bytes/4⌉\lceil \text{bytes} / 4 \rceil rather than failing the request.
  2. Reserve that estimate in both buckets (1 request, nn tokens), or reject with 429.
  3. Run the rest of the chain.
  4. 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 CC) 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.

The limiter is only useful if clients can pace themselves, so every authenticated response carries five headers, defined in openai-subset.v1.yaml:

HeaderValue
x-ratelimit-limit-requests / -tokensCC of each bucket
x-ratelimit-remaining-requests / -tokens⌊L⌋\lfloor L \rfloor after this request’s reservation, at least 0
x-ratelimit-reset-tokenstime 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 ww of 0.4 s would become Retry-After: 0, which means “retry now”. So the value is ⌈w⌉\lceil w \rceil and at least 1.

Key k has RPM 3 and TPM 1000, and the clock starts at t=0t = 0.

  1. A request reserves 300 tokens (prompt 60, max_tokens 240). The request bucket goes 3→23 \to 2 and the token bucket 1000→7001000 \to 700. The headers say remaining requests 2, remaining tokens 700, and reset-tokens =300/(1000/60)=18= 300 / (1000/60) = 18 s.
  2. It finishes having used 120 tokens. Settle refunds 300−120=180300 - 120 = 180, so the token bucket is 700+180=880700 + 180 = 880.
  3. Still at t=0t = 0, a request needs 900 tokens. Since 880<900880 < 900, it must wait w=(900−880)⋅60/1000=1.2w = (900 - 880) \cdot 60 / 1000 = 1.2 s. The answer is 429 with Retry-After: 2 and remaining tokens 880.
  4. At t=1.2t = 1.2 s the token bucket has refilled 1000⋅1.2/60=201000 \cdot 1.2 / 60 = 20 tokens to exactly 900, so the request is admitted and leaves 0. The request bucket has refilled 3⋅1.2/60=0.063 \cdot 1.2/60 = 0.06 to 2.06, and after this request holds 1.06: remaining requests 1.

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 = unlimited
type 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) *Limiter
func (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/tokenize
func PromptText(body []byte) string
func EstimateCost(ctx context.Context, counter Counter, req *server.Request) Cost
func SetHeaders(h http.Header, s Status)
func RetryAfterSeconds(d time.Duration) int
func Middleware(l *Limiter, counter Counter) server.Middleware

The 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.

The design follows from seven observations:

  1. 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.
  2. Refill can be computed lazily. Because refill is linear in time and capped, there is no need for a timer: on each decision, add ρ⋅Δt\rho \cdot \Delta t and cap at CC. That makes the bucket correct at whatever moments the clock is read, and lets a fake clock drive it exactly.
  3. 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.
  4. 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 without max_tokens pay.
  5. A reservation is a one-shot. Settle or Cancel, whichever comes first, wins; the other is a no-op. sync.Once is exactly that.
  6. A request larger than CC can never fit. Waiting for n>Cn > C 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.
  7. Time comes only from an injected clock. Then the hand example is reproducible to the nanosecond, and refill is testable without sleeping.

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)))
}

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
}

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
}

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 CC, 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).

Prompt tokens come from the engine’s tokenizer when it answers, otherwise from ⌈bytes/4⌉\lceil \text{bytes}/4 \rceil. 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 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} otherwise
res, err := l.Reserve(r.Context(), p.KeyID, Limits{RPM: p.RPM, TPM: p.TPM}, cost) // keyed by key, not tenant
var rej *RejectError
if 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 429
settled := false
defer func() {
if !settled {
res.Cancel() // a panic below: nothing ran to completion
}
}()
next.ServeHTTP(w, r)
st := ex.Snapshot() // the usage the proxy recorded
switch {
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 nothing
default:
res.Settle(Cost{Requests: 1}) // ran but produced no usage: the request counts, the tokens come back
}
settled = true

The 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.

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 rr gateway replicas and no stickiness, a key can get up to rr 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.

A correct solution must pass these checks:

CaseKind of checkChecksWhy it matters downstream
the hand exampleunitevery number: remaining counts, reset 18 s, the settle refund, RetryAfter 1.2 s and Retry-After 2, admission at 1.2 sone exact definition of the bucket
burst, then refillunit60 at once, the 61st waits 1 s, one per second after, 10 idle minutes bank only 60the burst limit in the load report
settle charges an overrununitreserve 100, use 700: the next 10 tokens wait 11 srequests without max_tokens cannot dodge TPM
cancel and settle count onceunitcancel returns everything; a second cancel and a cancel after settle do nothingno double refunds
zero means unlimitedboundarylimits of 0 never rejectthe admin API’s “0 = unlimited”
oversize cost rejectedboundary1001 tokens against TPM 1000 is rejected even when the bucket is full; 1000 fitsone request cannot exceed a minute’s budget
keys are independentunitkey a exhausted, key b untouchedthe noisy-neighbor drill
concurrent reserveproperty1000 goroutines, RPM 100: exactly 100 admitted, no data racecorrectness under load
Retry-After roundingboundary0, 1 ms, 1.2 s, 59 s, 59.001 sclients come back when the budget exists
the cost estimateunitprompt + max_tokens; max_completion_tokens wins; 256 default; bytes / 4 when the tokenizer failsreservations close to the truth
the prompt textunitprompt, chat contents, embeddings inputthe text that is tokenized
the tokenizer counterunitposts {model, text} to /v1/tokenize and counts the idsthe production counter
headers and the 429conformanceheaders on every 200; the third request at RPM 2 is 429 with Retry-After: 30 and the error shapethe contract’s ratelimit.429 behaviour
the middleware settles actual usageunitthe next response’s remaining tokens reflect the actual usage, not the estimateTPM tracks real cost
the middleware cancels on a 5xxunitafter a 503 without usage the one-request budget is backour outages are free
no principal passes throughboundaryno principal: no headers, no limitthe stage is safe before authentication is plugged in
buckets keyed by key idunittwo keys of one tenant have separate budgetsa 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 ⌈bytes/4⌉\lceil \text{bytes}/4 \rceil and adds MaxTokens or 256.

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 pieceProduction equivalentWhat it addsWhere to look
per-process bucketsEnvoy global rate limit service, Redis GCRAone budget shared by every gateway replicaEnvoy global rate limiting (free), GCRA (free)
reserve and settlesaige’s shared Budgetrequest, token, and cost capacity reserved under one lock and settled oncesaige budget package
two buckets per keyOpenAI and Anthropic API rate limitsper-model and per-organization tiers, daily capsOpenAI rate limits (free)
429 and Retry-Afterclient-side backoff with jitterclients that spread their retries instead of synchronizingAWS: Exponential backoff and jitter (free)
  • 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).
  • Token bucket: a counter capped at CC that refills at CC 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 - actual once 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.
  • A token bucket holds at most CC tokens and refills at CC 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-After in whole seconds rounded up, and every authenticated response carries the five x-ratelimit-* headers.
  • Exactly one of Settle and Cancel counts, 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.
  1. 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?
    AnswerThe 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.
  2. Why does Reserve compute the wait with min(c.Tokens, lim.TPM) and then reject c.Tokens > lim.TPM separately?
    AnswerWithout 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.
  3. A request reserves 300 tokens; the proxy panics before recording usage. What does the key get back, and which line makes that happen?
    AnswerEverything: 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.
  4. Why does a 5xx without usage cancel, while a 4xx without usage settles with one request?
    AnswerA 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.
  5. Why are buckets keyed by Principal.KeyID rather than by tenant?
    AnswerLimits 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.