Rate limiting caps how many requests a client may make to a service in a period, such as 100 requests a minute per API key. Requests over the cap are refused, usually with HTTP 429 Too Many Requests, or delayed until there is room. It protects sign-in pages, APIs and paid services from guessing, runaway scripts and overload.
This guide is for developers and for whoever owns an API, a sign-in page or an integration. It covers how the common algorithms work, what a limit should count and per what key, and how to pick the numbers. Then it turns to where to enforce limits, what a good 429 looks like, how to live with other providers' limits and how to test your own. The examples come from three platforms we build and run. Specifications, products and published limits are as of December 2026.
What is rate limiting, and how is it different from throttling and quotas?
RFC 6585, published in April 2012, gave the practice its status code: 429 means the user "has sent too many requests in a given amount of time". The RFC leaves the rest to you. It does not say how a server identifies the user or counts requests: per resource, across a server or across a set of servers, by credentials or by a cookie. Those choices are most of the work, and most of this guide.
The words overlap in practice. NIST's authentication guideline titles its section "Rate Limiting (Throttling)", and the Amazon Builders' Library says API rate limiting is also called throttling or admission control. Where a team does draw a line, it falls between refusing excess requests and slowing them down. NGINX's limit_req, for one, delays excess requests and refuses them only once a burst allowance is used up.
| Control | What it counts | What happens over the limit | Published example |
|---|---|---|---|
| Rate limit | Requests per key in a time window | Refused, usually with 429 | GitHub's REST API: 5,000 requests an hour for a signed-in user |
| Throttling | The same | Held, then released at the allowed rate | NGINX limit_req with a burst allowance |
| Quota | A total per tenant or plan, often over a long run | Refused until the period resets or it grows | Amazon API Gateway usage plans, which combine throttles with quotas |
| Concurrency limit | Requests in progress at the same moment | Refused, or made to wait | Stripe: 50 requests in progress for standard live-mode traffic by default |
| Load shedding | The load on the whole system, not one client | Low-priority work dropped first, often 503 | Stripe's 2017 post: capacity reserved for critical API calls |
Why rate limit, and what can't a rate limit do?
OWASP lists the problem as API4:2023 Unrestricted Resource Consumption in its API Security Top 10. Its first example is ordinary: a "forgot password" step that sends a text message through a provider charging $0.05 a message. A script calls it tens of thousands of times, and the company loses thousands of dollars in minutes. OWASP's fixes include a limit on how often a client can call the API, tuned to the business, since some endpoints need stricter ones. They also include a limit on how often one client can repeat a single operation, such as validating a one-time code, and a spending limit or billing alert at every paid provider.
The reasons to limit fall into five groups:
- Guessing. Passwords, one-time codes, coupon codes and short links can be tried one after another. A limit turns a fast search into a slow one.
- Cost. Every request that sends a text, calls a language model or reads a paid API spends money.
- Fairness. On a shared service, one tenant's surge should not slow everyone else. AWS enforces quotas per tenant or per workload, so the unplanned part of one workload is refused while the others keep predictable performance.
- Runaway clients. A retry loop, a polling bug or a misconfigured job can send as much traffic as an attack. Stripe wrote in 2017 that its request rate limiter turned away millions of requests a month, especially from test-mode scripts that had got out of hand.
- Scraping and enumeration. Walking through every record by ID or by search.
A rate limit is not a defence against a volumetric DDoS attack. Once a flood fills your link, it no longer matters what the server refuses, so floods are absorbed upstream by an edge network; our guide to DDoS attacks covers those layers. It is also weak against attackers who spread their requests out. The OWASP testing guide's page on lockout mechanisms notes that distributed brute force and password spraying, which send attempts from many IP addresses, can bypass lockouts that count failures only per address. Nor is it access control: a request under the limit still has to be authorized. The IETF's draft on rate limit headers says the same of its own fields, which "are not meant to support authorization".
How do rate limiting algorithms work?
Five algorithms come up again and again. They differ in how much they store per key, how they treat bursts and how accurate they are at the edges of a window.
Fixed window counter
Keep one counter per key per period and reset it when the next period starts. The Redis documentation shows the classic version: one key per IP address per second, incremented with INCR and given an expiry, with requests above ten refused. It also flags a trap in the single-counter variant: if a client increments the key but the expiry is never set, the counter never resets. Run the increment and the expiry together, in a transaction or a server-side script.
The flaw is at the edges. Cloudflare's engineers note that resetting the counter at regular intervals lets regular traffic spikes through. With a limit of 100 a minute, a client can send 100 requests in the last second of one minute and 100 more in the first second of the next: 200 requests in two seconds, every one of them within the limit.

Sliding log
Store the timestamp of every request and count those inside the last period. It is exact, but Cloudflare calls its processing and memory needs huge, especially for long windows such as 5,000 requests an hour, because each check has to read and process a lot of stored data.
Sliding window counter
Keep the fixed window's two counters, this period's and the last one's, and weight the previous count by how much of it still overlaps the rolling window. In Cloudflare's 2017 example the limit is 50 a minute. The previous minute had 42 requests and the current one, which began 15 seconds ago, has 18, so the estimate is 42 × 0.75 + 18 = 49.5 and the next request is refused. Across 400 million requests from 270,000 distinct sources, Cloudflare measured 0.003% of requests wrongly allowed or limited and an average 6% difference between the real and the estimated rate, with only two numbers stored per counter.
Token bucket
Each key has a bucket of tokens. Every request takes one, and tokens are added at a fixed rate up to a maximum that the Builders' Library calls the burst capacity, because a full bucket can be spent at once. It is a widely used design. Stripe's 2017 engineering post says its request rate limiter used a token bucket, Amazon API Gateway throttles with one, and the Claude API uses one, so capacity is continuously replenished rather than reset at fixed intervals.

The token bucket algorithm fits in a few lines. With a capacity of 10 and a rate of one token a second, a client that has been quiet can send ten requests at once, then one a second after that.
def allow(bucket, now, rate, capacity):
# Refill for the time since the last request, never above capacity.
bucket.tokens = min(capacity, bucket.tokens + (now - bucket.last) * rate)
bucket.last = now
if bucket.tokens >= 1:
bucket.tokens -= 1
return True # serve the request
return False # refuse with 429
One consequence surprises people. Anthropic, which makes Claude, notes that a limit of 60 requests a minute may be enforced as one request a second, so a short burst can be refused even when the minute's total is under 60. AWS also describes composing two buckets, one with a low rate and a high burst capacity and one with a high rate and a low burst capacity, to allow bursts while bounding how fast they arrive.
Leaky bucket
Requests fill a bucket that drains at a fixed rate, and new requests are refused once it is full. NGINX's limit_req uses this method. With rate=1r/s and burst=5, it allows one request a second on average with bursts of up to five; excess requests are delayed, and nodelay serves the burst at once instead. Mind the default: NGINX refuses with 503 unless you set limit_req_status.
limit_req_zone $binary_remote_addr zone=signin:10m rate=1r/s;
limit_req_status 429;
server {
location /signin/ {
limit_req zone=signin burst=5 nodelay;
}
}
This keys the sign-in page by address, so it is a per-address backstop against floods; guesses are counted per account, as the sign-in section below explains.
| Algorithm | Stored per key | Bursts | Accuracy at window edges | Where you meet it |
|---|---|---|---|---|
| Fixed window counter | One counter | Up to twice the limit across a boundary | Poor | The Redis INCR pattern |
| Sliding log | Every timestamp in the window | Never more than the limit in any window | Exact | Small limits over short windows |
| Sliding window counter | Two counters | Smoothed | Close (0.003% wrong) | Cloudflare's 2017 design |
| Token bucket | Token count and last refill time | Allowed up to the bucket size | Exact for its model | Stripe, Amazon API Gateway, Claude API |
| Leaky bucket | Bucket level and last drain time | Delayed while there is room, then refused | Exact for its model | NGINX limit_req |
If you have no reason to choose otherwise, use a token bucket. It allows the short bursts real clients produce, it is cheap to store, and it behaves like the APIs your developers already call.
What should a limit count, and per what key?
A limit has three parts: the unit it counts, the key it counts per and the window.
Most limits count requests, but a request is a poor unit when requests vary in cost. GitHub's secondary limits count points, at most 900 a minute for REST endpoints. Anthropic counts requests, input tokens and output tokens a minute. The Builders' Library describes services that admit each request as if it were the cheapest kind, then debit the client's quota by the true cost once the call completes. The IETF draft lets a server name its unit, with requests as the default, for the same reason.
| Key | Good for | Watch out for |
|---|---|---|
| IP address | Anonymous traffic: sign-up, contact forms, new drafts | Many people behind one address; attackers with many |
| Account or user | Everything after sign-in | Credential stuffing spreads guesses across accounts |
| API key or token | Partner and machine clients | Leaked keys; one customer holding many keys |
| The object being worked on | Uploads to one order, guesses at one code | The object id has to be known before the check |
| Site-wide | A ceiling on total cost or load | One abuser can use up everyone's share |
The IP address is the key most limits start with and the one most likely to be wrong. RFC 6269, on issues with IP address sharing, describes what happens to a "penalty box" when one address carries many subscribers. Many sign-in attempts from one address become normal, and one user who fails a few times can lock out others on their first try. Its conclusion is blunt: under widespread address sharing, "penalty box solutions to service abuse simply will not work". Cloudflare offers a characteristic called IP with NAT support that tells visitors behind one address apart with a cookie; visitors who refuse or clear cookies still share one counter.

IPv6 has the opposite problem. RFC 6177 says an end site should get at least one /64, and in most cases significantly more, and under RFC 8981 devices rotate temporary addresses with a default preferred lifetime of one day. A client that wants a fresh address has 2^64 of them in its own /64, so a per-address limit on IPv6 does almost nothing. Key IPv6 clients by their /64 prefix. A site that holds a /56 or a /48 can still move between /64s, so watch for many /64s inside one larger prefix.
Behind a proxy, the address your application sees is the proxy's, and the client's arrives in a header. MDN is explicit that any security-related use of X-Forwarded-For, rate limiting included, must only use addresses added by a trusted proxy. That holds only if the origin accepts connections from that proxy alone: a server that can also be reached directly reads whatever header the caller sends. A PortSwigger training lab shows the alternative: an IP-based brute-force block bypassed by sending a made-up X-Forwarded-For with each guess. Our reverse proxy guide shows where NGINX appends to that header.
On Minute Notary, an online notary platform we build and run, many limits are keyed by the thing being worked on rather than by address. The tight upload limits are counted per booking draft, behind a wide per-address backstop, and the signing screen's status checks per signer, so a notary and several signers in one office do not use up each other's allowance. Starting a brand-new draft, the step that writes to the database for an anonymous visitor, is counted per address. Every address key folds IPv6 to its /64, and the address is taken from the header our CDN sets at its edge, which overwrites whatever the client sent.
One more rule: decide which bucket a request belongs to from state the server holds, not from what the request says about itself. If a request can claim to be the cheap continuation of a session rather than the expensive start of a new one, a script will claim it every time.
How do you choose the numbers?
Start from what honest clients do, not from a round number. Stripe's advice is to dark-launch each limiter, watch what it would block and tune it until it keeps the API up without affecting users' existing request patterns. NGINX has a switch for this, limit_req_dry_run (since version 1.17.1), which counts excess requests without limiting them. AWS goes further: it logs the throttle key and limit with every request and measures, for each key, how many requests were wrongly refused and how many were wrongly admitted.
Then decide what each limit is for, because there are two kinds and they want different numbers.
- Backstops sit on things an honest user does: loading a page, saving a draft, checking whether a payment went through. Their job is to stop a runaway loop or a script, so they sit far above anything a real person produces, including a household, an office or a mobile carrier sharing one address.
- Security limits sit where each request is a guess: a password, a one-time code, a gift card number. Their number comes from the odds of guessing, and they stay tight even if an honest user occasionally meets one.
We learned the difference on Minute Notary. A customer in the middle of paying was refused at checkout. The payment page re-checked the payment's status every time its tab came back into focus, so switching between apps a few times used up an hourly allowance meant to stop scripts, and the refusal appeared as an error with no way forward. That limit protected nothing about the payment itself; the booking's own token and the payment provider authorize the charge. We raised the customer-facing limits well above honest use and left the admin limits, which also slow down guessing of one-time codes, exactly where they were.
Good Cleaner Co., a local cleaning company serving Ottawa homes and businesses whose site we build and run, made the same call on its booking form. The price estimate refreshes as a visitor changes rooms, add-ons and frequency, and several genuine visitors often share one address, so the limit on those previews was raised: they read rules, create nothing, charge nothing and call no outside provider. The limit in front of payment attempts was left as it was.
Keep separate buckets for separate actions, so that a burst of one never starves another, and give the sensitive or expensive actions their own stricter limits, as OWASP recommends.
How should sign-in and one-time code limits work?
For sign-in, NIST SP 800-63B-4, final since July 2025, sets the ceiling. Unless an authenticator's own rules say otherwise, a verifier must limit consecutive failed attempts with one authenticator on one account to no more than 100, then disable that authenticator. NIST explains the number as a balance between the chance of a correct guess, such as 100 attempts against a six-digit one-time code, and the cost of account recovery; agencies may set lower limits. NIST also suggests ways to keep attackers from locking real users out. One is a bot challenge before an attempt. Another is a wait after each failure that grows as the account nears its limit, from 30 seconds up to an hour in its example. A third is risk signals such as the address, location and timing of requests.
Count failures per account, not per address. OWASP's Authentication Cheat Sheet says the failed-login counter should be associated with the account itself, so that an attacker cannot spread attempts across many addresses. It also describes exponential lockout: a lockout that starts very short, such as one second, and doubles after each failure. Reset the count only when that account signs in successfully, which is what NIST recommends for the authenticators used. A PortSwigger lab shows why: its count of failed attempts resets whenever the attacker signs in to their own account between guesses at the victim's.
Watch the window as well as the count. A six-digit code has a million values. Ten guesses a minute sounds strict, but on a code that stays valid for 24 hours it allows 14,400 guesses, a 1.4% chance of finding it. Count tries over the life of the code, not per minute or per hour. NIST closes a related gap: for codes sent out of band, generating a new code must not reset the failure count.
Good Cleaner Co. ties the code budget to the sign-in itself. Proving the password issues a short-lived ticket with a small, fixed number of code tries. Each try is counted, under a lock on that ticket, before the code is checked, so parallel requests cannot all slip into the same gap, and a request that crashes costs the same as a wrong code. When the tries are gone, so is the ticket, and the person signing in starts again from the password, where attempts have their own per-account limit.
Important
A limit that guards guessing must hold when its own storage fails. If the counter store is down and the check answers "allowed", the limit has quietly disappeared for exactly the requests that matter.
Where should rate limiting run?
Most systems need limits at more than one layer, because each layer sees different things. The Builders' Library describes Amazon putting API Gateway and AWS WAF in front of its services, so that API Gateway absorbs a surge and the service fleet stays free to serve real traffic.
- Edge network or WAF. It sees every request and the client's address, but not who is signed in. Cloudflare's rate limiting rules count requests for each combination of characteristics, such as the address, headers, cookies or path, over a period, then act for a mitigation timeout. Its counters are not shared across data centers, except those in the same geographical location. AWS WAF rate-based rules group requests by your criteria and track each instance of a rule separately.
- API gateway or reverse proxy. It sees API keys and routes. Amazon API Gateway applies its throttles and quotas on a best-effort basis, as targets rather than guaranteed ceilings. Envoy pairs a local token bucket, which absorbs very large bursts, with a global rate limit service that applies the fine-grained limit.
- Application. Only the application knows the account, the tenant, the object and what an action costs, so per-account and per-action limits live here.
- The expensive resource itself. A document renderer or a database that can only do a few things at once needs a concurrency limit, whoever is asking.
Once there is more than one server, the count has to be shared or divided. The Builders' Library lists two common approaches. One divides each key's quota by the number of servers and counts locally, which assumes requests spread evenly. The other hashes each key to one rate tracker server, which scales to many keys but turns a very busy key into a hot spot. Stripe's 2017 post describes its limiters running on Redis, a shared in-memory store.

Then decide what happens when that store is down. Stripe's advice is to fail open, so a bug in the limiter or an outage of its store never takes the API down with it. That is right for backstops and wrong for security limits. On Minute Notary, ordinary limits let requests through when the counter store cannot answer, while the checks that are the only guard against guessing one-time codes refuse. Their message says the request could not be checked, not that there were too many attempts, because someone sent to wait out a cooldown that does not exist will simply keep trying. Good Cleaner Co.'s limit in front of payment attempts also fails closed.
What should a rate-limited response look like?
Answer with 429 Too Many Requests and say when to come back. RFC 6585 says the response should explain the condition and may include Retry-After, and that 429 responses must not be stored by a cache. RFC 9110 defines Retry-After as either an HTTP date or a number of seconds.
Use 503 Service Unavailable when the server is out of capacity rather than the client out of quota. The Builders' Library draws the line the same way, and notes that some AWS services still return 503 for rate limits because they predate RFC 6585. Under attack, you need not answer at all: RFC 6585 points out that answering every request with 429 consumes resources too, and that dropping connections may be more appropriate.
Tell well-behaved clients how much they have left. Today that is done with vendor headers: GitHub sends x-ratelimit-limit, -remaining, -used, -reset and -resource, and Stripe adds Stripe-Rate-Limited-Reason to say which limit was hit. The IETF's HTTPAPI working group is standardizing RateLimit-Policy and RateLimit, plus, since revision 12, RateLimit-Partition, which declares what each quota is counted per. As of December 2026 they are still an Internet-Draft, at revision 12 from November 2026, and that revision renamed the RateLimit field's parameters from r and t to a (available quota) and w (window), so check which revision a library implements. The draft also says a client must not treat remaining quota as a promise, and that Retry-After takes precedence when both are present.
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 30
RateLimit-Policy: "default";q=100;w=60
RateLimit: "default";a=0;w=30
{"error": "rate_limited", "message": "Too many requests. Try again in 30 seconds."}

For people rather than programs, a refusal should not be a dead end. Stripe's blog asks for an actionable message. On Minute Notary, a click on an emailed review link that goes over its limit still redirects; only the click counter is skipped. A "continue my booking" link over its limit still opens the booking page, just without the saved draft handed over.
How should your code handle another service's rate limits?
Your integrations are clients too, and their providers' limits become yours. Three published examples, as of December 2026:
| Provider | Published limits | What a refusal carries | What the provider advises |
|---|---|---|---|
| Stripe | 100 requests a second in live mode, 25 in a sandbox; 25 a second per endpoint unless noted; 50 in progress | 429 with Stripe-Rate-Limited-Reason | Exponential backoff with jitter; a client-side token bucket |
| GitHub REST API | 5,000 requests an hour per user (60 unauthenticated); 100 concurrent requests; 900 points a minute | 403 or 429, x-ratelimit-* headers, sometimes retry-after | Wait for the reset; otherwise at least a minute, then back off |
| Claude API | Requests, input tokens and output tokens a minute for each model class | 429 naming the limit, with retry-after when present | Wait as told; tokens read from the cache do not count toward the input-token limit |
What to do, in order:
- Pace yourself below the limit. Stripe suggests a client-side token bucket that paces all your traffic to it, throttled back further when refusals start to appear.
- Honour Retry-After. GitHub asks clients not to retry until its reset time, or the seconds in
retry-after, and to wait at least a minute when neither is given. - Back off exponentially, with jitter. The Builders' Library calls retries selfish: each one spends more of a struggling server's time. Jitter spreads retries out so they do not arrive together, and retries belong at one layer only, because retries at every layer multiply: with three tries at each of five layers, a failing database sees 243 times the load.
- Treat waiting callers and background work differently. AWS notes that synchronous systems have to be impatient because someone is waiting, while asynchronous ones can apply back pressure and slow down until requests succeed again.
- Read the refusal before you retry. Stripe warns that a 429 without its rate limit header may be a lock timeout from concurrent requests on the same object, which goes away when you send writes to one object in sequence.
- Make fewer calls. Cache what does not change, batch what can be batched, and let the provider tell you about changes with a webhook instead of polling for them.
- Park what still fails. Work that cannot get through after its retries belongs in a dead letter queue, not in a loop.
Our integrations service builds connections this way: calls stay within each provider's published limits, a throttled request waits for the interval the provider asks for, and bulk work runs in batches.
When is a queue better than a refusal?
A rate limit refuses what arrives too often. Some resources fail for a different reason: they can only do so much at once, however rarely each client asks. A document renderer, a report query or a model call is expensive while it runs. For those, limit concurrency. In the same 2017 post, Stripe says its concurrent requests limiter triggered far less often than its rate limiter, yet "totally solved" contention on its most CPU-intensive endpoints. It asks clients for a different pattern: a fixed number of workers processing a queue, instead of hammering the API and backing off on 429.
When a request is legitimate and only its timing is wrong, a line beats a refusal. Minute Notary puts the requests that reach its document processing service in a line in arrival order, so a long document is not starved by small saves slipping past it; our dead letter queue guide describes how.
Load shedding is the last layer: when the whole system is overloaded, cheaply refuse the least important work first, which is how the Builders' Library defines it. Stripe's 2017 post describes reserving a fraction of capacity for critical calls such as creating charges, and shedding test-mode traffic before anything else.
Order the checks so the cheapest refusal comes first. Via Ottawa, a guide to local businesses across Ottawa that we build and run, answers visitors' questions with a language model, and every question meets the same gates in order. First a size limit on the request body. Then a limit per address and one for the whole site, both before anything is written or any model is called, so a flood cannot turn into database writes. Then a daily limit per visitor, a bot check for a new conversation and a cap on questions per conversation, and then a spending cap that refuses when it is reached or cannot be checked. Only then does the model run. The site-wide limit is the one that catches a botnet spread across many addresses, which no per-address limit can see.

How do you test rate limits?
A limit that can be walked around can be worse than none, because it looks like protection. The OWASP Web Security Testing Guide covers lockout under WSTG-ATHN-02 and limits on how often a function can be used under WSTG-BUSL-05, such as applying a discount more than once. Test for these bypasses:
- A spoofed client address. Send each request with a different X-Forwarded-For or similar header. If the limit moves, it trusts the client.
- A reset by success. Mix successful actions on your own account in between the failures. If the counter resets, an attacker will do the same.
- Rotation. Fresh IPv6 addresses inside one /64, new sessions, new API keys from a free tier.
- Parallel requests. Send many at once. PortSwigger classes limit overruns as time-of-check to time-of-use flaws: requests slip in between the check and the update. Its single-packet technique, first shown at Black Hat USA 2023, makes a batch of requests arrive together, inside race windows that are often only milliseconds long.
- Batching. One request that does many things. OWASP's example uploads hundreds of pictures in one GraphQL batch, each generating thumbnails, past a limit on how often the endpoint is called.
- Other routes to the same action. An older API version, a mobile endpoint or a second form that reaches the same code.
- The response itself. A 429 or 503 with Retry-After, never cached, and a message that does not reveal which accounts exist.
If an attacker only needs passwords that already leaked elsewhere, no limit is enough. OWASP's credential stuffing guidance calls multi-factor authentication by far the best defence. Our comparison of penetration testing and vulnerability scanning explains what each of the two can find.
A rate limiting checklist
- List what each endpoint costs to serve and what it lets someone guess.
- Pick a key for every limit: the account or the object where you can, the address where you must, with IPv6 folded to its /64 and the address taken only from your own proxy, with the origin closed to direct connections.
- Separate backstops from security limits. Size backstops from logs and security limits from the odds, over the life of each secret.
- Use a token bucket unless you have a reason not to, and count cost rather than requests where requests vary.
- Enforce at the edge for floods, at the gateway for keys and in the application for accounts and actions, with a site-wide ceiling on anything that costs money.
- Decide for each limit whether it fails open or closed when its store is down.
- Answer 429 with Retry-After, use 503 for overload, and never leave a person at a dead end.
- Dark-launch new limits, then watch refusals per key.
- Pace your own calls to providers, back off with jitter and retry at one layer only.
- Test the bypasses before an attacker does.
If you want a second pair of eyes, our security testing service tests web apps and APIs against the OWASP Web Security Testing Guide, and our hosting and maintenance service runs sites behind an edge network with WAF rules and rate limiting.


