---
title: "Rate limiting: algorithms, HTTP 429, headers, and LLM API limits"
description: "Rate limiting caps how many requests or tokens a client can send per time window. Learn the algorithms, HTTP 429, rate limit headers, retries, and LLM limits."
summary: "Every API that returns HTTP 429 runs a rate limiter, but the algorithm, the unit it counts, and the headers it sends differ by service. This explainer covers windows and buckets, Retry-After and the IETF RateLimit fields, backoff with jitter, and how LLM providers meter tokens."
type: "explainer"
canonical_url: "https://theaiengineering.com/articles/rate-limiting"
markdown_url: "https://theaiengineering.com/articles/rate-limiting.md"
topic: "AI gateways and LLM routing"
author: "The AI Engineering Editors"
publisher: "The AI Engineering"
published: "2026-11-24"
updated: "2026-11-24"
keywords: ["rate limiting","what is rate limiting","rate limiting algorithms","api rate limiting","429 too many requests","rate limiter"]
citation: "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"
---

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

## TL;DR

- Rate limiting caps how many requests or units of work, such as tokens, a client can send in a time window, and servers usually reject the excess with HTTP 429 Too Many Requests, defined in RFC 6585.
- A fixed window counter can admit twice its limit across a window boundary, while sliding window counters, token buckets, and leaky buckets avoid that spike with different trade-offs in memory and burst tolerance.
- Retry-After, defined in RFC 9110, is the standardized way to say when to retry; vendor X-RateLimit headers vary by API, and the IETF RateLimit and RateLimit-Policy fields were still an Internet-Draft as of November 2026.
- Clients should honor Retry-After, otherwise retry with capped exponential backoff and full jitter, and stop retrying when a 429 reports an exhausted quota or spend cap.
- LLM APIs limit tokens as well as requests and apply limits per organization or project, so extra API keys in the same project or organization add no capacity.

[Rate limiting](https://theaiengineering.com/glossary/rate-limiting) is a control that caps how many requests, or units of work such as [tokens](https://theaiengineering.com/glossary/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](https://theaiengineering.com/topics/ai-gateways) 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](https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/) 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](https://theaiengineering.com/glossary/ai-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.

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

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.

Spans:

- Window 1, limit 60: 0 to 60s
  - Burst A: 60 requests: 58 to 60s (allowed, count 60)
- Window 2, limit 60: 60 to 120s
  - Burst B: 60 requests: 60 to 62s (allowed, count reset)
- Rolling minute, 2 s to 62 s: 2 to 62s (120 requests, 2x the limit)

Markers:

- 60s: counter resets

### 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:

```text
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](https://platform.claude.com/docs/en/api/rate-limits), so capacity refills continuously instead of resetting on a schedule.

```python
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](https://nginx.org/en/docs/http/ngx_http_limit_req_module.html) limits requests with this method:

```nginx
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](https://www.rfc-editor.org/rfc/rfc6585.html#section-4) 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
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](https://www.rfc-editor.org/rfc/rfc9110.html#section-10.2.3) defines `Retry-After` as either a number of seconds or an HTTP date:

```http
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
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.

**Figure 2: Handling a 429. Rule out an exhausted quota, check the attempt budget, wait, then resend the same request.**

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.

Components:

- **429 received**
- **Read the error body**: quota or spend cap used up?
- **Stop retrying**: alert or fail over
- **Attempts left?**
- **Return the error**
- **Retry-After present?**
- **Wait Retry-After**: plus a small random delay
- **Full jitter backoff**: random(0, min(cap, base x 2^n))
- **Resend the same request**

Connections:

- 429 received → Read the error body
- Read the error body → Stop retrying: yes
- Read the error body → Attempts left?: no
- Attempts left? → Return the error: no
- Attempts left? → Retry-After present?: yes
- Retry-After present? → Wait Retry-After: yes
- Retry-After present? → Full jitter backoff: no
- Wait Retry-After → Resend the same request
- Full jitter backoff → 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](https://developers.openai.com/api/docs/guides/rate-limits) 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](https://aws.amazon.com/blogs/architecture/exponential-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](https://theaiengineering.com/glossary/model-failover) 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:

```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](https://theaiengineering.com/glossary/llm-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](https://theaiengineering.com/platforms/model-providers), 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](https://developers.openai.com/api/docs/guides/rate-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](https://theaiengineering.com/glossary/prompt-caching) 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](https://aistudio.google.com/docs/rate-limits) 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](https://theaiengineering.com/glossary/llm-streaming).
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](https://theaiengineering.com/articles/what-is-an-ai-gateway) is a common place to enforce these limits for model traffic. It issues each team or customer a [virtual key](https://theaiengineering.com/glossary/virtual-key), counts tokens and spend per key, and returns the 429 before a request reaches the provider; the [AI gateways directory](https://theaiengineering.com/platforms/ai-gateways) 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](https://modelcontextprotocol.io/specification/2026-07-28/server/tools) requires [MCP servers](https://theaiengineering.com/glossary/mcp-server) to rate limit tool invocations, and the [MCP security guide](https://theaiengineering.com/articles/mcp-security) 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](https://theaiengineering.com/articles/llm-routing) covers fallbacks for a provider that keeps returning 429s, the [semantic caching guide](https://theaiengineering.com/articles/semantic-caching) covers removing repeat calls that spend quota, and the [LLM observability guide](https://theaiengineering.com/articles/llm-observability) 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

- [Rate limiting](https://theaiengineering.com/glossary/rate-limiting): Rate limiting is the enforcement of a maximum number of requests or tokens a client may send to an API within a time window, with excess requests rejected, usually with HTTP 429.
- [Tokens](https://theaiengineering.com/glossary/tokens): Tokens are the units of text a language model processes, typically whole words, word fragments, punctuation, or bytes, each mapped to an integer ID from the model's fixed vocabulary.
- [AI agent](https://theaiengineering.com/glossary/ai-agent): An AI agent is a software system in which a large language model runs in a loop, calling tools, reading their results, and repeating until the task is complete or a stop condition is reached.
- [Model failover](https://theaiengineering.com/glossary/model-failover): Model failover is the automatic rerouting of an LLM request to a backup model, deployment, or provider when the primary target returns an error, times out, or hits a rate limit.
- [LLM load balancing](https://theaiengineering.com/glossary/llm-load-balancing): LLM load balancing is the distribution of requests for one model across several interchangeable deployments, such as API keys, regions, providers, or replicas, by weight, latency, load, or remaining quota.
- [Prompt caching](https://theaiengineering.com/glossary/prompt-caching): Prompt caching is an LLM API and inference-server feature that stores the computed attention state for a repeated prompt prefix, so later requests sharing that prefix skip reprocessing it.
- [LLM streaming](https://theaiengineering.com/glossary/llm-streaming): LLM streaming is the delivery of a language model's output in small chunks as it is generated, usually as server-sent events over HTTP, so clients can show text before the response is complete.
- [Virtual key](https://theaiengineering.com/glossary/virtual-key): A virtual key is an API key issued by an AI gateway that maps a caller to its allowed models, budget, and rate limits, while the gateway keeps the real provider credentials.
- [MCP server](https://theaiengineering.com/glossary/mcp-server): An MCP server is a program that exposes tools, resources, and prompts to AI applications through the Model Context Protocol, running locally over stdio or remotely over Streamable HTTP.
- [AI gateway](https://theaiengineering.com/glossary/ai-gateway): An AI gateway is a proxy layer between applications and model providers that exposes one API for many models and centralizes routing, failover, access control, cost tracking, caching, and logging.

## Related guides

- [What is an AI gateway? How it works and when you need one](https://theaiengineering.com/articles/what-is-an-ai-gateway): An AI gateway is a proxy between your apps and model providers. Learn how it works, its core features, AI gateway vs API gateway, and open source options.
- [LLM routing: strategies, fallbacks, and learned routers](https://theaiengineering.com/articles/llm-routing): LLM routing guide: rule-based and cost-aware strategies, fallbacks, load balancing, semantic and learned routers like RouteLLM, router evals, and pitfalls.
- [LLM observability: what to capture, which metrics, and tools](https://theaiengineering.com/articles/llm-observability): LLM observability guide: what to capture in traces and spans, metrics to track, OpenTelemetry GenAI conventions, tool categories, and keeping prompts private.
- [MCP security: threats, authentication, and controls for MCP servers](https://theaiengineering.com/articles/mcp-security): MCP security guide: tool poisoning, prompt injection, and token passthrough, how MCP authentication works with OAuth 2.1, and controls for MCP servers.

Part of the [AI gateways and LLM routing](https://theaiengineering.com/topics/ai-gateways) topic hub.

## 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: 2026-11-24
- Updated: 2026-11-24
- URL: https://theaiengineering.com/articles/rate-limiting
- Markdown: https://theaiengineering.com/articles/rate-limiting.md

To cite one section, link to its anchor:

- [What is rate limiting?](https://theaiengineering.com/articles/rate-limiting#what-is-rate-limiting)
- [Why services use rate limiting](https://theaiengineering.com/articles/rate-limiting#why-services-use-rate-limiting)
- [Rate limiting algorithms](https://theaiengineering.com/articles/rate-limiting#rate-limiting-algorithms)
- [HTTP 429 Too Many Requests](https://theaiengineering.com/articles/rate-limiting#http-429-too-many-requests)
- [Rate limit headers](https://theaiengineering.com/articles/rate-limiting#rate-limit-headers)
- [How to handle a 429: retries with backoff and jitter](https://theaiengineering.com/articles/rate-limiting#how-to-handle-a-429-retries-with-backoff-and-jitter)
- [API rate limiting at LLM providers](https://theaiengineering.com/articles/rate-limiting#api-rate-limiting-at-llm-providers)
- [How to build a rate limiter for your own API](https://theaiengineering.com/articles/rate-limiting#how-to-build-a-rate-limiter-for-your-own-api)
- [Frequently asked questions](https://theaiengineering.com/articles/rate-limiting#faq)
