API Rate Limiting
Table of Contents
Quick Answer
Rate limiting caps how many requests a client can make to an API in a set period, such as 100 requests a minute per API key. Requests over the limit are rejected, usually with HTTP 429 Too Many Requests and a Retry-After header saying when to try again. It protects login and OTP endpoints from guessing, stops scraping and runaway costs, and keeps one client from overloading the service. Limits work best per user or per key, enforced at more than one layer, with counters shared across servers.
This guide explains what API rate limiting is, how the common rate limiter algorithms work, and the ways weak limits fail in practice. Three Java examples each show the fault, a harmless test and the fix, followed by an nginx configuration, a method for choosing limits, two real incidents, and how to test and monitor limits on your own API.
What is rate limiting?
Rate limiting is a control that counts the requests each client makes and refuses those over an agreed number in a time window. An API rate limit is the published form of that rule: GitHub's REST API, for example, allows 60 requests an hour without authentication and 5,000 an hour for an authenticated user, and reports the current count in response headers.
The "client" can be identified in several ways, and the choice matters as much as the number:
| Limit per | Example | Strength and weakness |
|---|---|---|
| IP address | 10 login attempts a minute per address | Works before login. Attackers can rotate addresses, and many users can share one address behind a company or mobile network. |
| API key or client | 1,000 requests a minute per key | Fair between customers and easy to put on a plan. Says nothing about which user is acting. |
| User or account | 5 OTP checks per account per 10 minutes | Cannot be bypassed by changing address. Needs care so attackers cannot lock real users out. |
| Endpoint or action | 3 password reset SMS per number per hour | Puts the tightest limits where a request is sensitive or costs money. |
When a request is over the limit, the standard response is status 429, defined in RFC 6585 for exactly this case, with a Retry-After header from RFC 9110:
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 42
{"error": "rate_limited", "message": "Too many attempts. Try again in 42 seconds."}
An IETF draft, RateLimit header fields for HTTP, defines RateLimit-Policy and RateLimit headers that tell clients their quota before they hit it. It is still a draft, so many APIs use their own headers, such as GitHub's x-ratelimit-remaining.
Why APIs need rate limiting
An API has no screen to slow anyone down. A script can call it thousands of times a minute, and every call costs CPU, database time and sometimes money. Rate limiting reduces four kinds of harm:
- Guessing. Brute force on passwords, credential stuffing, and guessing short codes such as six-digit OTPs, which have only a million possible values.
- Scraping and enumeration. Walking through IDs, phone numbers or email addresses to collect data at scale. Limits slow this down; object-level authorization is what stops it.
- Cost abuse. OWASP's example is a "forgot password" endpoint that sends an SMS costing $0.05: a script that calls it tens of thousands of times costs the company thousands of dollars in minutes. Paid third-party lookups and LLM tokens work the same way, which OWASP's LLM Top 10 calls denial of wallet.
- Overload. A buggy client in a retry loop, or one customer's batch job, can starve everyone else. This is the denial of service case.
The OWASP API Security Top 10 covers this ground in two risks. API4:2023 Unrestricted Resource Consumption, called "Lack of Resources and Rate Limiting" in 2019, is about limits on requests, payloads, page sizes and spending. API6:2023 Unrestricted Access to Sensitive Business Flows is about automated use of flows such as buying, booking or posting. MITRE's matching weaknesses are CWE-770 (allocation of resources without limits or throttling), CWE-307 (excessive authentication attempts) and CWE-799 (improper control of interaction frequency).
Rate limiting vs throttling vs quotas
| Control | What happens over the limit | Typical period | Example |
|---|---|---|---|
| Rate limiting | The request is rejected, usually with 429 | Seconds to minutes | 100 requests a minute per key |
| Throttling | The request is delayed or queued, then served | Seconds | Requests above 10 a second wait their turn |
| Quota | Rejected until the period renews or the plan changes | Days to months | 50,000 calls a month on the free plan |
Products often use "throttling" for all three. AWS API Gateway, for instance, calls its token bucket limits throttling and returns 429 when they are exceeded.
How rate limiters work: five algorithms
A rate limiter has to answer one question for every request, quickly: has this client used up its allowance? Five algorithms are in common use.
| Algorithm | How it counts | Bursts | State per client | Good for |
|---|---|---|---|---|
| Fixed window | One counter per window, such as per minute, reset at the boundary | Up to twice the limit across a boundary: the end of one window and the start of the next | One counter | Simple quotas |
| Sliding window log | Stores the time of every request and counts those within the last window | None: exact | One entry per request | Low limits that must be exact, such as login |
| Sliding window counter | Weights the previous window's count by how much of it still overlaps, and adds the current count | Smoothed, approximate | Two counters | High-volume APIs |
| Token bucket | Tokens refill at a steady rate up to a capacity; each request takes one | Allowed up to the capacity | Token count and last refill time | Most APIs |
| Leaky bucket | Requests drain from a queue at a fixed rate; overflow is dropped | Smoothed out | Queue level | Protecting a backend that needs an even rate |
AWS API Gateway, Stripe and the Java library Bucket4j all use token buckets. nginx describes its request limiter as a leaky bucket. Cloudflare uses a sliding window counter and reported, from an analysis of 400 million requests, that only 0.003% were wrongly allowed or limited compared with an exact count.
Where to enforce rate limits
| Layer | What it can see | Best used for |
|---|---|---|
| CDN or WAF | IP address, path, headers, country | Stopping floods early and cheaply, before they reach your servers |
| API gateway or reverse proxy | API key, client ID, route, plan | Per-key and per-plan limits, the same for every service behind it |
| Application | The user, the account and the business action | OTP attempts per account, resets per phone number, purchases per user |
Use more than one. The edge sees volume but not identity; the application sees identity but only after the request has cost you a connection. A login endpoint, for example, needs an edge limit per address and an application limit per account.
How weak rate limits fail
Most bypassed limits are not broken by clever tricks. They count the wrong thing, or count in the wrong place.
- Counting by IP address alone. Cloud servers and proxy networks give an attacker thousands of addresses, so a per-address limit only sets the price. Sensitive actions also need a limit per account or per target.
- Trusting
X-Forwarded-For. If the key comes from a header the client can write, every request can claim a new address. MDN warns that any security use of this header, rate limiting included, must use only addresses added by a trusted proxy. - The same action under another path. A limit on
/api/loginthat misses/api/Login,/api/login/,/api/v1/loginor the mobile endpoint. Old versions that never received the limit are part of API9 Improper Inventory Management. - Many operations in one request. GraphQL batching and aliases let one HTTP request carry hundreds of login or OTP attempts. A proxy counting requests sees one. OWASP's GraphQL cheat sheet recommends counting the objects or operations in code, or refusing batches for sensitive operations.
- Counters on each server. With four instances behind a load balancer, an in-memory limit of 5 becomes 20, and every restart resets it.
- Limits on the first step only. Login is limited, but the password-reset code check or the "resend SMS" button is not.
- Racing the counter. If the check and the increment are separate steps, a burst of concurrent requests can all pass before the counter updates. Use an atomic operation in the counter store.
Java examples with fixes
The examples use Bucket4j, a maintained Java token bucket library, with imports left out for length. Run the tests only against systems you own or are authorised to test.
An OTP check with no limit
The fault. A password reset sends a six-digit code by SMS, and this endpoint checks it. Nothing counts the attempts, so a script can try codes until one works.
Result verifyOtpUnsafe(String account, String code) {
// a six-digit code: one million possibilities, valid for ten minutes
return otpStore.matches(account, code)
? new Result(200, "verified")
: new Result(401, "invalid code");
}
How to detect it. List every endpoint that checks a secret: passwords, OTPs, reset codes, PINs, coupon codes. For each, find the limit and what it is counted by. In a test on your own staging system, send 20 wrong codes for a test account and look at the status codes.
Test: 20 wrong codes for one test account, sent one after another
verifyOtpUnsafe -> 20 x 401 every guess was checked
verifyOtpFixed -> 5 x 401, 15 x 429 checking stopped after five guesses
The fix. Give each account its own bucket: five attempts per ten minutes. The limit is per account, so changing IP address does not help an attacker. When the limit is hit, also expire the code and make the user request a new one, so the account's guesses stop counting towards the same code. Add a per-address limit at the edge as a second layer, and in production keep the buckets in an expiring cache or a shared store, as in the third example.
final Map<String, Bucket> otpBuckets = new ConcurrentHashMap<>();
Bucket otpBucketFor(String account) {
return otpBuckets.computeIfAbsent(account, a -> Bucket.builder()
.addLimit(limit -> limit.capacity(5).refillIntervally(5, Duration.ofMinutes(10)))
.build());
}
Result verifyOtpFixed(String account, String code) {
ConsumptionProbe probe = otpBucketFor(account).tryConsumeAndReturnRemaining(1);
if (!probe.isConsumed()) {
long wait = TimeUnit.NANOSECONDS.toSeconds(probe.getNanosToWaitForRefill()) + 1;
return new Result(429, "too many attempts, Retry-After: " + wait);
}
return otpStore.matches(account, code)
? new Result(200, "verified")
: new Result(401, "invalid code");
}
A client key taken from a request header
The fault. The service runs behind a load balancer, so the developer reads the client's address from X-Forwarded-For to use as the rate limit key. The leftmost entry in that header is whatever the client sent.
static String clientKeyUnsafe(String remoteAddr, String xForwardedFor) {
// the leftmost entry is whatever the client chose to send
if (xForwardedFor != null && !xForwardedFor.isBlank()) {
return xForwardedFor.split(",")[0].trim();
}
return remoteAddr;
}
How to detect it. Find where the rate limit key is built and check every header it reads. In a test, send three requests with different made-up X-Forwarded-For values. If they produce three different keys, each request starts a fresh limit. The test values below are documentation addresses that belong to no one.
Test: one client (203.0.113.7) behind the load balancer (10.0.0.5) sends three
requests, each with a different made-up X-Forwarded-For value
clientKeyUnsafe -> 3 keys [198.51.100.1, 198.51.100.2, 198.51.100.3]
clientKeyFixed -> 1 key [203.0.113.7] all three requests count against one limit
The fix. Trust the header only when the connection comes from your own proxy, and read it from the right, skipping the addresses your proxies added. The first address that is not yours is the one your proxy actually saw. A request that bypasses the proxy and connects directly is keyed by its real address, whatever header it sends.
static final Set<String> TRUSTED_PROXIES = Set.of("10.0.0.5", "10.0.0.6");
static String clientKeyFixed(String remoteAddr, String xForwardedFor) {
if (!TRUSTED_PROXIES.contains(remoteAddr) || xForwardedFor == null) {
return remoteAddr; // not from our proxy: ignore the header
}
String[] hops = xForwardedFor.split(",");
for (int i = hops.length - 1; i >= 0; i--) { // right to left
String hop = hops[i].trim();
if (!TRUSTED_PROXIES.contains(hop)) {
return hop; // the first address our proxies did not add
}
}
return remoteAddr;
}
Counters kept on each server
The fault. The fix in the first example keeps buckets in memory. That is correct on one server. With four instances behind a load balancer, each has its own bucket for the same account, so five attempts become twenty, and a deployment resets them all.
How to detect it. Repeat the OTP test through the load balancer rather than against one instance. If more than five attempts are checked before the 429s start, the counters are not shared.
The fix. Keep the buckets in a store all instances share. Bucket4j supports Redis through several clients; with Lettuce, the per-account bucket becomes a proxy to a Redis key. The update is a compare-and-swap, so concurrent requests cannot both take the last token.
RedisClient redis = RedisClient.create("redis://rate-limit-store:6379");
StatefulRedisConnection<String, byte[]> connection =
redis.connect(RedisCodec.of(StringCodec.UTF8, ByteArrayCodec.INSTANCE));
LettuceBasedProxyManager<String> buckets = Bucket4jLettuce.casBasedBuilder(connection)
.expirationAfterWrite(ExpirationAfterWriteStrategy
.basedOnTimeForRefillingBucketUpToMax(Duration.ofMinutes(10)))
.build();
BucketConfiguration otpLimit = BucketConfiguration.builder()
.addLimit(limit -> limit.capacity(5).refillIntervally(5, Duration.ofMinutes(10)))
.build();
Bucket otpBucketFor(String account) {
return buckets.getProxy("otp:" + account, () -> otpLimit);
}
A limit at the edge with nginx
The application limit protects each account; an edge limit stops floods before they reach the application. This nginx configuration allows 10 login requests a minute per client address, with a burst of 5, and answers 429 instead of nginx's default 503. The first three lines make nginx take the client address from your load balancer's header, and only from your load balancer.
# The load balancer at 10.0.0.5 sets the client address; trust it and nothing else
set_real_ip_from 10.0.0.5;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
limit_req_zone $binary_remote_addr zone=login:10m rate=10r/m;
limit_req_status 429;
server {
location = /api/login {
limit_req zone=login burst=5 nodelay;
proxy_pass http://app;
}
}
nginx also has limit_req_dry_run, which counts and logs without rejecting anything. Use it to see what a new limit would block before you turn it on.
How to set API rate limits
- Measure normal use. From your access logs, find how many requests a typical client makes to each endpoint per minute, and the busiest legitimate clients.
- Set the general limit above normal. A few times the busiest normal client leaves room for real bursts without letting a script run free.
- Set tight limits on sensitive actions. Login, OTP and reset-code checks, password reset requests, sign-up, SMS and email sending, and anything that calls a paid service. Count these per account or per target, not only per address.
- Allow short bursts. Apps load several resources at once. A token bucket's capacity, or nginx's
burst, absorbs this. - Tell clients. Return 429 with Retry-After, document the limits, and consider the draft RateLimit headers so clients can slow down before they are refused.
- Roll out in log-only mode first, then enforce, and review the 429s after each release.
- Set spending limits with SMS, email and AI providers, or billing alerts where limits are not offered, as OWASP recommends for API4.
Rate limits across many servers
The "rate limiter system design" question comes down to four decisions:
- A shared counter store. Redis is the usual choice, because it is fast and supports atomic updates. Stripe's engineering team described running its token bucket limiters this way.
- Atomic updates. Read, check and decrement in one operation (a script or compare-and-swap), so concurrent requests cannot overspend.
- What happens if the store is down. Stripe chose to fail open, letting requests through, so a limiter fault never takes the API down. That suits general limits. For login and OTP checks, failing closed is usually safer.
- Expiry. Give every counter a time to live, so keys for clients that never return do not fill memory.
For API consumers: handling rate limits
If you call someone else's API, treat 429 as normal. Wait for the time in Retry-After when it is present. Otherwise retry with exponential backoff and random jitter, so many clients do not retry at the same moment, an approach AWS describes in its architecture guidance. Cache responses that do not change, and spread batch jobs out instead of starting them all on the hour.
Real incidents
Instagram password reset, 2019
Instagram's mobile password reset sent a six-digit code valid for ten minutes, and limited attempts per IP address. Security researcher Laxman Muthiyah found that sending requests concurrently from many addresses got around the limit: in testing he used 1,000 cloud IP addresses to try 200,000 codes against a test account. Facebook fixed the flaw and paid him a $30,000 bug bounty.
The lesson is in the key. A limit per address set the cost of an attack in cloud servers; a limit per account, as in the first example, would have stopped it at a handful of guesses.
Dell partner portal, 2024
In May 2024, Dell told customers that a portal holding names, addresses and order details had been accessed. The person who claimed responsibility told TechCrunch he had registered as a reseller partner and guessed seven-character service tags, sending more than 5,000 requests a minute for nearly three weeks without being noticed, and collecting about 49 million records. Dell confirmed it had received his emails; the volume and duration figures are his account.
Two controls were missing together: a check that a partner could see a given customer's record, and any limit or alert on one account making millions of lookups. Either would have cut the damage sharply.
Testing and monitoring your own API
A short loop against your own staging API confirms that a limit exists and what status it returns. Use a test account and a fixed wrong code:
# Only against your own staging API: 20 wrong codes for a test account
for i in $(seq 1 20); do curl -s -o /dev/null -w "%{http_code}\n" -X POST https://staging.example.com/api/otp/verify -H "Content-Type: application/json" -d '{"account":"test-user","code":"000000"}'; done | sort | uniq -c
You should see a few 401s followed by 429s. If every response is 401, nothing is counting. Repeat the test through the load balancer, on every API version and path that reaches the same action, and with GraphQL batching if you use GraphQL.
| Signal | What it can mean |
|---|---|
| A rise in 429s for one key or account | A buggy client, or someone testing your limits |
| Many accounts each staying just under the limit | A distributed attack spread to avoid it |
| Many addresses failing logins for the same account | Guessing with rotated addresses |
| One account reading far more records than its peers | Scraping, as in the Dell case |
| SMS, email or AI spending above normal | Cost abuse of an unlimited flow |
API rate limiting checklist
- Every endpoint has a general limit per key or per client.
- Login, OTP, reset and sign-up have tighter limits counted per account or target, not only per address.
- Endpoints that send SMS or email or call paid services have limits and provider spending caps.
- The client key never comes from a header the client controls.
- Counters are shared across instances, updated atomically and given an expiry.
- Every path, version and alias of a sensitive action shares the same limit.
- GraphQL counts operations or objects, not just HTTP requests.
- Rejected requests get 429 with Retry-After, and the limits are documented.
- Page sizes, payload sizes and query complexity are capped as well.
- 429 rates and unusual volumes per account raise alerts.
For the wider set of controls, see our API security guide. Rate limiting is one layer: it slows attackers down, while authentication and authorization decide what they can reach.
FAQs
429 Too Many Requests, defined in RFC 6585, ideally with a Retry-After header that says how long to wait. Some APIs use other codes: GitHub returns 403 or 429, and nginx returns 503 unless you set limit_req_status 429. Whatever you choose, document it so clients can handle it.X-Forwarded-For header, the same endpoint reachable under another path or API version, GraphQL batching many operations into one request, and counters kept separately on each server. Each of these is covered, with its fix, on this page.limit_req module as a leaky bucket.Sources and further reading
- OWASP API Security Top 10 - API4:2023 Unrestricted Resource Consumption — Rate limiting, spending limits and the SMS cost scenario
- OWASP API Security Top 10 - API6:2023 Unrestricted Access to Sensitive Business Flows — Automated abuse of business flows
- MITRE CWE-770 - Allocation of Resources Without Limits or Throttling — The weakness behind missing limits
- MITRE CWE-307 - Improper Restriction of Excessive Authentication Attempts — Unlimited login and code guessing
- MITRE CWE-799 - Improper Control of Interaction Frequency — Unlimited use of a feature
- IETF RFC 6585 - Additional HTTP Status Codes — Defines 429 Too Many Requests
- IETF RFC 9110 - HTTP Semantics: Retry-After — How long a client should wait
- IETF draft - RateLimit header fields for HTTP — RateLimit-Policy and RateLimit headers; draft 12, November 2026
- OWASP Top 10 for LLM Applications - LLM10:2025 Unbounded Consumption — Rate limiting and denial of wallet for AI services
- OWASP Cheat Sheet Series - GraphQL — Mitigating batching attacks
- OWASP Cheat Sheet Series - Authentication — Protecting login against automated attacks
- MDN - X-Forwarded-For — Only addresses added by a trusted proxy are safe for rate limiting
- nginx - ngx_http_limit_req_module — limit_req, burst, dry run and the default 503 status
- nginx - ngx_http_realip_module — Taking the client address from a trusted proxy
- Bucket4j 8.23.0 Reference — Token bucket API and the Redis (Lettuce) integration
- AWS - Throttle requests to your REST APIs in API Gateway — Token bucket throttling and 429 responses
- GitHub Docs - Rate limits for the REST API — Published limits and rate limit headers
- Stripe - Scaling your API with rate limiters — Token buckets in Redis and failing open
- Cloudflare - How we built rate limiting capable of scaling to millions of domains — Sliding window counter accuracy
- AWS Architecture Blog - Exponential Backoff and Jitter — Retrying without synchronised clients
- ESET - How your Instagram account could have been hacked — The 2019 password reset rate limit bypass
- TechCrunch - Threat actor says he scraped 49M Dell customer addresses — The 2024 Dell partner portal scraping