Token-Based Rate Limiting for LLM APIs: Why Request-Count Limits Fail and How to Build Token-Aware Throttling A complete technical guide to token-based rate limiting for LLM APIs: why request-count limits fail, how token-aware throttling works, and… 2026-11-17T12:00:00.000Z Deep Dives Deep Dives deep-divereferencearchitecture

Token-Based Rate Limiting for LLM APIs: Why Request-Count Limits Fail and How to Build Token-Aware Throttling

A complete technical guide to token-based rate limiting for LLM APIs: why request-count limits fail, how token-aware throttling works, and…

The post you bookmark. One topic, covered end to end.

A complete technical guide to token-based rate limiting for LLM APIs: why request-count limits fail, how token-aware throttling works, and implementation patterns across API gateways.

Token-Based Rate Limiting for LLM APIs: Why Request-Count Limits Fail and How to Build Token-Aware Throttling

Traditional API rate limiting counts requests per second. LLM APIs break this model because a single request can consume anywhere from 50 tokens to 1,000,000+ tokens, with costs and compute requirements varying by four orders of magnitude. A rate limiter that treats a 100-token classification call the same as a 200K-token document analysis is not rate limiting — it’s guessing.

This post covers the mechanics of token-aware rate limiting: why it’s necessary, how the major providers implement it, the algorithms that work, and concrete implementation patterns for API gateways, proxy layers, and application code.

Table of Contents

The Problem with Request-Count Limits

A standard REST API serves requests with roughly uniform cost. A GET /users/123 and a GET /users/456 consume similar CPU, memory, and I/O. Rate limiting at 100 requests per second works because each request is approximately interchangeable.

LLM APIs violate this assumption in three ways:

Variable input size. A request with a 500-token prompt and a request with a 500,000-token prompt differ by 1000x in compute cost. The GPU time for prefill (processing the input through the transformer) scales roughly linearly with input length.

Variable output size. A request that generates 50 tokens and one that generates 16,000 tokens occupy the GPU for vastly different durations. Output generation is sequential — each token requires a forward pass — so longer outputs hold resources longer.

Cost asymmetry. Input tokens and output tokens are priced differently (typically 3-5x more for output), reflecting the different compute profiles. A rate limiter that ignores this bills users inaccurately and fails to protect backend resources.

Diagram

Request-count limiting works for uniform-cost APIs but breaks when request costs vary by orders of magnitude.

The practical failure mode: a user sends 10 requests per minute, each with 100K tokens of context. Another user sends 100 requests per minute, each with 200 tokens. Under request-count limiting, the second user looks like the heavier consumer. Under token-aware limiting, the first user is consuming ~50x more resources.

How LLM Providers Rate Limit Today

Every major LLM provider now enforces limits on both requests per minute (RPM) and tokens per minute (TPM). Some also limit tokens per day (TPD). The specific limits vary by model tier, pricing plan, and usage history.

ProviderDimensions EnforcedToken CountingNotable Behavior
OpenAIRPM + TPM + TPD (some tiers)Input + output combined for TPMTiered by usage level (1-5); higher spend = higher limits
AnthropicRPM + input TPM + output TPMInput and output tracked separatelySeparate input/output token budgets
Google (Gemini API)RPM + TPMCombined input + outputPer-model limits; Gemini 4 Argon has lower RPM than Flash models
DeepSeekRPM + TPMCombinedPeak vs off-peak pricing but same rate limits
xAI (Grok)RPM + TPMCombinedLimits vary by model; grok-4.7 has different limits than grok-4.6

The critical insight: providers enforce token limits because they must. GPU memory and compute are the actual bottlenecks, and tokens are the best proxy for resource consumption available at the API layer. If you’re building an API gateway or proxy that sits in front of these providers, you need the same kind of accounting.

Anthropic’s approach of tracking input and output tokens separately is worth noting. Input tokens are consumed during prefill (a parallelizable, relatively fast operation), while output tokens are generated autoregressively (sequential, slower, and each one occupies KV cache memory for the duration of generation). Treating them as a single pool conflates two different resource pressures.

Token Estimation Before the Request

To enforce token limits, you need to know (or estimate) token counts before the request reaches the LLM. For input tokens this is deterministic. For output tokens, it’s a prediction.

Input Token Counting

Input tokens can be counted exactly by running the provider’s tokenizer locally. The two dominant tokenizers in production:

tiktoken (OpenAI): Used by all GPT models. The o200k_base encoding covers GPT-4o and later models including GPT-6 Astra. Runs in ~1ms for typical prompts.

import tiktoken

enc = tiktoken.get_encoding("o200k_base")
tokens = enc.encode("Your prompt text here")
input_token_count = len(tokens)

Anthropic’s tokenizer: Claude 4.7 and later models use a tokenizer that emits approximately 30% more tokens for the same text compared to earlier Claude models. Anthropic provides a token counting API endpoint (/v1/messages/count_tokens) but no open-source tokenizer. For pre-request estimation, the common approach is to use a character-to-token ratio of roughly 3.5 characters per token for Claude 4.7+, versus ~4 characters per token for earlier models and OpenAI.

# Rough estimation for Claude models (4.7+)
def estimate_claude_tokens(text: str) -> int:
    return int(len(text) / 3.5)

# More accurate: use the count_tokens API
import anthropic
client = anthropic.Anthropic()
response = client.messages.count_tokens(
    model="claude-opus-5-5",
    messages=[{"role": "user", "content": text}]
)
exact_count = response.input_tokens

For Google’s Gemini models, the countTokens API endpoint provides exact counts. Locally, the SentencePiece tokenizer from the Gemini family gives reasonable estimates but isn’t guaranteed to match the production tokenizer exactly.

Diagram

Input tokens are counted exactly with a local tokenizer; output tokens must be estimated or bounded by max_tokens.

Output Token Estimation

Output token count is unknown before the request completes. Three strategies:

  1. Use max_tokens as the upper bound. If the request specifies max_tokens: 4096, reserve 4096 output tokens in the rate limiter. This overestimates but guarantees safety. The downside: a request that actually generates 200 tokens wastes 3896 tokens of budget.

  2. Use historical averages. Track the actual output token count per endpoint, user, or prompt template. If your summarization endpoint typically generates 300-500 tokens, estimate 500. This requires a feedback loop — the rate limiter must receive actual counts from completed requests and adjust.

  3. Reserve-then-reconcile. Reserve the max_tokens budget before the request, then credit back unused tokens after the request completes. This is the most accurate approach but requires tracking in-flight reservations.

The reserve-then-reconcile pattern is what most production systems converge on:

class TokenBudget:
    def __init__(self, max_tpm: int):
        self.max_tpm = max_tpm
        self.used = 0
        self.reserved = 0

    def try_reserve(self, input_tokens: int, max_output: int) -> bool:
        total_needed = input_tokens + max_output
        if self.used + self.reserved + total_needed > self.max_tpm:
            return False
        self.reserved += total_needed
        return True

    def reconcile(self, input_tokens: int, max_output: int, 
                  actual_output: int):
        # Release the reservation, record actual usage
        self.reserved -= (input_tokens + max_output)
        self.used += (input_tokens + actual_output)

The Token Bucket Algorithm, Adapted

The classic token bucket algorithm — not to be confused with LLM tokens — maps well to token-aware rate limiting with one modification: the “tokens” in the bucket represent LLM tokens rather than abstract permission units.

A standard token bucket has:

  • A capacity (maximum burst size)
  • A refill rate (tokens added per second)
  • A current level (available tokens)

For LLM rate limiting, set the capacity to the per-minute token limit and the refill rate to capacity / 60 tokens per second.

import time

class LLMTokenBucket:
    def __init__(self, tokens_per_minute: int):
        self.capacity = tokens_per_minute
        self.tokens = float(tokens_per_minute)
        self.refill_rate = tokens_per_minute / 60.0
        self.last_refill = time.monotonic()

    def _refill(self):
        now = time.monotonic()
        elapsed = now - self.last_refill
        self.tokens = min(
            self.capacity,
            self.tokens + elapsed * self.refill_rate
        )
        self.last_refill = now

    def try_consume(self, token_count: int) -> tuple[bool, float]:
        """Returns (allowed, wait_seconds_if_denied)."""
        self._refill()
        if self.tokens >= token_count:
            self.tokens -= token_count
            return True, 0.0
        else:
            deficit = token_count - self.tokens
            wait = deficit / self.refill_rate
            return False, wait
Diagram

Token bucket adapted for LLM tokens: the bucket’s capacity equals the TPM limit, and each request drains it by its estimated token count.

The advantage of token bucket over fixed-window counting: it handles bursts gracefully. A user can send a 50K-token request if they haven’t used much recently, even if the per-minute limit is 60K. Fixed-window counters reset at minute boundaries and create edge-case bursts at window transitions.

Sliding Window Token Counters

Sliding window counters avoid the boundary problem of fixed windows without the memory overhead of tracking every individual request. The approach: maintain counts for the current and previous window, then interpolate.

import time
from dataclasses import dataclass

@dataclass
class SlidingWindowCounter:
    window_size: int = 60  # seconds
    max_tokens: int = 100_000  # per window
    
    prev_count: int = 0
    curr_count: int = 0
    curr_window_start: float = 0.0
    
    def _get_weighted_count(self) -> float:
        now = time.monotonic()
        elapsed = now - self.curr_window_start
        
        if elapsed >= self.window_size:
            # Roll over
            self.prev_count = self.curr_count
            self.curr_count = 0
            self.curr_window_start = now
            elapsed = 0.0
        
        # Weight previous window by overlap
        prev_weight = 1.0 - (elapsed / self.window_size)
        return self.prev_count * prev_weight + self.curr_count
    
    def try_consume(self, tokens: int) -> bool:
        weighted = self._get_weighted_count()
        if weighted + tokens > self.max_tokens:
            return False
        self.curr_count += tokens
        return True

This provides smoother rate limiting than fixed windows at the cost of slightly more computation per check. For most LLM gateway workloads — where individual requests take hundreds of milliseconds to seconds — the overhead of a sliding window check is negligible.

Dual-Dimension Limiting: Tokens and Requests

Token limits alone are insufficient. A user could theoretically send millions of tiny requests (1 token each) that stay within the TPM budget but overwhelm connection handling, routing, and scheduling infrastructure. Conversely, request limits alone allow a few massive requests to monopolize GPU resources.

The correct approach: enforce both simultaneously. A request must pass both the RPM check and the TPM check.

Diagram

Both dimensions must pass: request-count limits protect connection infrastructure while token limits protect compute resources.

class DualLimiter:
    def __init__(self, rpm: int, tpm: int):
        self.request_bucket = LLMTokenBucket(rpm)  # reuse, 1 unit = 1 request
        self.token_bucket = LLMTokenBucket(tpm)

    def try_allow(self, estimated_tokens: int) -> tuple[bool, str]:
        req_ok, req_wait = self.request_bucket.try_consume(1)
        if not req_ok:
            return False, f"RPM exceeded. Retry in {req_wait:.1f}s"
        
        tok_ok, tok_wait = self.token_bucket.try_consume(estimated_tokens)
        if not tok_ok:
            # Refund the request count since we're denying
            self.request_bucket.tokens += 1
            return False, f"TPM exceeded. Retry in {tok_wait:.1f}s"
        
        return True, ""

Some providers add a third dimension — tokens per day (TPD) — for cost control. This prevents a user from burning through their entire monthly budget in an hour of heavy usage. TPD limits typically use a simple fixed-window counter that resets at midnight UTC.

Handling Output Tokens You Can’t Predict

The reserve-then-reconcile pattern described earlier works for systems where you control the rate limiter and receive response metadata. In a gateway or proxy architecture, the flow looks like this:

Diagram

The gateway reserves max_tokens before forwarding, then reconciles with actual usage from the response.

For streaming responses, the reconciliation happens when the stream ends. The usage object in the final chunk (or the stream_options.include_usage parameter in OpenAI’s API) provides exact token counts. Until the stream completes, the full max_tokens reservation stays in place.

This creates a problem for long-running generations. A request that generates 128K output tokens on GPT-6 Astra or Claude Fable 5.2 (both support 128K max output) might run for 60+ seconds. During that time, the reserved tokens are “locked,” reducing throughput for other requests. Three mitigations:

  1. Lower default max_tokens. If most requests need <4K output, set a lower default and require explicit opt-in for large outputs.

  2. Progressive reservation. Reserve an initial estimate (e.g., 2x the historical median output length), then extend the reservation if the stream exceeds it. This risks under-reservation but improves throughput.

  3. Separate budgets for in-flight and completed tokens. Track reserved-but-unspent tokens separately from consumed tokens, and use different thresholds. Allow total (consumed + reserved) to exceed the nominal limit by some factor (e.g., 1.2x) to account for overestimation.

Implementing Token-Aware Limiting in an API Gateway

A production gateway (Nginx, Envoy, Kong, or a custom proxy) needs token-aware limiting at the HTTP layer. The challenge: extracting token counts from the request body before making a routing decision.

Architecture

Diagram

Gateway architecture: extract token count from the request body, check rate limits, forward, and record actual usage on response.

Extracting Token Counts in Nginx/OpenResty

-- OpenResty Lua module for token estimation
local cjson = require "cjson"

local function estimate_tokens_from_body()
    ngx.req.read_body()
    local body = ngx.req.get_body_data()
    if not body then return 0, 0 end
    
    local ok, data = pcall(cjson.decode, body)
    if not ok then return 0, 0 end
    
    -- Count characters in messages, estimate tokens
    local char_count = 0
    if data.messages then
        for _, msg in ipairs(data.messages) do
            if type(msg.content) == "string" then
                char_count = char_count + #msg.content
            end
        end
    end
    
    -- ~4 chars per token for English text (adjust per model)
    local input_estimate = math.ceil(char_count / 4)
    local max_output = data.max_tokens or 4096
    
    return input_estimate, max_output
end

The character-counting approach is imprecise — tokenizer behavior varies by language, code vs prose, and special characters. For higher accuracy, embed a tokenizer (tiktoken has C bindings usable from Lua/C extensions) or call a sidecar token-counting service.

Kong Plugin Pattern

# kong.yml - token-aware rate limiting plugin config
plugins:
  - name: token-rate-limiting
    config:
      limits:
        - dimension: tokens_per_minute
          value: 100000
          window_size: 60
        - dimension: requests_per_minute
          value: 60
          window_size: 60
      token_estimation:
        method: char_ratio  # or "tiktoken" if binary available
        chars_per_token: 4.0
      output_estimation:
        method: max_tokens_field
        default_max_tokens: 4096
      storage: redis
      redis_host: redis.internal
      redis_port: 6379

No major API gateway ships a token-aware rate limiting plugin out of the box as of November 2026 — this is typically custom code. Kong and Envoy’s built-in rate limiting plugins count requests, not tokens. The common pattern is a custom plugin or filter that:

  1. Reads and parses the JSON request body
  2. Estimates input tokens
  3. Reads max_tokens from the request
  4. Checks combined token count against a Redis-backed counter
  5. On response, reads the usage object and reconciles

Distributed Token Counting

Single-process token buckets work for single-instance gateways. Multi-instance deployments need shared state. Redis is the standard choice.

Redis-Based Token Counter

import redis
import time

class DistributedTokenLimiter:
    def __init__(self, redis_url: str, key_prefix: str, 
                 tpm_limit: int):
        self.r = redis.from_url(redis_url)
        self.prefix = key_prefix
        self.tpm_limit = tpm_limit
        self.window = 60  # seconds

    def _window_key(self) -> str:
        window_id = int(time.time()) // self.window
        return f"{self.prefix}:{window_id}"

    def try_consume(self, tokens: int, 
                    entity_id: str) -> tuple[bool, int]:
        key = f"{self._window_key()}:{entity_id}"
        
        pipe = self.r.pipeline()
        pipe.incrby(key, tokens)
        pipe.expire(key, self.window * 2)  # TTL > window for safety
        results = pipe.execute()
        
        new_total = results[0]
        if new_total > self.tpm_limit:
            # Over limit — roll back
            self.r.decrby(key, tokens)
            remaining = self.tpm_limit - (new_total - tokens)
            return False, max(0, remaining)
        
        return True, self.tpm_limit - new_total

The increment-then-check pattern has a race condition: two concurrent requests might both increment past the limit before either rolls back. For strict enforcement, use a Lua script to make the check-and-increment atomic:

-- Redis Lua script for atomic token limiting
local key = KEYS[1]
local tokens = tonumber(ARGV[1])
local limit = tonumber(ARGV[2])
local ttl = tonumber(ARGV[3])

local current = tonumber(redis.call('GET', key) or '0')
if current + tokens > limit then
    return -1  -- denied
end

local new_total = redis.call('INCRBY', key, tokens)
if redis.call('TTL', key) == -1 then
    redis.call('EXPIRE', key, ttl)
end

return limit - new_total  -- remaining tokens
Diagram

Multiple gateway instances share token counts through Redis with atomic Lua scripts to prevent race conditions.

Sliding Window in Redis

For sliding window accuracy in a distributed setting, use a Redis sorted set where each entry’s score is its timestamp and value is its token count:

def sliding_window_check(self, entity_id: str, 
                         tokens: int) -> bool:
    key = f"tpm:{entity_id}"
    now = time.time()
    window_start = now - 60
    
    pipe = self.r.pipeline()
    # Remove entries outside the window
    pipe.zremrangebyscore(key, 0, window_start)
    # Sum all entries in the window
    pipe.zrangebyscore(key, window_start, now, withscores=True)
    results = pipe.execute()
    
    current_total = sum(
        int(member.decode()) for member, score in results[1]
    )
    
    if current_total + tokens > self.tpm_limit:
        return False
    
    # Add this request
    self.r.zadd(key, {str(tokens): now})
    self.r.expire(key, 120)
    return True

The tradeoff: sorted sets use more memory than simple counters (O(n) in the number of requests per window per user), but provide precise sliding window behavior. For high-throughput systems, the fixed-window approach with interpolation (described in the sliding window section above) uses O(1) memory per user.

Backpressure and Queuing Strategies

When the rate limit is reached, the system has three options: reject, queue, or shed load selectively.

Reject with Retry-After

The simplest approach. Return HTTP 429 with a Retry-After header indicating when the client should retry.

from fastapi import FastAPI, HTTPException, Response

app = FastAPI()

@app.post("/v1/chat/completions")
async def chat(request: ChatRequest, response: Response):
    allowed, wait_seconds = limiter.try_consume(
        estimated_tokens(request)
    )
    if not allowed:
        response.headers["Retry-After"] = str(int(wait_seconds) + 1)
        response.headers["X-RateLimit-Remaining-Tokens"] = "0"
        raise HTTPException(
            status_code=429,
            detail=f"Token limit exceeded. Retry in {wait_seconds:.0f}s"
        )
    # ... forward to provider

Priority Queuing

More sophisticated: queue requests by priority and process them as token budget becomes available.

Diagram

Priority queuing: classify requests by urgency, dequeue as token budget replenishes, process high-priority first.

import asyncio
import heapq
from dataclasses import dataclass, field

@dataclass(order=True)
class QueuedRequest:
    priority: int
    timestamp: float = field(compare=False)
    tokens_needed: int = field(compare=False)
    future: asyncio.Future = field(compare=False)

class TokenAwareQueue:
    def __init__(self, tpm_limit: int):
        self.bucket = LLMTokenBucket(tpm_limit)
        self.queue: list[QueuedRequest] = []
        self._running = True

    async def enqueue(self, tokens: int, priority: int = 5, 
                      timeout: float = 30.0) -> bool:
        future = asyncio.get_event_loop().create_future()
        entry = QueuedRequest(priority, time.monotonic(), 
                              tokens, future)
        heapq.heappush(self.queue, entry)
        
        try:
            return await asyncio.wait_for(future, timeout)
        except asyncio.TimeoutError:
            return False

    async def drain_loop(self):
        while self._running:
            if self.queue:
                entry = self.queue[0]
                allowed, wait = self.bucket.try_consume(
                    entry.tokens_needed
                )
                if allowed:
                    heapq.heappop(self.queue)
                    entry.future.set_result(True)
                else:
                    await asyncio.sleep(min(wait, 0.1))
            else:
                await asyncio.sleep(0.05)

Load Shedding

Under sustained overload, queuing just delays the inevitable. Load shedding drops low-priority requests entirely to preserve capacity for high-priority ones. The token-aware twist: shed requests that would consume the most tokens first, since they provide the best capacity recovery per dropped request.

Per-User and Per-Tenant Fairness

A multi-tenant LLM gateway needs to prevent any single user from consuming the entire token budget. Two patterns:

Hierarchical Token Budgets

Allocate a global TPM limit across tenants, then per-user within each tenant:

LevelBudgetShare of parent
Global1,000,000 TPM
Tenant A400,000 TPM40% of global
Tenant A: User A1100,000 TPM25% of Tenant A
Tenant A: User A2100,000 TPM25% of Tenant A
Tenant A: shared pool200,000 TPM50% of Tenant A
Tenant B300,000 TPM30% of global
Global shared pool300,000 TPM30% of global

The shared pool at each level handles burst capacity. When a user exhausts their individual budget, they can draw from the tenant’s shared pool. When the tenant’s shared pool is empty, requests wait or fail.

Weighted Fair Queuing

Borrowed from network scheduling: assign each tenant a weight proportional to their plan tier, then schedule requests such that token throughput matches the weight ratios over time.

class WeightedFairScheduler:
    def __init__(self, tenant_weights: dict[str, float]):
        self.weights = tenant_weights
        self.virtual_time = {t: 0.0 for t in tenant_weights}
    
    def next_tenant(self, ready_tenants: list[str]) -> str:
        # Pick the tenant with the lowest virtual time
        # (they've consumed the least relative to their weight)
        return min(
            ready_tenants,
            key=lambda t: self.virtual_time[t] / self.weights[t]
        )
    
    def record_usage(self, tenant: str, tokens: int):
        self.virtual_time[tenant] += tokens
Diagram

Weighted fair scheduling allocates token throughput proportionally to tenant weights, preventing any single tenant from starving others.

Provider-Side Rate Limit Headers

When your gateway forwards to an upstream LLM provider, the provider’s rate limit headers tell you how much capacity remains. Using this information avoids sending requests that will be rejected.

OpenAI Headers

x-ratelimit-limit-requests: 500
x-ratelimit-limit-tokens: 200000
x-ratelimit-remaining-requests: 487
x-ratelimit-remaining-tokens: 148231
x-ratelimit-reset-requests: 12s
x-ratelimit-reset-tokens: 7s

Anthropic Headers

anthropic-ratelimit-requests-limit: 1000
anthropic-ratelimit-requests-remaining: 950
anthropic-ratelimit-requests-reset: 2026-11-17T10:00:30Z
anthropic-ratelimit-input-tokens-limit: 400000
anthropic-ratelimit-input-tokens-remaining: 312000
anthropic-ratelimit-input-tokens-reset: 2026-11-17T10:00:45Z
anthropic-ratelimit-output-tokens-limit: 100000
anthropic-ratelimit-output-tokens-remaining: 87500
anthropic-ratelimit-output-tokens-reset: 2026-11-17T10:00:45Z

Anthropic’s separate input/output token tracking is visible in the headers — this is the most granular provider-side rate limit information available.

Using Provider Headers for Adaptive Throttling

class AdaptiveThrottler:
    def __init__(self):
        self.provider_remaining_tokens = float('inf')
        self.provider_reset_at = 0.0

    def update_from_headers(self, headers: dict):
        remaining = headers.get('x-ratelimit-remaining-tokens')
        reset = headers.get('x-ratelimit-reset-tokens')
        
        if remaining is not None:
            self.provider_remaining_tokens = int(remaining)
        if reset is not None:
            # Parse "12s" format
            self.provider_reset_at = (
                time.monotonic() + parse_duration(reset)
            )

    def should_throttle(self, tokens_needed: int) -> bool:
        if self.provider_remaining_tokens < tokens_needed:
            return True
        # Also throttle if we're below 10% of the limit
        # to leave headroom for concurrent requests
        if self.provider_remaining_tokens < tokens_needed * 10:
            return True
        return False
Diagram

The gateway reads provider-side rate limit headers and adjusts its local token budget accordingly, preventing 429s from the upstream provider.

The two-layer approach — your own rate limits plus tracking the provider’s — catches misconfigurations. If your gateway’s limit is set too high relative to the provider’s actual limit, the provider headers act as a safety net.

Retry Logic for Provider 429s

Even with proactive throttling, 429s happen. The retry strategy should be token-aware:

import random

async def retry_with_backoff(request, max_retries=3):
    for attempt in range(max_retries):
        response = await send_to_provider(request)
        
        if response.status_code != 429:
            return response
        
        retry_after = response.headers.get('retry-after')
        if retry_after:
            wait = float(retry_after)
        else:
            # Exponential backoff with jitter
            wait = min(2 ** attempt + random.uniform(0, 1), 60)
        
        # Update local limiter with provider's remaining capacity
        throttler.update_from_headers(response.headers)
        
        await asyncio.sleep(wait)
    
    raise RateLimitExceeded("Max retries exceeded")

The key addition: updating the local limiter from the 429 response headers. This prevents subsequent requests from hitting the same wall.

Token-Cost-Weighted Rate Limiting

A refinement for multi-model gateways: weight token consumption by cost rather than raw count. A GPT-6 Astra output token at $50/M costs 100x more than a GPT-6 Luna output token at $0.50/M. If the goal is cost control rather than resource protection, the limiter should track cost-equivalent tokens.

# Cost per million tokens (input, output)
MODEL_COSTS = {
    "gpt-6-astra":        (10.0, 50.0),
    "gpt-6.1-sol":        (2.0,  10.0),
    "gpt-6-luna":         (0.10, 0.50),
    "claude-opus-5-5":    (4.0,  20.0),
    "claude-sonnet-5-5":  (2.0,  10.0),
    "claude-haiku-5-5":   (0.10, 0.50),  # ≤100K input tier
}

class CostWeightedLimiter:
    def __init__(self, daily_budget_usd: float):
        self.daily_budget = daily_budget_usd
        self.spent_today = 0.0

    def estimate_cost(self, model: str, input_tokens: int, 
                      max_output: int) -> float:
        input_rate, output_rate = MODEL_COSTS.get(
            model, (10.0, 50.0)  # default to expensive
        )
        input_cost = (input_tokens / 1_000_000) * input_rate
        output_cost = (max_output / 1_000_000) * output_rate
        return input_cost + output_cost

    def try_allow(self, model: str, input_tokens: int, 
                  max_output: int) -> bool:
        cost = self.estimate_cost(model, input_tokens, max_output)
        if self.spent_today + cost > self.daily_budget:
            return False
        self.spent_today += cost
        return True

This is particularly useful for systems that route between models — a cost-weighted limiter naturally allows more cheap-model requests and fewer expensive-model requests within the same budget.

Monitoring and Alerting

Token-aware rate limiting produces metrics that request-count limiting doesn’t:

MetricWhat It Tells You
TPM utilization (%)How close to the limit you’re running
Average tokens per requestWhether request profiles are changing
Output token overestimation ratioHow much budget you’re wasting on reservations
429 rate by token bucket vs request bucketWhich dimension is the bottleneck
Token budget waste (reserved - actual)Efficiency of your output estimation
Queue depth (tokens)Backpressure in token-equivalent terms
Diagram

Instrument the token limiter to export utilization, rejection rates, and estimation accuracy metrics.

The output token overestimation ratio is the most actionable metric. If the ratio is consistently high (e.g., reserving 4096 tokens but averaging 400 actual output tokens), reduce the default max_tokens or switch to historical-average estimation.

Summary

Token-aware rate limiting replaces the uniform-cost assumption of traditional rate limiting with an accounting model that reflects actual LLM resource consumption. The core pattern:

  • Count input tokens exactly using the provider’s tokenizer (tiktoken for OpenAI, character estimation or the count_tokens API for Anthropic).
  • Estimate output tokens using max_tokens as an upper bound, then reconcile with actual usage after the response completes.
  • Enforce dual dimensions — both RPM and TPM — because they protect different resources (connection infrastructure vs GPU compute).
  • Use token bucket or sliding window algorithms adapted to count LLM tokens instead of abstract units.
  • Distribute state through Redis with atomic Lua scripts to prevent race conditions across gateway instances.
  • Read provider rate limit headers and feed them back into local limiters for adaptive throttling.
  • Implement per-tenant fairness through hierarchical budgets or weighted fair queuing.
  • Monitor estimation accuracy — the gap between reserved and actual output tokens is the main source of wasted capacity.

Request-count limiting was designed for a world where every request costs roughly the same. LLM workloads operate in a world where costs vary by four orders of magnitude. Token-aware limiting is not an optimization — it’s the minimum viable approach.

Further Reading