Every public endpoint will eventually receive more requests than it should: a buggy client stuck in a retry loop, a scraper, a credential-stuffing attack against a login form, or simply a popular moment. Without limits, one heavy user can slow the service for everyone, run up infrastructure costs or exhaust a downstream dependency.
Rate limiting is the practice of capping how many requests a client may make in a given period. It sounds simple, and the first version usually is. The interesting part is in the details: how to count, how to treat bursts, what to key the limit on, how to enforce it across many servers and how clients should behave when they hit it. This guide walks through each.
What to limit, and by whom
A limit needs a key: the identity whose requests are counted. Common choices are an API key or user account, an IP address, or a combination, sometimes with separate limits per endpoint. Authenticated identities are the most reliable keys; IP addresses are useful for anonymous traffic but imperfect, because many users can share one address and one attacker can use many.
Different endpoints deserve different limits. A cheap read can tolerate far more traffic than an expensive search or report, and a login or password-reset endpoint needs strict limits to slow guessing attacks. Many systems combine a broad limit per client with tighter limits on sensitive or costly operations.
Fixed window counters
The simplest algorithm divides time into fixed windows — each minute, say — and counts requests per key within the current window. When the count reaches the limit, further requests are rejected until the next window begins. It is easy to implement with a counter that resets on the window boundary.
Its weakness is the boundary. A client can make the full allowance at the very end of one window and the full allowance again at the start of the next, briefly sending twice the intended rate. For many purposes that is acceptable; where bursts matter, smoother algorithms are better.
Sliding windows
A sliding window log keeps a timestamp for every request and counts how many fall within the last interval — the last sixty seconds, for example — at the moment a new request arrives. It enforces the limit precisely and has no boundary problem, but storing a timestamp per request can be expensive for high-volume clients.
A sliding window counter approximates the same behaviour cheaply. It keeps counts for the current and previous fixed windows and estimates the number of requests in the sliding interval by weighting the previous window’s count according to how much of it still overlaps. The result is much smoother than a fixed window, with only two counters per key.
The token bucket
The token bucket is the algorithm most often used when bursts should be allowed but sustained rates controlled. Imagine a bucket that holds a maximum number of tokens and is refilled at a steady rate. Each request takes a token; if the bucket is empty, the request is rejected or delayed.
The two parameters express two different promises: the refill rate is the long-term average a client may sustain, and the bucket size is how large a burst it may make after a quiet period. A client that has been idle can send a quick burst up to the bucket size, then is held to the refill rate. That matches real usage well — people and programs are bursty — while still protecting the service from sustained overload.
The leaky bucket
The leaky bucket is a close relative often described as a queue that drains at a constant rate. Requests enter the queue and are processed at a fixed pace; if the queue is full, new requests are dropped. Where the token bucket permits bursts, the leaky bucket smooths output into a steady stream.
That makes it useful for protecting a downstream system that cannot handle bursts at all, at the cost of added latency while requests wait in the queue. In practice the names are sometimes used loosely; what matters is whether you want to allow bursts or flatten them.
Enforcing limits across many servers
A limit counted separately on each of ten application servers is effectively ten times larger than intended, and it behaves unpredictably as load balancers move traffic around. Distributed rate limiting needs a shared store for counters — commonly an in-memory data store that supports atomic increments and expiry — or enforcement at a single layer such as an API gateway or edge proxy.
Atomicity matters: reading a counter, checking it and writing it back in separate steps creates a race in which concurrent requests all pass. Use atomic increment operations or scripts that run as a single step in the store. And decide what happens if the store is unavailable: failing open keeps the service up but removes protection, failing closed protects dependencies but blocks users. Choose deliberately per endpoint.
Telling clients what happened
The standard HTTP response for a client that has sent too many requests is status 429, Too Many Requests. Include a Retry-After header indicating how long the client should wait, either as a number of seconds or a date, so that well-behaved clients can back off precisely rather than guessing.
Many APIs also return headers describing the limit, the remaining allowance and when it resets, so that clients can pace themselves before hitting the wall; work on standardising such headers is ongoing, so document whatever format you use. A clear error body explaining the limit and linking to documentation saves your users and your support team a lot of confusion.
How clients should respond
If you are writing the client, treat a 429 as an instruction, not an error to retry immediately. Respect Retry-After when it is present. When it is absent, retry with exponential backoff — doubling the wait after each failure up to a maximum — and add random jitter so that many clients that failed at the same moment do not retry at the same moment and cause another spike.
Make retries safe, too. Retrying a request that creates something, such as a payment or an order, can duplicate it unless the API supports idempotency keys. And put a cap on total retries, so that a client facing a long outage gives up gracefully rather than hammering the service indefinitely.
Choosing limits that make sense
Set limits from data rather than guesses. Look at how real clients use the API — typical request rates, peaks, the heaviest legitimate users — and set limits comfortably above normal behaviour but well below what would harm the service. Start in a monitoring-only mode that logs who would have been limited, review the results, then enforce.
Revisit limits as usage grows, and offer a route for legitimate users who need more, such as higher limits for paid plans or on request. Limits that block real customers without explanation create support burden and churn; limits that are too generous provide no protection when you need it.
Where rate limiting stops helping
Rate limiting controls how fast a single identity can act, but large distributed attacks spread requests across many addresses and accounts, each staying under the limit. Defending against those needs additional layers: network-level protection, bot detection, challenges for suspicious traffic and capacity planning.
Rate limiting is also not a substitute for making expensive operations efficient, for authentication and authorisation, or for proper queueing of heavy work. It is a guard rail that keeps a healthy system healthy under pressure, not a cure for a system that cannot handle its normal load.
Protecting login and password-reset endpoints
Authentication endpoints need limits keyed on more than one thing. Limiting by IP address alone lets an attacker spread guesses across many addresses; limiting by account alone lets an attacker lock a real user out simply by failing logins for that account on purpose. A common pattern combines a per-address limit, a per-account limit that slows rather than locks — growing delays after repeated failures — and broader monitoring for many failures across many accounts from related sources.
Password-reset and verification-code endpoints deserve the same care, because each request may send an email or a text message that costs money and can be used to harass someone. Limit how often a reset can be requested for one address, keep codes short-lived and single-use, cap the number of guesses per code, and return the same response whether or not the account exists, so that the endpoint does not reveal which addresses are registered.
Testing your rate limiter
Rate limiting code is easy to get subtly wrong, so test it directly. Unit-test the algorithm with a controllable clock rather than real time, so that you can step precisely across window boundaries and refill moments. Check the edges: exactly at the limit, one request over it, the first request after a reset, a long idle period followed by a burst, and many concurrent requests arriving at once against a shared counter.
Then test the behaviour end to end. Send a burst against a staging environment and confirm that the right requests are rejected, that 429 responses carry a sensible Retry-After value, and that the limit still holds when traffic is spread across several servers. Keep watching in production as well: a metric for rejected requests per endpoint makes problems visible, and a sudden rise can mean an attack, a broken client or a limit that no longer fits real usage.
In short
Choose a key for each limit, set different limits for cheap, expensive and sensitive endpoints, and pick an algorithm that matches the behaviour you want: fixed windows for simplicity, sliding windows for smoothness, the token bucket for controlled bursts and the leaky bucket for a steady flow.
Enforce limits atomically in a shared store or at the edge, return 429 with Retry-After and clear documentation, and make clients back off with jitter and retry safely. Set limits from real usage, monitor before enforcing, and remember that rate limiting is one layer of protection among several.