Any endpoint reachable from the internet will eventually be called far more often than you planned for. Sometimes it is an attacker trying passwords. Sometimes it is a scraper. Quite often it is a well-meaning customer whose script has a bug and calls your API in a tight loop.
A rate limiter decides how many requests a client may make in a given period and rejects the rest. It protects your infrastructure, stops one noisy client from degrading service for everyone else, and puts a ceiling on costs that grow with usage.
There are four common algorithms, and each makes a different trade-off.
Fixed window counter
Count requests per client in fixed time windows, for example per calendar minute. Once the count passes the limit, reject everything until the next window starts.
key = ratelimit:{client}:{current minute}
INCR key
EXPIRE key 60 (only when the key is new)
reject if the count is above 100
It is simple and needs one counter per client. The weakness is the boundary. A client can send 100 requests at 12:00:59 and another 100 at 12:01:00: that is 200 requests in two seconds, without ever breaking a "100 per minute" rule.
Use it when rough limits are good enough, such as protecting an internal endpoint from a runaway loop.
Sliding window log
Store a timestamp for every request and count only those from the last 60 seconds. In Redis, a sorted set per client works well: add the current timestamp, remove entries older than the window, and count what is left.
This is exact. There is no boundary problem, because the window moves with every request. The cost is memory: a client allowed 10,000 requests an hour can mean 10,000 stored timestamps for that client alone.
Use it when limits are low and accuracy matters, such as login attempts and password resets.
Sliding window counter
A practical middle ground. Keep fixed window counters for the current and the previous window, and estimate the rolling count by weighting the previous window by how much of it still overlaps:
estimate = current_count + previous_count * (1 - elapsed_fraction)
If a client made 80 requests last minute and 30 so far this minute, and the current minute is 25 percent over, the estimate is 30 + 80 × 0.75 = 90. It needs two counters per client and is accurate enough for nearly every API.
Token bucket
Each client has a bucket that holds up to N tokens. Tokens are added at a steady rate, say 10 per second, up to the bucket's capacity. Every request takes one token, and a request that finds the bucket empty is rejected.
The token bucket is the most widely used algorithm for APIs because it separates two things clients care about: the sustained rate, which is the refill rate, and the allowed burst, which is the capacity. A client that has been quiet can send a quick burst, which matches how real applications behave, while the long-run average stays capped.
It needs only two values per client: the current token count and the time of the last refill. Tokens are calculated on each request instead of being added by a timer.
The leaky bucket is a close relative. Requests join a queue that drains at a fixed rate, so the output is perfectly smooth. That suits traffic shaping in front of a fragile downstream system better than it suits public APIs, where clients usually prefer a quick rejection to a long wait in a queue.
How they compare
| Algorithm | Allows bursts | Memory per client | Accuracy |
|---|---|---|---|
| Fixed window | Yes, up to 2x at window edges | One counter | Poor at boundaries |
| Sliding window log | No | One entry per request | Exact |
| Sliding window counter | A little | Two counters | Close approximation |
| Token bucket | Yes, up to capacity | Two values | Exact for its model |
A token bucket in Redis
When your API runs on more than one server, the limiter state has to be shared, and reading, updating and writing it must happen as one atomic step. A small Lua script executed by Redis does exactly that:
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill_per_ms = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local state = redis.call('HMGET', key, 'tokens', 'ts')
local tokens = tonumber(state[1]) or capacity
local last = tonumber(state[2]) or now
tokens = math.min(capacity, tokens + (now - last) * refill_per_ms)
local allowed = 0
if tokens >= 1 then
tokens = tokens - 1
allowed = 1
end
redis.call('HSET', key, 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', key, math.ceil(capacity / refill_per_ms))
return allowed
Call it with the client's key, the capacity, the refill rate per millisecond and the current time in milliseconds. If you pass the time in from your application servers, keep their clocks synchronised with NTP. The expiry means idle clients cost nothing: once a bucket would be full again, the key simply disappears.
Choosing what to count
The algorithm matters less than the key you count against.
- API key or user ID is the fairest choice for authenticated traffic. The limit follows the customer, not whichever network they happen to be on.
- IP address is the only option for anonymous endpoints such as login and sign-up, but use it with care. Many people can share one IP behind an office network or a mobile carrier. With IPv6, a single client often controls a whole /64 range, so count by the /64 prefix rather than by individual address.
- The real client IP. If your servers sit behind a load balancer or CDN, read the client address from the header your proxy sets, and only trust that header when the request came through the proxy. Anyone can send their own
X-Forwarded-For. - Endpoint cost. An expensive search or export deserves a tighter limit than a cheap read. Some APIs give each endpoint a token cost instead of counting every request as one.
Layering limits works well: a generous per-key limit for normal use, plus a strict per-IP limit on authentication endpoints to slow down credential stuffing.
Tell clients what happened
A rejected request should get 429 Too Many Requests with a Retry-After header saying how many seconds to wait:
HTTP/1.1 429 Too Many Requests
Retry-After: 12
Content-Type: application/json
{"error": "rate_limited", "message": "Limit of 100 requests per minute reached."}
Many APIs also send headers on every response so clients can slow down before they hit the limit. Older APIs use X-RateLimit-Limit and X-RateLimit-Remaining, and the IETF is standardising RateLimit and RateLimit-Policy headers for the same job. Whichever you choose, document it, so the people integrating with your API can build clients that back off politely instead of hammering you with retries.
Rate limiting is rarely the most interesting part of an API, but it is often what decides whether a traffic spike becomes an incident or a non-event.
Rate limiting in our OCPP platform
The OCPP Management Platform keeps its rate limit store per process, which is one of the reasons it deliberately runs as a single Node process today: with several processes, each would count requests separately and the effective limit would quietly multiply. The deployment configuration says so next to the setting. Questions like this come up in most of our systems integration and cloud deployment and DevOps projects.



