Pidoku

Abuse Prevention, Rate Limiting, and Quotas

Module 23 Lesson 23.j 1h Difficulty 3/5

Prerequisites 23.i, 20.c, 21.f


Before you start: words you need#

WordPlain meaning
Rate limitA cap on how fast a caller may use the service (“60,000 tokens per minute”).
QuotaA caller’s allowance of a resource over a period, or held at one time. Rate limits enforce quotas.
Token bucketA counter that refills at a steady rate up to a maximum; each request takes from it, and an empty bucket means “wait”.
Weighted tokensInput, cached input and output tokens added up with different prices, so one number reflects real cost (23.c).
KV blocks in flightThe KV-cache memory a caller’s running requests hold right now (17.e). The resource that actually runs out.
429 / 503HTTP “too many requests” (this caller is over its quota) and “service unavailable” (the service is full).
Retry-AfterA response header telling the client how many seconds to wait before trying again.
DistillationTraining a copy of a model on another model’s outputs. Heavy, systematic API use is how it is done.

1. What is it?#

Per-caller limits on an LLM service, expressed in the resources that are actually scarce, plus the detection and response for callers who abuse them. This lesson builds the gateway limiter: what to count, when to charge, where to enforce, and what to tell the client.

Neighbouring lessons own the rest. Quota models (reserved plus burst, credits) and fair queueing between tenants under contention are in 21.f; the engine’s own admission control is in 20.c and 16.e; the threat model behind abuse is 23.i; and cost per token, which sets the weights, is 23.c.

Facts checked on 13 November 2026 (vLLM v0.32.0, provider rate-limit documentation, the IETF RateLimit header draft).


2. Why does it matter?#

Requests are the wrong unit:

"1,000 requests per minute" allows:

  Tenant A: 1,000 requests × (50 input + 100 output) tokens       =     150,000 tokens/min
  Tenant B: 1,000 requests × (100,000 input + 4,000 output) tokens = 104,000,000 tokens/min

  Same limit, 693× the consumption.

And tokens per minute are not enough either. A tenant sending a few 100k-token prompts has a modest token rate but holds most of the KV cache while they run, so everyone else waits. A limiter must count the thing that runs out, and on an LLM server that is KV memory held at the same time.


3. Simple analogy#

A car park. Counting cars through the gate per hour (requests per minute) does not stop one coach parking across twelve spaces all afternoon. Charging by distance driven (tokens) does not help either. What protects the other drivers is a limit on spaces held at once per company, with the gate checking it before the vehicle comes in.


4. Tiny example: four limiters, one replica#

Two tenants share one replica with 20,000 KV blocks (320,000 tokens). chat sends 3 requests a second of 1,000 prompt tokens; docs sends one request every 5 seconds with a 100,000-token prompt. Each gets the same limit. The program in section 6 simulates 10 minutes:

policy                         who     sent  rejected   p95 wait   KV held
300 requests/min each          chat    1800         0     77.9 s        5%
300 requests/min each          docs     120         0     81.1 s       92%
3M weighted tokens/min each    chat    1800         0     77.9 s        5%
3M weighted tokens/min each    docs     120         0     81.1 s       92%
3M tokens/min + 4 in flight    chat    1800      1395      1.6 s        1%
3M tokens/min + 4 in flight    docs     120        17      6.1 s       92%
3M tokens/min + 40% KV cap     chat    1800         0      0.0 s        6%
3M tokens/min + 40% KV cap     docs     120        90      0.0 s       27%
  • Requests per minute and tokens per minute never trigger: both tenants are inside their limits. Yet docs holds 92% of the cache and chat’s p95 wait for admission is 78 seconds.
  • “4 requests in flight” is a concurrency limit in the wrong unit: it rejects most of chat’s small requests (chat needs about 15 at once) and still lets docs fill the cache.
  • A cap on KV blocks in flight protects chat completely. Docs is told no, with a 429, whenever it already holds its share; in practice its long-context work belongs in its own pool (21.g) or in a batch queue.

5. Technical explanation#

Three dimensions to limit#

1. KV OCCUPANCY (memory held now)       blocks reserved by in-flight requests
   → what denies capacity to others; check it first

2. TOKEN RATE (throughput over time)    weighted tokens per minute
   → what costs money; the published limit

3. REQUEST RATE (overhead)              requests per minute
   → bounds gateway, tokenizer and scheduler work; a secondary limit

Count KV in blocks the request could reach: ceil((prompt + max_tokens) / block_size), with block size 16 for a standard model (17.e). The gateway knows the prompt length after tokenizing and the max_tokens from the request; it does not need the engine’s live state to enforce a per-tenant share. A tenant with no max_tokens gets the server’s default, which is why an explicit cap matters.

Weighting tokens#

One weighted number lets one bucket stand for cost:

weighted = uncached_input × w_in + cached_input × w_cached + output × w_out

w_in = 1, w_out ≈ 5, w_cached ≈ 0.1–0.25

The output weight comes from the cost model: in 23.c an output token costs about 6× an input token on GPU time, and November 2026 price lists charge 3–8× (23.c). Cached input is cheap because prefill is skipped. Two published examples:

  • Anthropic limits input tokens and output tokens per minute separately, and cache reads do not count towards the input limit, which rewards callers for caching.
  • OpenAI limits requests and tokens per minute (and per day for some tiers).

When to charge: reserve, or count as you go#

The output length is unknown at admission. There are two designs, and the two big providers chose differently:

RESERVE AND REFUND                         COUNT AS PRODUCED
charge prompt + max_tokens at admission    charge output tokens as they stream
refund the unused part at the end          max_tokens costs nothing
OpenAI: counts max(max_tokens, estimate)   Anthropic: output limit "evaluated in real
                                           time"; max_tokens does not factor in
+ a burst can never overshoot              + no penalty for generous max_tokens
- callers who set huge max_tokens are      - many long streams can start together
  throttled early; they learn to set it      and overshoot; needs a concurrency or
  close to the expected length               KV limit beside it

Either works if a KV limit sits beside it. Reserve-and-refund is simpler to make safe in your own gateway, which is what section 6 does.

Where to enforce#

LAYER                  ENFORCES                               REPLY
CDN / WAF              gross abuse, IP reputation, body size   403 / 413
API gateway (21.i)     per-key token, KV and request limits    429 + Retry-After
Router / flow control  per-tenant fairness under contention   queue, then 429 (21.f)
Engine admission       "the server is full"                   503 + Retry-After (20.c)

Reject as early as possible: a rejection at the edge costs nothing, while one at the engine has already paid for tokenizing and routing. But the engine is the only layer that knows its real state, so it must be able to refuse too. vLLM v0.32.0 can bound its own queue with max_num_queued_reqs and max_num_queued_tokens (16.e); refusals answer 503 and are counted in vllm:admission_rejections_total (22.j). Keep the codes distinct: 429 means “you are over your quota”, 503 means “we are full, try elsewhere or later” (20.c). Clients and routers react to them differently.

Running it on many gateways#

A fleet has many gateway replicas, so the counters must be shared:

  • A central store (Redis, or Envoy’s global rate-limit service) is exact but adds a network round trip to every request and is a dependency. Decide what happens when it is down: fail open with a local fallback limit for rate limits, so a cache blip is not an outage (23.e).
  • Local buckets with a share each (limit ÷ number of gateways) need no store but are unfair when traffic is unevenly spread. Many systems combine them: local buckets that sync with the store every few hundred milliseconds.
  • KV-in-flight must be released reliably. Count it with an expiry (a lease), so a gateway that crashes mid-request does not leak a tenant’s allowance forever.

Off-the-shelf options exist: Envoy AI Gateway’s usage-based rate limiting counts input, cached input, output and total tokens (or a CEL expression of them) from the model’s reported usage, and LiteLLM’s proxy enforces per-key tokens per minute, requests per minute and parallel-request limits. Check whether a product can limit concurrent KV; most limit tokens and requests only.

Quota design#

WINDOWS
  per second     the token bucket that does the enforcing (smooth)
  per minute     the published limit users understand
  per day/month  billing and credit; needs persistent state
  ramp limit     how fast usage may grow; stops a new key going 0 → max at once

KINDS
  hard           reject when exceeded
  soft           admit, but at lower priority (21.f, 20.k)
  burst          short allowance above the sustained rate
  credit         a pre-paid budget drawn down over time

Publish per minute, enforce per second. “60,000 tokens per minute” enforced as a bucket refilling 1,000 per second with a capacity of a few seconds’ worth stops a caller spending the whole minute in the first second. Anthropic documents both a token bucket and a ramp limit that caps how quickly an organisation’s usage may grow after a quiet period.

Telling the client#

HTTP/1.1 429 Too Many Requests
Retry-After: 4
x-ratelimit-limit-tokens: 60000
x-ratelimit-remaining-tokens: 0
x-ratelimit-reset-tokens: 4s
x-ratelimit-limit-requests: 500
x-ratelimit-remaining-requests: 143

{"error": {"type": "rate_limit_error",
           "code": "token_rate_limit",
           "message": "Over 60000 tokens/min. Retry in 4 s."}}

Retry-After makes clients back off instead of hammering; the remaining-and-reset headers let good clients slow down before they hit the wall; a machine-readable code tells them which limit. There is no single standard yet. The x-ratelimit-* names above are OpenAI’s (reset as a duration like 6m0s); Anthropic uses anthropic-ratelimit-input-tokens-remaining and similar, with reset times in RFC 3339. The IETF draft (RateLimit-Policy and RateLimit fields, draft -11, May 2026) is still a draft. Most OpenAI-compatible clients understand the x-ratelimit-* form, so it is a safe choice.

Detecting abuse#

SIGNAL                                          OFTEN MEANS
cost per key far above its tier's normal        abuse, or a runaway client loop
many keys from one account or payment method    limit evasion
near-identical prompts at high volume           scraping or distillation
systematic coverage of a topic or input space   distillation
steady requests for top logprobs                extraction (23.i)
many 429s or 4xx validation errors in a row     probing the limits
perfectly regular timing, round the clock       automation (fine, if declared)
requests that crash or stall the engine         attack, or a client bug (23.i)

RESPONSES, ESCALATING
  1. log and watch          4. soft ban: admit at the lowest priority
  2. tighten that key       5. hard ban
  3. add friction (verification in the application)

Distillation detection is hard and the signal is weak: a legitimate heavy user looks similar. Watch cost per key against its tier, look at the outliers by hand, and rely on terms of service for enforcement. The per-request record of 23.h (tenant, key, tokens, kv_block_seconds) is the data for all of these.


6. Under the hood: the limiter in a simulation#

The program behind section 4. The gateway checks request rate, a weighted-token bucket charged for max_tokens (refunded when the request finishes), requests in flight, or KV blocks in flight; the engine admits in arrival order while blocks are free.

Go
// quotas.go — four ways to limit two tenants sharing one replica's KV cache.
// Tenant "chat" sends many short requests; tenant "docs" sends a few huge ones.
package main

import (
	"fmt"
	"sort"
)

const (
	dt         = 0.1    // simulation step, seconds
	duration   = 600.0  // seconds simulated
	kvBlocks   = 20000  // replica KV capacity, 16-token blocks (320k tokens)
	prefillTPS = 20000. // prompt tokens per second, per request
	decodeTPS  = 40.    // output tokens per second, per stream
	wOut       = 5.     // weight of an output token vs an input token (23.c)
)

type tenant struct {
	name           string
	perSec         float64 // arrival rate
	prompt, maxOut int     // request shape
	actualOut      int     // what it really generates
	bucket, refill float64 // weighted-token bucket: level and refill per second
	bucketCap      float64
	kvHeld, kvCap  int // gateway's count of KV blocks in flight, and the cap
	inFlight       int
	sent, rejected int
	waits          []float64
	blockSecs      float64
	arrivalAccum   float64
}

type req struct {
	t                *tenant
	arrived, doneAt  float64
	blocks, reserved int
	reservedW        float64
}

type policy struct {
	name        string
	reqPerMin   float64 // 0 = off
	tokPerMin   float64 // weighted tokens per minute, 0 = off
	kvShare     float64 // max share of KV per tenant, 0 = off
	maxInFlight int     // max concurrent requests per tenant, 0 = off
}

func blocksFor(tokens int) int { return (tokens + 15) / 16 }

func run(p policy) []*tenant {
	ts := []*tenant{
		{name: "chat", perSec: 3, prompt: 1000, maxOut: 1000, actualOut: 200},
		{name: "docs", perSec: 0.2, prompt: 100000, maxOut: 1000, actualOut: 500},
	}
	reqBucket := map[*tenant]float64{}
	for _, t := range ts {
		if p.tokPerMin > 0 {
			t.bucketCap, t.refill, t.bucket = p.tokPerMin, p.tokPerMin/60, p.tokPerMin
		}
		if p.kvShare > 0 {
			t.kvCap = int(p.kvShare * kvBlocks)
		}
		reqBucket[t] = p.reqPerMin
	}
	var queue, running []*req
	free := kvBlocks
	for now := 0.0; now < duration; now += dt {
		// 1. arrivals pass the gateway's limits, or get a 429
		for _, t := range ts {
			t.arrivalAccum += t.perSec * dt
			if p.reqPerMin > 0 {
				reqBucket[t] = min(p.reqPerMin, reqBucket[t]+p.reqPerMin/60*dt)
			}
			if p.tokPerMin > 0 {
				t.bucket = min(t.bucketCap, t.bucket+t.refill*dt)
			}
			for ; t.arrivalAccum >= 1; t.arrivalAccum-- {
				t.sent++
				r := &req{t: t, arrived: now, blocks: blocksFor(t.prompt + t.actualOut),
					reserved: blocksFor(t.prompt + t.maxOut)}
				r.reservedW = float64(t.prompt) + wOut*float64(t.maxOut) // charge max_tokens now
				switch {
				case p.reqPerMin > 0 && reqBucket[t] < 1,
					p.tokPerMin > 0 && t.bucket < r.reservedW,
					p.kvShare > 0 && t.kvHeld+r.reserved > t.kvCap,
					p.maxInFlight > 0 && t.inFlight >= p.maxInFlight:
					t.rejected++
					continue
				}
				if p.reqPerMin > 0 {
					reqBucket[t]--
				}
				if p.tokPerMin > 0 {
					t.bucket -= r.reservedW
				}
				t.kvHeld += r.reserved
				t.inFlight++
				queue = append(queue, r)
			}
		}
		// 2. finished requests free their blocks; refund unused output tokens
		keep := running[:0]
		for _, r := range running {
			if now >= r.doneAt {
				free += r.blocks
				r.t.kvHeld -= r.reserved
				r.t.inFlight--
				if p.tokPerMin > 0 {
					r.t.bucket = min(r.t.bucketCap, r.t.bucket+wOut*float64(r.t.maxOut-r.t.actualOut))
				}
				continue
			}
			r.t.blockSecs += float64(r.blocks) * dt
			keep = append(keep, r)
		}
		running = keep
		// 3. the engine admits in arrival order while KV blocks are free
		for len(queue) > 0 && queue[0].blocks <= free {
			r := queue[0]
			queue = queue[1:]
			free -= r.blocks
			r.t.waits = append(r.t.waits, now-r.arrived)
			r.doneAt = now + float64(r.t.prompt)/prefillTPS + float64(r.t.actualOut)/decodeTPS
			running = append(running, r)
		}
	}
	return ts
}

func p95(xs []float64) float64 {
	if len(xs) == 0 {
		return 0
	}
	s := append([]float64(nil), xs...)
	sort.Float64s(s)
	return s[len(s)*95/100]
}

func main() {
	fmt.Printf("%-30s %-5s %6s %9s %10s %9s\n", "policy", "who", "sent", "rejected", "p95 wait", "KV held")
	for _, p := range []policy{
		{name: "300 requests/min each", reqPerMin: 300},
		{name: "3M weighted tokens/min each", tokPerMin: 3e6},
		{name: "3M tokens/min + 4 in flight", tokPerMin: 3e6, maxInFlight: 4},
		{name: "3M tokens/min + 40% KV cap", tokPerMin: 3e6, kvShare: 0.4},
	} {
		ts := run(p)
		for _, t := range ts {
			fmt.Printf("%-30s %-5s %6d %9d %8.1f s %8.0f%%\n", p.name, t.name, t.sent, t.rejected,
				p95(t.waits), 100*t.blockSecs/(kvBlocks*duration))
		}
	}
}

Output:

policy                         who     sent  rejected   p95 wait   KV held
300 requests/min each          chat    1800         0     77.9 s        5%
300 requests/min each          docs     120         0     81.1 s       92%
3M weighted tokens/min each    chat    1800         0     77.9 s        5%
3M weighted tokens/min each    docs     120         0     81.1 s       92%
3M tokens/min + 4 in flight    chat    1800      1395      1.6 s        1%
3M tokens/min + 4 in flight    docs     120        17      6.1 s       92%
3M tokens/min + 40% KV cap     chat    1800         0      0.0 s        6%
3M tokens/min + 40% KV cap     docs     120        90      0.0 s       27%

Three details matter in a real gateway. The KV estimate uses max_tokens, so it over-reserves for short answers; that is the safe side, and releasing the reservation at the end returns it. The refund happens on every ending, including client disconnects and errors, or the bucket drains for no reason. And the cap is a share of the replica pool the tenant is routed to, not of one replica, so the gateway needs the pool’s size.


7. Performance implications#

  • The limiter is on the hot path. A central store adds a round trip (often around a millisecond in one zone) to every request; batch the updates or use local buckets that sync.
  • Counting tokens means tokenizing at the gateway. That is CPU, and the gateway’s count must match the engine’s: use the same tokenizer and chat template (16.e).
  • KV caps raise goodput. In section 4 the KV cap took chat’s p95 admission wait from 78 s to zero without touching throughput for anyone within their share.
  • Over-reservation lowers utilisation. Reserving for max_tokens holds allowance a request never uses; a caller that sets max_tokens near its real length gets more in.

8. Production implications#

  • Limit KV in flight, weighted tokens, and requests, in that order of importance.
  • Weight output and cached input by real cost (23.c), and publish the weights.
  • Choose reserve-and-refund or count-as-produced, and pair either with a KV limit.
  • Refund on every ending, and lease KV reservations so crashes do not leak them.
  • 429 with Retry-After and remaining headers for quota; 503 for “full”.
  • Fail open, with a local fallback limit, when the shared limiter store is down.
  • Watch cost per key and alert on outliers; keep the per-request records (23.h).
  • Send long-context and bulk tenants to their own pool or a batch queue rather than only rejecting them.
  • Publish your limits, so clients can design around them.

9. Common mistakes#

  1. Request-based limits only. 693× spread in real consumption.
  2. Token limits only. A few long-context requests hold the whole cache.
  3. Concurrency counted in requests. Punishes many small requests, barely touches a few huge ones.
  4. Charging only for output already produced, with no KV or concurrency cap. Many long streams start at once.
  5. Forgetting the refund on errors and disconnects. Buckets drain on their own.
  6. No Retry-After. Clients retry at once and make it worse.
  7. 429 for “the server is full”. Clients back off their quota instead of trying another region.
  8. A fail-closed limiter. A Redis blip rejects everyone (23.e).
  9. Quotas without fair queueing. Tenants within quota still starve each other under contention (21.f).
  10. Discovering abuse from the bill. No cost-per-key monitoring.

10. Hands-on exercise#

  1. Run quotas.go. Change docs’ prompt to 30,000 tokens and its rate to 1 per second. Which policies still protect chat? What KV share would you give docs?
  2. Change the KV cap to 60% and 20%. Plot chat’s p95 wait and docs’ rejections against the cap.
  3. Replace reserve-and-refund with count-as-produced (charge output tokens when the request ends). With no KV cap, what happens when docs sends 20 requests at once?
  4. Add a “chat-burst” tenant that sends 30 requests in one second every minute. Give the token bucket a capacity of 5 seconds’ refill and compare with 60 seconds'.
  5. Write the 429 response for your limiter with the x-ratelimit-* headers, and a client that slows down when remaining falls below 10%. How many 429s does it avoid?
  6. From a week of per-request records, compute weighted tokens per key. Which keys are more than 10× the median of their tier, and why?

11. Interview questions#

  1. Why is request-based rate limiting wrong for LLM services? Put a number on it.
  2. Why are token-rate limits not enough? What should the concurrency limit be counted in?
  3. Compare reserving max_tokens at admission with counting output as it is produced. What must accompany each?
  4. Where would you enforce limits, and what status code does each layer return?
  5. How do you run a limiter across many gateway replicas, and what happens when its store is down?
  6. What should a 429 response contain?
  7. How would you notice a tenant distilling your model, and what would you do?

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in