No. 31API9 min read2,388 words
API rate limiting: algorithms and strategies that scale
API rate limiting for teams running more than one server: choosing the key and algorithm, where to enforce limits, and an atomic Redis limiter you can copy.
- Written by
- Lazy Devs
- Published
- Updated
- Sources
- Cited inline

Key takeaways ยท 05
The short version
- 01Choose the rate limit key before the algorithm: IP or device for abuse, API key or user ID for plan limits, and one global budget for protecting a fragile downstream service.
- 02A sliding window counter is the best default for most APIs: two counters per key, no double-quota burst at window boundaries, and cheap to run in Redis.
- 03Use a token bucket when clients legitimately burst; it caps the sustained rate while letting a quiet client spend a saved-up reserve.
- 04Enforce limits in two layers: a coarse IP-based limit at the edge or WAF to absorb floods, and a precise application limit that knows plans and API keys.
- 05With more than one server, keep counters in Redis and make check-and-increment atomic with a Lua script, then decide deliberately whether the limiter fails open or closed.
On this page ยท 09
API rate limiting that scales comes down to four decisions: what you key the limit on, which algorithm you count with, where in the stack you enforce it, and where the counters live once you run more than one server. Get those right and a limiter is a few dozen lines of code. Get them wrong and it either blocks your best customers or does nothing when you are actually under attack.
Rate limiting feels trivial until you have more than one server. A counter in a hash map works on your laptop and falls apart the moment a load balancer spreads traffic across three instances. This is a walkthrough of the algorithms worth knowing, where to put the limiter, and how to make limits hold up when you scale horizontally.
What you are actually protecting
Before picking an algorithm, get clear on what the limit is for. The answer changes the design.
You might be protecting a fragile downstream resource, like a third-party API that charges per call or a database that buckles under a write storm. You might be defending against abuse: credential stuffing on a login route, scrapers hammering your search endpoint, someone enumerating IDs. Or you might be enforcing a plan, where a free tier gets a small hourly allowance and a paid tier gets far more. OWASP lists unrestricted resource consumption among the top API security risks precisely because missing limits turn into both outages and surprise bills. AI features sharpen the cost side, since every model call is billed, which is why per-customer limits are part of building an AI SaaS.
These goals need different keys:
| Goal | Key on | Typical scope | Watch out for |
|---|---|---|---|
| Abuse and attack protection | IP address, device, or IP plus route | Login, signup, password reset, search | Many legitimate users share one IP behind offices and mobile carriers |
| Fairness and plan limits | API key, user ID or tenant ID | Whole API, or per endpoint group | Does nothing for unauthenticated traffic |
| Protecting a downstream dependency | One global key per dependency | Calls to a payment, email or AI provider | One noisy customer can starve everyone else |
| Expensive operations | User ID plus operation | Exports, report generation, AI calls | Count cost, not just requests |
Mixing these up is the most common mistake we see. A per-user limit does nothing to stop a botnet hitting your login page, and a strict per-IP limit punishes a whole company behind one NAT. Most real systems need two or three of these layers at once.
The rate limiting algorithms, ranked by how often you should use them
Stripe's engineering write-up on scaling an API with rate limiters is a good real-world account of layering limiters with a token bucket in Redis. Here is the practical version of the options.
Sliding window counter: the default
The sliding window fixes the fixed window's boundary burst (described below) by weighting the previous window. You take the current window's count, add a fraction of the previous window's count based on how far into the current window you are, and compare that to the limit. It is an approximation, but a good one, and it costs only two counters per key. This is our default for API work: cheap, fair, and free of the fixed window's cliff.
Token bucket: when bursts are legitimate
A bucket holds tokens up to a maximum. Tokens refill at a steady rate, and each request spends one (or several, for expensive calls). If the bucket is empty, the request is rejected. The useful property is that it allows bursts: a client that has been quiet builds up a reserve and can spend it at once, which matches how real clients behave, like a mobile app syncing after it reconnects. Use it when you want to permit short spikes but cap the sustained rate.
Fixed window: coarse protection only
You count requests in a clock-aligned window: requests between 10:00:00 and 10:00:59 go in one bucket, and the next minute starts fresh. It is one counter and one expiry, which is why it is the first thing everyone reaches for.
The flaw is the boundary. A client can send the full quota at 10:00:59 and the full quota again at 10:01:00, so you allow double the limit across a two-second span. For blunt protection that is fine. For anything you actually care about, it leaks.
Sliding window log: exact, but expensive
Store a timestamp for every request in a sorted set, drop entries older than the window, and count what is left. It is perfectly accurate, but memory grows with the limit, so a key allowed 10,000 requests an hour stores up to 10,000 entries. Use it only for low limits where precision matters, such as five password reset emails per hour.
Leaky bucket: smoothing output
Requests drain at a fixed rate regardless of how they arrive, which smooths traffic into a constant outflow. Reach for it when the thing downstream cannot tolerate bursts at all. In practice this is usually implemented as a queue with a fixed number of workers rather than as a request limiter, which is a pattern we cover in background jobs and queues.
| Algorithm | Allows bursts | Memory per key | Accuracy | Best for |
|---|---|---|---|---|
| Sliding window counter | Small, bounded | Two counters | Very good approximation | Default for APIs |
| Token bucket | Yes, up to bucket size | Token count and timestamp | Exact | Bursty clients, cost-weighted limits |
| Fixed window | Up to 2x at boundaries | One counter | Poor at edges | Coarse abuse protection |
| Sliding window log | No | One entry per request | Exact | Low, precise limits |
| Leaky bucket | No, output is smoothed | Queue | Exact | Feeding fragile downstream systems |
Where to enforce rate limits
Put the limiter as far out as you reasonably can. Every request you reject at the edge is a request that never touches your application code, your database or your bill.
- Edge, CDN or WAF. If your platform has a managed firewall, configure IP-based limits there first. Cloudflare, Vercel's firewall and most API gateways can drop abusive traffic before it reaches an instance. The catch is that edge rules usually key on IP and are coarse, so they handle floods well but cannot express plans.
- Request entry point. In Next.js 16,
middlewarehas been renamed toproxy, which runs before routes and is a reasonable place for a shared limiter across many routes. Keep it lean, since it sits in front of everything it matches. - Route handler or service layer. Per-user, per-key and per-operation limits need to know who the caller is and what plan they are on, and only your application knows that. This is where the precise limits live.
- Outbound calls. Limit your own calls to third-party APIs with a global key per provider, so a spike in your traffic does not get your account throttled or blocked.
The realistic setup is layered: a blunt edge limit to absorb attacks, and a precise application limit for fairness and billing. If you sell usage-based plans, the same counting infrastructure often feeds metering too, which we cover in usage-based billing for SaaS.
Making rate limits work across many servers
The core problem with horizontal scaling is shared state. Three instances each with a local counter means a client gets three times the limit, and the number drifts as the load balancer shuffles them around. You need a single source of truth, and Redis is the standard answer because it is fast and gives you atomic operations.
The trap is doing a read, then a write, in two round trips. Between those two calls another request can slip in, and your count is wrong under exactly the load where correctness matters. The fix is to make check and increment atomic. A Lua script runs on the Redis server as a single operation, so no other command interleaves.
Here is a sliding window limiter as a Lua script. Both window keys are passed in as KEYS and share a hash tag (the part in braces), so the script also works on Redis Cluster, where every key a script touches must live on the same node.
import Redis from "ioredis";
const redis = new Redis(process.env.REDIS_URL!);
// KEYS[1] = current window key, KEYS[2] = previous window key
// ARGV[1] = limit, ARGV[2] = window in ms, ARGV[3] = ms elapsed in current window
const slidingWindow = `
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local elapsed = tonumber(ARGV[3])
local curCount = tonumber(redis.call('GET', KEYS[1]) or '0')
local prevCount = tonumber(redis.call('GET', KEYS[2]) or '0')
local weighted = prevCount * (1 - elapsed / window) + curCount
if weighted >= limit then
return -1
end
redis.call('INCR', KEYS[1])
redis.call('PEXPIRE', KEYS[1], window * 2)
return limit - math.floor(weighted) - 1
`;
export async function rateLimit(identifier: string, limit: number, windowMs: number) {
const now = Date.now();
const current = now - (now % windowMs);
const previous = current - windowMs;
const tag = `rl:{${identifier}}`;
const remaining = (await redis.eval(
slidingWindow,
2,
`${tag}:${current}`,
`${tag}:${previous}`,
limit.toString(),
windowMs.toString(),
(now - current).toString(),
)) as number;
const resetSeconds = Math.ceil((current + windowMs - now) / 1000);
return { allowed: remaining >= 0, remaining: Math.max(remaining, 0), resetSeconds };
}And a route handler that uses it. It keys on the API key when present and falls back to the client IP, so anonymous and authenticated traffic get separate budgets.
import { NextRequest, NextResponse } from "next/server";
import { rateLimit } from "@/lib/rate-limit";
function clientIp(req: NextRequest) {
// x-forwarded-for can be a comma-separated list and is client-controlled
// unless your platform overwrites it. Trust only what your proxy sets.
const forwarded = req.headers.get("x-forwarded-for");
return forwarded?.split(",")[0]?.trim() ?? "unknown";
}
export async function POST(req: NextRequest) {
const apiKey = req.headers.get("x-api-key");
const identifier = apiKey ? `key:${apiKey}` : `ip:${clientIp(req)}`;
const { allowed, remaining, resetSeconds } = await rateLimit(identifier, 100, 60_000);
if (!allowed) {
return NextResponse.json(
{ error: { code: "rate_limited", message: "Too many requests" } },
{ status: 429, headers: { "Retry-After": String(resetSeconds) } },
);
}
const res = NextResponse.json({ ok: true });
res.headers.set("X-RateLimit-Remaining", String(remaining));
return res;
}In production, look up the API key first and key on the resolved account or tenant ID rather than the raw key, so a customer who rotates keys keeps one budget, and so invalid keys get rejected before they consume Redis memory.
Response headers and client behaviour
A limiter is only half the system. The other half is clients backing off correctly, and they can only do that if you tell them what is happening.
- Return 429, not 400 or 403. RFC 6585 defines
429 Too Many Requests, and retry libraries treat it as "slow down", not "give up". - Always send
Retry-Afterwith the real number of seconds until the window resets, not a hard-coded guess. - Expose remaining quota. The
X-RateLimit-*headers are a widespread convention (GitHub's REST API rate limit docs are a good model). The IETF is standardisingRateLimitandRateLimit-Policyfields in an HTTP API rate limit headers draft, so it is worth tracking. - Document the limits. Publish them per plan and per endpoint group, in the same place as your API design conventions.
On your own client side, when you call someone else's rate-limited API, retry with exponential backoff and jitter. AWS's timeouts, retries and backoff with jitter explains why random jitter matters: without it, every client that was throttled at the same moment retries at the same moment, and you get the spike again.
Failure modes that separate a real limiter from a toy
Decide what happens when Redis is down. If your limiter throws on a connection error and you have no fallback, a Redis blip takes down every rate-limited route. For most product endpoints, failing open (allowing the request when the limiter cannot be reached) is the right call, because a brief loss of limiting is less bad than a full outage. For a login route guarding against credential stuffing, you may want to fail closed. Make that choice per route, on purpose, and alert on it, rather than discovering it during an incident. Our web application security checklist covers the rest of login hardening.
Do not trust headers you did not set. If your app reads x-forwarded-for but sits behind a proxy that does not overwrite it, any client can claim any IP and get a fresh budget per request. Check what your hosting platform guarantees.
Watch the cost of the limiter itself. One Redis round trip per request is usually fine, but it is now in your hot path. Keep the script tight, set expiries so keys clean themselves up, use a short client timeout so a slow Redis does not stall every request, and run Redis in the same region as your application.
Count cost, not just requests. A request that triggers an AI call or a large export is not the same as a cheap read. A token bucket where expensive operations spend more tokens is often fairer than separate limits for everything.
Do not rate limit your own health checks and webhooks. Exempt internal traffic and known partner IPs explicitly, or your load balancer will mark healthy instances as dead during a spike.
A rate limiting rollout checklist
- List the routes that need protection and group them: auth, public read, write, expensive.
- Pick the key for each group using the table above.
- Turn on coarse IP limits at the edge.
- Add the application limiter in log-only mode first, and look at what it would have blocked.
- Set limits from real traffic, with generous headroom for your largest legitimate customers.
- Switch to enforcing, with
429,Retry-Afterand remaining-quota headers. - Dashboard and alert on 429 rates per key, so you notice both attacks and customers who have outgrown their plan.
Rate limiting that grows with you
Pick the key first (IP for abuse, API key or user for plans), use a sliding window unless you specifically need bursts, enforce limits at the edge and in the application, and move counters to Redis with an atomic Lua script the moment you have more than one server. Get those right and your limiter scales with the rest of the stack instead of becoming the thing that falls over first.
Rate limiting is a standard part of how we build APIs in our API and backend engineering work. If you want a second pair of eyes on where to draw your limits, or you are already seeing abuse in production, get in touch and we will take a look.
FAQ ยท 05 questions
Frequently asked questions
What is API rate limiting?
API rate limiting caps how many requests a client can make in a period of time, such as 100 requests per minute per API key. Requests over the limit are rejected with HTTP status 429 Too Many Requests. It protects your infrastructure from abuse and overload, keeps usage fair between customers, and enforces plan limits.
Which rate limiting algorithm is best?
For most web APIs, a sliding window counter is the best balance of accuracy, fairness and cost. Token bucket is better when you want to allow short bursts but cap the sustained rate. Fixed window is fine only for coarse protection, and leaky bucket suits feeding a downstream system that cannot handle bursts at all.
What HTTP status code should a rate limited request return?
Return 429 Too Many Requests, defined in RFC 6585, with a Retry-After header telling the client how many seconds to wait. Do not use 400 or 403, because clients and retry libraries treat those as permanent failures rather than a signal to slow down.
Should I rate limit by IP address or by user?
Usually both, for different reasons. IP limits are the only option for anonymous traffic like login and signup, but they punish many users behind one office or mobile carrier address. Limits on authenticated users or API keys are fairer and map to billing plans, but they do nothing against an attacker who has not logged in.
What happens to rate limiting if Redis goes down?
Your limiter has to choose. Failing open lets requests through when Redis is unreachable, which avoids an outage but briefly removes protection. Failing closed rejects requests, which is safer for login or payment routes but turns a Redis blip into downtime. Make the choice per route, on purpose, and alert when it happens.