Skip to main content

API Rate Limiting

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 perExampleStrength and weakness
IP address10 login attempts a minute per addressWorks before login. Attackers can rotate addresses, and many users can share one address behind a company or mobile network.
API key or client1,000 requests a minute per keyFair between customers and easy to put on a plan. Says nothing about which user is acting.
User or account5 OTP checks per account per 10 minutesCannot be bypassed by changing address. Needs care so attackers cannot lock real users out.
Endpoint or action3 password reset SMS per number per hourPuts 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

ControlWhat happens over the limitTypical periodExample
Rate limitingThe request is rejected, usually with 429Seconds to minutes100 requests a minute per key
ThrottlingThe request is delayed or queued, then servedSecondsRequests above 10 a second wait their turn
QuotaRejected until the period renews or the plan changesDays to months50,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.

AlgorithmHow it countsBurstsState per clientGood for
Fixed windowOne counter per window, such as per minute, reset at the boundaryUp to twice the limit across a boundary: the end of one window and the start of the nextOne counterSimple quotas
Sliding window logStores the time of every request and counts those within the last windowNone: exactOne entry per requestLow limits that must be exact, such as login
Sliding window counterWeights the previous window's count by how much of it still overlaps, and adds the current countSmoothed, approximateTwo countersHigh-volume APIs
Token bucketTokens refill at a steady rate up to a capacity; each request takes oneAllowed up to the capacityToken count and last refill timeMost APIs
Leaky bucketRequests drain from a queue at a fixed rate; overflow is droppedSmoothed outQueue levelProtecting a backend that needs an even rate
Token bucket: tokens refill at a steady rate, each request takes a token, and requests that find the bucket empty get HTTP 429 Refill: 1 token every 6 seconds Capacity: 10 tokens (the burst) Request Token available: served Bucket empty: 429 + Retry-After
A token bucket with capacity 10 and a refill of 10 tokens a minute: a client can send 10 requests at once, then one every six seconds.

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

LayerWhat it can seeBest used for
CDN or WAFIP address, path, headers, countryStopping floods early and cheaply, before they reach your servers
API gateway or reverse proxyAPI key, client ID, route, planPer-key and per-plan limits, the same for every service behind it
ApplicationThe user, the account and the business actionOTP 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/login that misses /api/Login, /api/login/, /api/v1/login or 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

  1. 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.
  2. Set the general limit above normal. A few times the busiest normal client leaves room for real bursts without letting a script run free.
  3. 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.
  4. Allow short bursts. Apps load several resources at once. A token bucket's capacity, or nginx's burst, absorbs this.
  5. 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.
  6. Roll out in log-only mode first, then enforce, and review the 429s after each release.
  7. 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.

SignalWhat it can mean
A rise in 429s for one key or accountA buggy client, or someone testing your limits
Many accounts each staying just under the limitA distributed attack spread to avoid it
Many addresses failing logins for the same accountGuessing with rotated addresses
One account reading far more records than its peersScraping, as in the Dell case
SMS, email or AI spending above normalCost 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

There is no single number. Measure how many requests a normal client makes to each endpoint, set the general limit a few times above that, and set much lower limits on sensitive or costly actions such as login, OTP checks, password resets and SMS sending. Public APIs publish theirs: GitHub, for example, allows 60 requests an hour without authentication and 5,000 an hour for an authenticated user.

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.

Only in part. Per-client limits stop one client from overwhelming an endpoint, but a DDoS attack spreads traffic over thousands of sources, each staying under the limit, and a large flood can fill your network link before any limiter sees it. Rate limiting is one layer, alongside a CDN or DDoS protection service and capacity planning.

Weak ones can. The common causes are counting by IP address alone (attackers rotate addresses), trusting a client-supplied 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.

A token bucket allows short bursts up to its capacity and then holds clients to the refill rate, which suits most APIs, where real clients send bursts. A leaky bucket processes requests at an even rate, which suits protecting a backend that cannot absorb bursts. AWS API Gateway, Stripe and Bucket4j use token buckets; nginx describes its limit_req module as a leaky bucket.

They are close, and many products use the words interchangeably. Strictly, rate limiting rejects requests over the limit, while throttling slows them down, by queueing or delaying them, so they still complete. A quota is a larger allowance over a long period, such as requests per month on a paid plan.

Sources and further reading