Rate limiting: algorithms, HTTP 429, headers, and LLM API limits

Explainer · Gateways

Rate limiting is a control that caps how many requests, or units of work such as tokens, a client can send to a service in a time window, and rejects or delays the rest. A client over the limit usually receives HTTP 429 Too Many Requests. This explainer, part of the AI gateways and LLM routing hub, covers the common algorithms, the 429 status code and its headers, retries, and how LLM providers meter requests and tokens.

What is rate limiting?#

Rate limiting is a server-side policy that counts each client's requests or work over a time window and refuses the excess until capacity returns. A rate limiter enforces that policy on the request path, and every limit comes down to three choices:

  • Key: who is counted, such as an API key, user, organization, project, or IP address.
  • Unit: what a request costs, such as one request, a number of tokens, bytes, or a concurrency slot.
  • Window: the period counted, such as one second, one minute, or one day.

Rate limiting vs throttling vs quotas#

Rate limiting rejects requests above a short-term cap, throttling delays them, and a quota caps total use over a long period. Vendors use the three words loosely.

Control Excess traffic is Example
Rate limit Rejected, usually with 429 100 requests per minute per API key
Throttle Delayed or queued, then served NGINX limit_req delaying requests above its rate
Quota Rejected until a long period resets Anthropic's monthly spend cap, which pauses usage until the next month

Why services use rate limiting#

Services use rate limiting to protect capacity, share it fairly, and enforce commercial plans. The IETF's RateLimit header fields draft gives the same reasons: avoiding overload, distributing resources equitably, and enforcing policies such as monetization. Abuse resistance and cost control matter too, especially on login endpoints and LLM traffic.

  • Overload: one client's spike cannot consume the threads, connections, or GPU time other clients depend on.
  • Fairness: one customer, batch job, or runaway agent loop cannot drain a shared pool.
  • Abuse: a low per-account limit on login and password-reset endpoints slows password guessing.
  • Cost: each LLM call has a per-token price, and Anthropic says its limits exist partly to reduce unintentional overspend.

Rate limiting is not access control. As the draft notes, advertising a limit does not stop a client from sending requests, so servers still need authentication and overload protection.

Rate limiting algorithms#

Five rate limiting algorithms cover most implementations: the fixed window counter, the sliding window log, the sliding window counter, the token bucket, and the leaky bucket. They trade memory per key against precision, and they differ most in how they treat bursts, which is usually what decides between them.

Fixed window counter#

A fixed window counter keeps one integer per key for each clock window and resets it to zero when the window ends. It is cheap and makes the reset time easy to publish, which suits daily and monthly quotas.

The flaw is the boundary. With a limit of 60 requests per minute, a client can send 60 requests in the last two seconds of one minute and 60 in the first two seconds of the next. Each window sees 60, so the limiter admits 120 within four seconds.

Timeline of a fixed window counter with a limit of 60 per minute: bursts of 60 just before and just after the reset are both allowed, putting 120 requests inside one rolling minute. 0s30s60s90s120sWindow 1, limit 60Burst A: 60 requestsallowed, count 60Window 2, limit 60Burst B: 60 requestsallowed, count resetRolling minute, 2 s to 62 s120 requests, 2x the limitCounter resets
Figure 1: A fixed window counter resets at the window boundary, so a client that bursts on both sides of the reset gets twice the limit within one rolling minute.

Sliding window log#

A sliding window log stores a timestamp for every accepted request and counts the timestamps inside the rolling window, so the count is exact and there is no boundary spike. Memory grows with the limit, which makes the log a fit for small, strict limits such as five login attempts per 15 minutes.

Sliding window counter#

A sliding window counter estimates the rolling count from two fixed windows: the current window's count plus the previous window's count, weighted by how much of that window still overlaps. With a limit of 100 per minute, 80 requests in the previous minute, and 30 in a current minute that began 20 seconds ago:

estimate = 80 × (60 - 20) / 60 + 30 = 83.3 requests

The estimate is under 100, so the request passes. It assumes the previous minute's traffic arrived evenly, but it needs only two integers per key, which suits per-user limits shared across many servers.

Token bucket#

A token bucket holds up to a fixed number of tokens, refills at a steady rate, and spends tokens on each request, rejecting requests that find too few. Capacity sets the largest burst, and the refill rate sets sustained throughput. Anthropic's Claude API uses a token bucket, so capacity refills continuously instead of resetting on a schedule.

import time
 
class TokenBucket:
    """Refills `rate` tokens per second, up to `capacity` tokens."""
 
    def __init__(self, rate: float, capacity: float):
        self.rate = rate
        self.capacity = capacity
        self.tokens = capacity
        self.last = time.monotonic()
 
    def try_take(self, cost: float = 1.0) -> bool:
        now = time.monotonic()
        self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
        self.last = now
        if self.tokens < cost:
            return False
        self.tokens -= cost
        return True
 
# Sustained 5 requests per second, bursts of up to 20.
limiter = TokenBucket(rate=5, capacity=20)

The cost argument fits LLM traffic, where one request can spend thousands of tokens of quota.

Leaky bucket#

A leaky bucket queues incoming requests, drains the queue at a constant rate, and rejects arrivals once it is full, so output stays smooth however bursty the input. The NGINX limit_req module limits requests with this method:

limit_req_zone $binary_remote_addr zone=perip:10m rate=10r/s;
 
server {
    location /api/ {
        limit_req zone=perip burst=20;
        limit_req_status 429;
    }
}

This allows an average of 10 requests per second per IP address. NGINX delays excess requests and rejects them once more than 20 are waiting, with a 503 unless limit_req_status sets another code.

Comparing the algorithms#

Algorithm State per key Bursts Accuracy Good fit
Fixed window counter One counter Up to 2x the limit at a boundary Exact per window only Quotas with a published reset
Sliding window log One timestamp per request None beyond the limit Exact Small, strict limits
Sliding window counter Two counters Smoothed Approximate Per-user limits across servers
Token bucket Token count and refill time Up to bucket capacity Exact Public APIs with bursty clients
Leaky bucket Queue and drain rate Absorbed by the queue Exact output rate Backends that need steady input

HTTP 429 Too Many Requests#

HTTP 429 Too Many Requests is the status code for a client that has sent too many requests in a given amount of time. RFC 6585 defined it in April 2012: the response should explain the condition, may include Retry-After, and must not be stored by a cache. The RFC leaves user identification and request counting to each server.

The IETF draft defines a quota-exceeded problem type that tells the client which policy it violated:

HTTP/1.1 429 Too Many Requests
Content-Type: application/problem+json
Retry-After: 30
 
{
  "type": "https://iana.org/assignments/http-problem-types#quota-exceeded",
  "title": "Per-minute request quota exceeded",
  "violated-policies": ["per-minute"]
}

Limits do not always arrive as a 429. The draft notes that servers also answer with 403 or drop connections, and NGINX defaults to 503, which signals that the server itself is temporarily overloaded or down rather than that one client sent too much. Some providers also use 429 for an exhausted monthly quota, which waiting does not fix.

Rate limit headers#

Rate limit headers report how much quota remains and when it returns, so a client can slow down before it receives a 429. Three kinds are in use: Retry-After, which HTTP standardizes; vendor X-RateLimit-* headers, which differ from one API to the next; and the IETF's draft RateLimit fields, which aim to replace them.

Retry-After#

RFC 9110, section 10.2.3 defines Retry-After as either a number of seconds or an HTTP date:

Retry-After: 120
Retry-After: Fri, 31 Dec 1999 23:59:59 GMT

RFC 6585 makes the header optional on a 429, so parse both forms and handle responses that carry neither.

X-RateLimit headers#

No standard defines X-RateLimit-Limit, X-RateLimit-Remaining, or X-RateLimit-Reset. The IETF draft's survey found the same names carrying seconds, milliseconds, Unix timestamps, or dates. LLM providers each use their own scheme, as of November 2026:

Source Remaining-quota header Reset format
OpenAI x-ratelimit-remaining-requests, x-ratelimit-remaining-tokens Duration, such as 6m0s
Anthropic anthropic-ratelimit-requests-remaining, plus token variants RFC 3339 timestamp
IETF draft RateLimit: "default";a=50;w=30 Seconds in the effective window

Write one small parser per provider rather than a generic reader that guesses.

The IETF RateLimit header fields#

The IETF HTTPAPI working group's draft defines RateLimit-Policy for the quota a server applies and RateLimit for what remains. Version 12, dated November 20, 2026, also defines RateLimit-Partition to describe how quota is split, and the document was still an Internet-Draft as of November 2026. An example from it:

HTTP/1.1 200 OK
Content-Type: application/json
RateLimit: "fixedwindow";a=99;w=50
RateLimit-Policy: "fixedwindow";q=100;w=60

The policy grants a quota (q) of 100 requests per 60-second window (w), and 99 remain (a) within an effective window of 50 seconds. Units default to requests, with content-bytes and concurrent-requests also defined. Two of the draft's client rules are worth adopting now: Retry-After takes precedence when both fields appear, and a positive available quota is a hint, not a guarantee.

How to handle a 429: retries with backoff and jitter#

Handle a 429 by waiting and then resending the same request: honor Retry-After when the server sends it, fall back to capped exponential backoff with jitter when it does not, and stop after a fixed number of attempts. First check whether the 429 reports an exhausted quota, because then no amount of waiting helps.

Decision flow for a 429: stop if the body reports an exhausted quota, return the error if no attempts remain, otherwise wait for Retry-After or a jittered backoff and resend. 429 receivedRead the error bodyquota or spend cap used up?Stop retryingalert or fail overAttempts left?Return the errorRetry-After present?Wait Retry-Afterplus a small random delayFull jitter backoffrandom(0, min(cap, base x 2^n))Resend the same requestyesnonoyesyesno
Figure 2: Handling a 429. Rule out an exhausted quota, check the attempt budget, wait, then resend the same request.
  1. Check the body first. Anthropic's 429 for a spent monthly cap has no retry-after header and carries the error code enforced_spend_limit_reached, and retries fail until access resumes. OpenAI also advises against retrying quota or billing errors.
  2. Wait at least the Retry-After value, plus a small random delay, as OpenAI's rate limits guide recommends, so clients do not all return at the same moment.
  3. Otherwise, back off with full jitter: a random wait between zero and min(cap, base × 2^attempt). In Marc Brooker's 2015 analysis of backoff and jitter on the AWS Architecture Blog, jitter cut calls by more than half with 100 contending clients, compared with plain exponential backoff.
  4. Cap the attempts, then return the error or fail over to another provider or deployment.
  5. Avoid tight loops and stacked retries. OpenAI counts failed requests toward its per-minute limits, and its official SDKs already retry eligible 429s, so a second retry loop multiplies attempts.

A provider-agnostic version in Python:

import random
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
 
def retry_after_seconds(value):
    """Parse Retry-After as delay-seconds or an HTTP-date (RFC 9110, 10.2.3)."""
    if not value:
        return None
    value = value.strip()
    if value.isdigit():
        return float(value)
    try:
        when = parsedate_to_datetime(value)
    except (TypeError, ValueError):
        return None
    if when.tzinfo is None:
        when = when.replace(tzinfo=timezone.utc)
    return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())
 
def quota_exhausted(response):
    """Provider-specific. Anthropic marks a spent monthly cap with this code."""
    try:
        error = response.json().get("error") or {}
    except ValueError:
        return False
    return (error.get("details") or {}).get("error_code") == "enforced_spend_limit_reached"
 
def send_with_retries(send, max_attempts=5, base=1.0, cap=60.0):
    """`send` performs one HTTP request and returns the response."""
    for attempt in range(max_attempts):
        response = send()
        if response.status_code != 429:
            return response
        if quota_exhausted(response) or attempt == max_attempts - 1:
            return response  # waiting will not help, or the budget is spent
        delay = retry_after_seconds(response.headers.get("retry-after"))
        if delay is not None:
            delay += random.uniform(0, 1)  # spread clients that got the same value
        else:
            delay = random.uniform(0, min(cap, base * 2 ** attempt))  # full jitter
        time.sleep(delay)

Swap quota_exhausted for each provider's own signal, and log 429s as their own error class.

Pace requests before the limit#

Pacing traffic below the limit costs less than recovering from 429s:

  • Read the remaining-requests and remaining-tokens headers on every success, and slow down as they approach zero.
  • Run a client-side token bucket slightly below the provider's limit, with cost set to each request's estimated tokens.
  • Route all workers that share an organization or project through one limiter. Ten workers that each pace to the full limit send ten times the limit.
  • Do not add API keys for capacity. OpenAI applies limits per organization and project, Gemini per project, and Anthropic per organization, so load balancing across keys in one project or organization adds no headroom.

API rate limiting at LLM providers#

LLM providers limit tokens as well as requests, because one request can carry a short question or a whole document. OpenAI, Anthropic, and Google apply their limits per organization or project, raise them automatically through usage tiers, and count tokens in different ways.

The three APIs from the model providers directory, as of November 2026:

OpenAI Anthropic Google Gemini
Metrics RPM, RPD, TPM, TPD, images per minute RPM, input TPM, output TPM per model class RPM, input TPM, RPD
Scope Organization and project Organization, with optional workspace limits Project, not API key
Token counting Larger of max_tokens and estimated size Cache reads excluded; output counts generated tokens Input tokens
Refill or reset Reset reported as a duration Token bucket, continuous refill RPD resets at midnight Pacific
Increases Tiers rise with credit purchases Tiers rise with usage history Tiers rise with billing and spend

Five details change how requests should be shaped:

  • OpenAI counts max_tokens up front. OpenAI's token limits use the larger of max_tokens and the estimated request size, so an oversized default wastes capacity. Some model families share one limit, and Batch API jobs draw on a separate cap on queued input tokens.
  • Anthropic enforces per-minute limits as a token bucket. A 60 RPM limit might be enforced as one request per second, so a short burst can trigger 429s while the per-minute total looks fine.
  • Anthropic excludes cached input. Tokens read from the prompt cache do not count toward input tokens per minute (ITPM); in Anthropic's example, a 2,000,000 ITPM limit with an 80 percent cache hit rate processes 10,000,000 input tokens per minute. Output limits count generated tokens only, so a high max_tokens has no rate limit cost.
  • Anthropic caps how fast usage grows. A sharp rise can return a 429 with error code ramp_limit_exceeded while traffic is under its limits, and Anthropic recommends raising traffic by at most one step per minute.
  • Gemini quotas belong to the project. The Gemini API resets its daily quota at midnight Pacific time, moves projects from the Free tier through Tiers 1, 2, and 3 as billing is linked and spend grows, and gives preview models tighter limits.

How to build a rate limiter for your own API#

Building a rate limiter for your own API means choosing a key, a unit, and an algorithm for each resource, storing counters where every replica can read them, and telling clients which limit they hit. The same decisions apply to an LLM application that divides a shared provider quota among its own users, teams, or agents.

  1. Key on the authenticated identity, such as the API key, user, or tenant. Use IP addresses only for anonymous endpoints, since many users share one address behind a corporate proxy or NAT.
  2. Count the unit that tracks cost: requests for uniform endpoints, tokens for LLM endpoints (estimated before the call and reconciled after it), and concurrent requests for long-lived streams.
  3. Layer windows, such as 100 requests per minute plus 1,000 per day, the pair in the IETF draft's example policy.
  4. Share counters across replicas in a store such as Redis, updated atomically. Four instances that each allow 100 requests per minute in local memory admit 400.
  5. Return 429 with Retry-After and a body that names the limit, and add jitter to reset times; the draft warns that clients given the same reset moment all return at once.
  6. Give each tenant a slice below the provider limit. Anthropic's workspace example caps one workspace at 30,000 input tokens per minute inside a 40,000 organization limit.

An AI gateway is a common place to enforce these limits for model traffic. It issues each team or customer a virtual key, counts tokens and spend per key, and returns the 429 before a request reaches the provider; the AI gateways directory lists open source and managed options.

Agents need limits on tools as well as models, because one model response can request several tool calls. The MCP specification's tools page requires MCP servers to rate limit tool invocations, and the MCP security guide covers per-tool limits with the other server controls.

Where to go next: rate limiting is one of several controls on the path to a model. The LLM routing guide covers fallbacks for a provider that keeps returning 429s, the semantic caching guide covers removing repeat calls that spend quota, and the LLM observability guide covers tracking rate limit errors by provider and model.

Frequently asked questions

What does rate limited mean?

Being rate limited means a service has temporarily refused your requests because you sent more than its limit allows in a time window. The response is usually HTTP 429 Too Many Requests, sometimes 403 or 503. Access returns once the window passes or the bucket refills. It is not a ban, but retrying immediately keeps the limit triggered, and some providers, including OpenAI, count failed requests toward the limit.

What is a rate limiter?

A rate limiter is the component that enforces a rate limit. It keeps a counter, a timestamp log, or a token bucket for each client key and decides whether each request passes, waits, or is rejected. Rate limiters run in application middleware, in reverse proxies such as NGINX, in API gateways, and in AI gateways placed in front of model providers.

Why am I being rate limited?

You are being rate limited because your traffic crossed one of the service's limits, and the cause is often less obvious than total volume: a short burst inside a per-minute limit, a token limit reached before the request limit, other processes sharing the same organization or project quota, or retries that count as requests. The rate limit headers and the error body usually say which limit triggered.

What is the difference between rate limiting and throttling?

Rate limiting usually means rejecting requests above a cap, while throttling usually means slowing excess requests by delaying or queueing them. The terms overlap in practice. NGINX's limit_req module delays requests above the configured rate and rejects them only once they exceed the burst size, so one component throttles first and rate limits second. Read what a product does rather than what it calls the feature.

How do I fix a 429 Too Many Requests error?

Fix a 429 by waiting before you retry: honor Retry-After when it is present, otherwise use capped exponential backoff with jitter, and limit the number of attempts. Then lower the rate that caused it by pacing requests with a client-side token bucket, caching repeated work, or moving to a higher usage tier. If the error body says a quota or spend cap is exhausted, stop retrying.

What is an API rate limit?

An API rate limit is the published cap on how many requests, or units such as tokens, a key, user, organization, or project may send to an API in a time window. Providers document limits per endpoint or per model, report remaining capacity in response headers, and usually raise limits through usage tiers as an account's spend or history grows.

Terms in this guide

Cite this guide

The AI Engineering Editors. "Rate limiting: algorithms, HTTP 429, headers, and LLM API limits." The AI Engineering, updated Nov 24, 2026. https://theaiengineering.com/articles/rate-limiting

Title
Rate limiting: algorithms, HTTP 429, headers, and LLM API limits
Author
The AI Engineering Editors
Publisher
The AI Engineering
Published
Updated
View as Markdown

The AI Engineering Editors ·