Networking

What Is Rate Limiting? How It Works and Why Servers Use It

Rate limiting is a cap on how many requests a client can make to a server in a given amount of time. When a client goes over the cap, the server rejects or delays the extra requests, usually answering with HTTP status 429 "Too Many Requests".

RFC 6585 defines 429 as meaning "the user has sent too many requests in a given amount of time", and says the response may include a Retry-After header telling the client how long to wait. This article explains why servers do it, how the common methods work, and how to configure a basic limit in nginx.

Why servers use rate limiting

A server has finite CPU, memory, database connections and, often, a bill attached to each call. Without a cap, one misbehaving client can use more than its share. OWASP's API Security Top 10 recommends rate limiting as the core control against unrestricted resource consumption, and lists these specific cases:

  • Protecting capacity. A buggy script that retries in a tight loop can take down an endpoint for everyone else.
  • Slowing guessing attacks. OWASP says to also limit how often one client can run a sensitive operation, with the examples of validating a one-time password (OTP) and requesting password recovery.
  • Controlling cost. OWASP's example is a "forgot password" flow that sends an SMS for each request. A script made tens of thousands of calls, and at $0.05 per SMS the provider costs grew into thousands of dollars within minutes.
  • Fair sharing. API providers set per-customer limits so that one customer's traffic does not crowd out the others. Rate limit error 429 in LLM APIs shows how that looks from the client side.

How rate limiting works

Every rate limiter answers the same three questions.

  1. Who is the client? The server picks a key: an IP address, an API key, a logged-in user or a cookie. RFC 6585 states that it "does not define how the origin server identifies the user, nor how it counts requests", so this is up to each implementation. MDN notes that limits are typically based on the client's IP address, and tied to the user or application if requests are authenticated.
  2. What is being counted? Usually requests, but it can be a single route, the whole server, or a set of servers. Some systems also count tokens, bytes or a cost score.
  3. What happens when the limit is exceeded? Reject with an error, delay the request, or block the client for a fixed time.

Common counting methods

MethodHow it countsWeakness
Fixed windowA counter per key resets at the start of each interval, for example every minute.A client can send the full allowance at the end of one window and again at the start of the next, so up to twice the limit in a short span.
Sliding windowCounts requests over the last N seconds, measured back from the current moment.Needs more state per client than a single counter.
Token bucketA bucket refills at a steady rate; each request takes a token; an empty bucket means rejection.The bucket size has to be chosen: it sets how large a burst is allowed.
Leaky bucketRequests enter a bucket that drains at a fixed rate; requests that overflow are rejected.Smooths traffic, but queued requests wait longer.

The fixed-window weakness is plain arithmetic. With a limit of 100 requests per minute, a client can send 100 requests in the last second of minute one and 100 more in the first second of minute two: 200 requests in about two seconds, and every one of them is within the rules. Of the products documented here, nginx uses the leaky bucket (its documentation says "the limitation is done using the 'leaky bucket' method").

What a rate-limited response looks like

MDN gives this example of a server rejecting a client that went over its requests-per-minute threshold:

HTTP/1.1 429 Too Many Requests
Content-Type: text/html
Retry-After: 3600

<html lang="en-US">
  <head>
    <title>Too Many Requests</title>
  </head>
  <body>
    <h1>Too Many Requests</h1>
    <p>You're doing that too often! Try again later.</p>
  </body>
</html>

Retry-After: 3600 means the client may try again after 3,600 seconds (60 minutes). MDN documents two formats for the header: a number of seconds (Retry-After: 120) or an HTTP date (Retry-After: Wed, 21 Oct 2015 07:28:00 GMT). The header is optional on a 429, so a client cannot rely on it being there.

Not every server uses 429. nginx's limit_req module rejects with 503 unless you set limit_req_status to something else.

How to set up rate limiting in nginx

This is the example from the nginx documentation. The first line defines a shared memory zone keyed on the client IP address; the second applies it to one location:

http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

    server {
        location /search/ {
            limit_req zone=one burst=5;
        }
    }
}

What each part does, according to the nginx docs:

  • $binary_remote_addr is the key, the client address in a compact form (4 bytes for IPv4, 16 for IPv6). Requests with an empty key are not counted.
  • zone=one:10m names the zone one and gives it 10 megabytes. On 64-bit platforms one megabyte holds about 8,000 states.
  • rate=1r/s allows an average of 1 request per second. Use r/m for slower rates: 30r/m is half a request per second.
  • burst=5 lets up to 5 excess requests queue. They are delayed so they are processed at the defined rate. Anything beyond the burst is rejected. The default burst is zero.
  • Adding nodelay (limit_req zone=one burst=5 nodelay;) processes burst requests immediately instead of delaying them.
  • limit_req_status 429; changes the rejection code from the default 503.

After editing the config, test it with nginx -t and reload nginx. To see the effect, send a quick series of requests to the path from one machine and check which come back with the rejection status.

Rate limiting at the network edge

You can also apply limits before traffic reaches your server. Cloudflare's rate limiting rules, for example, have a counting key, a period, a request threshold and a mitigation timeout. On the Free plan, requests are counted by IP only, the period is fixed at 10 seconds, and the mitigation timeout is 10 seconds; paid plans allow more characteristics and longer periods and timeouts. Cloudflare also notes that counting is not exact: counter updates can lag by up to a few seconds, so some excess requests may still reach your origin. Plan limits change, so check the current documentation before relying on these numbers.

If you hit a rate limit as a client

  • Read the Retry-After header and wait at least that long.
  • If there is no header, wait and retry with an increasing delay instead of retrying immediately. Retrying at once usually keeps you over the limit.
  • Reduce how often you call: batch work, cache responses, and cap the number of requests in flight.
  • If you are a person rather than a script, such as a login or password-reset page blocking you, wait out the window. Repeated attempts normally extend the block.

Limits of rate limiting

A limit keyed on IP address can punish many users who share one address, such as an office or a mobile carrier's network, and does little against an attacker who spreads requests across many addresses. OWASP also points out that limits must cover work inside a single request: in its GraphQL example, an attacker bypassed a per-request limit by packing many upload operations into one array-based request and exhausted the server's memory. A request count alone is not enough when one request can do a lot of work.

Frequently asked questions

What is the difference between rate limiting and throttling?
The terms overlap and are used loosely. Rate limiting usually means rejecting requests above a threshold, typically with HTTP 429. Throttling usually means slowing requests down so they are processed at a set rate. nginx's limit_req does both: it delays excess requests up to a burst size and rejects anything beyond that.
What happens when you hit a rate limit?
Most HTTP servers reject the request, commonly with status 429 Too Many Requests, and may add a Retry-After header saying how long to wait. Some servers return a different code (nginx's limit_req defaults to 503) or silently delay the request instead.
How is a client identified for rate limiting?
The HTTP standard does not say. Common keys are the client IP address, an API key or login, or a cookie. MDN notes that limits are typically based on IP address, and tied to the user or application when requests are authenticated. Cloudflare's Free and Pro plans count by IP only.
Can rate limiting stop a DDoS attack?
It helps against simple floods from a few addresses, but a per-IP limit does little when an attack is spread across very many addresses. Treat it as one layer next to other protections, not as a complete defence.

Sources