Nov 26, 2026
Your API has no rate limit — one caller is all it takes
An endpoint I left open took hundreds of thousands of calls from a caller I couldn't identify, and it answered every one of them. A rate limit is the cheapest protection an API has — here's the algorithm to pick and the 429 that makes it work.
I found out one of my own endpoints had no rate limit the way you always find these things out: from the logs, after the fact. SensorGrid has a public dashboard endpoint I left open, and it had taken 421,000 calls from a caller I couldn't identify. The endpoint kept answering every one of them. Nothing crashed, nothing alerted, and that is exactly the problem — an API with no rate limit fails quietly, by getting slower and more expensive for everyone else, until the day it fails loudly.
A rate limit answers one question per request: has this caller already used its allowance? Without it, one caller is all it takes. It does not have to be an attacker. A scraper, a client stuck in a retry loop, a dashboard widget polling every second from a hundred open tabs — each of them is just a caller that never stops, and your database and your bill cannot tell the difference between that and a real attack.
Fixed window: the simple one, with a hole at the edge
The simplest limiter is a fixed window. Pick a window — say, 60 seconds — keep one counter per caller, and reset it when the window rolls over.
// 100 requests per minute, per IP
const hits = new Map<string, { count: number; windowStart: number }>();
function fixedWindow(key: string, limit = 100, windowMs = 60_000): boolean {
const now = Date.now();
const entry = hits.get(key);
if (!entry || now - entry.windowStart >= windowMs) {
hits.set(key, { count: 1, windowStart: now });
return true;
}
if (entry.count >= limit) return false;
entry.count += 1;
return true;
}
It works, and it has one hole worth knowing about: the window resets on a hard clock edge. A caller can send the full 100 requests at 00:00:59 and another full 100 at 00:01:00 — twice the limit in two seconds. For a coarse quota on a tolerant endpoint, that is fine. For a limit that has to mean what it says, it is not.
Sliding window: count the last 60 seconds, not this minute
The sliding window fixes the edge by counting requests in the trailing window — the last 60 seconds from now, whenever now is. The exact version keeps a timestamp for every accepted request, drops the ones older than the window, and counts what is left. It is precise, and it costs one stored entry per request.
The cheaper version, the sliding window counter, keeps two numbers — the previous window's count and the current one — and weights the previous count by how much of it still overlaps the trailing window. Two counters, near-exact enforcement, and it is the default most large APIs actually run.
Token bucket: my default
The token bucket is the one I reach for. A bucket holds up to capacity tokens and refills at a steady rate. Each request takes one token. An empty bucket means the request is refused.
type Bucket = { tokens: number; updatedAt: number };
function tokenBucket({ capacity, refillPerSecond }: { capacity: number; refillPerSecond: number }) {
const buckets = new Map<string, Bucket>();
return (req: any, res: any, next: () => void) => {
const key = req.ip ?? "unknown";
const now = Date.now();
const bucket = buckets.get(key) ?? { tokens: capacity, updatedAt: now };
const elapsed = (now - bucket.updatedAt) / 1000;
bucket.tokens = Math.min(capacity, bucket.tokens + elapsed * refillPerSecond);
bucket.updatedAt = now;
if (bucket.tokens < 1) {
const retryAfter = Math.ceil((1 - bucket.tokens) / refillPerSecond);
res.set("Retry-After", String(retryAfter));
return res.status(429).json({ error: "Too many requests" });
}
bucket.tokens -= 1;
buckets.set(key, bucket);
next();
};
}
What makes it the right default is that it separates two things you actually want to control independently. The capacity is the burst size — how far a client may deviate from the average in the short term. The refill rate is the sustained rate — what the client averages over a long period. A dashboard that loads ten widgets at once and then goes quiet is bursty, not abusive, and a token bucket lets that shape through while still capping the long-run average. A fixed window would punish the burst; a leaky bucket would smooth it into a queue and add latency to every request.
What to key on, and what to send back
The key is who gets throttled together, so choose it per endpoint. Authenticated traffic gets keyed by API key or user — that is the only key that survives a shared IP. Login, sign-up, and password reset get keyed by IP, and get a much tighter limit than the rest of the API: five attempts per fifteen minutes per IP makes credential stuffing economically pointless, and a real user almost never notices. Behind a proxy, configure Express's trust proxy with care — trusting the left-most X-Forwarded-For entry lets a client forge its own IP.
The response matters as much as the count. A rejection is a 429 Too Many Requests with a Retry-After header in seconds, telling the client when it may try again. Send the rate limit headers on every response, not just the rejections, so a well-behaved client can back off before it hits the wall. A 429 without Retry-After is a retry storm waiting to happen: the client has no idea when to come back, so it guesses, and usually guesses "right now."
For a single Node instance, express-rate-limit is the five-minute version of all of this:
import rateLimit from "express-rate-limit";
const apiLimiter = rateLimit({
windowMs: 60_000,
limit: 120,
standardHeaders: "draft-8",
legacyHeaders: false,
});
app.use("/api", apiLimiter);
const authLimiter = rateLimit({
windowMs: 15 * 60_000,
limit: 5,
standardHeaders: "draft-8",
legacyHeaders: false,
});
app.use("/api/auth", authLimiter);
What this does not fix
An in-memory limiter lives in one process. The moment you run two instances behind a load balancer, each one holds its own counters, and your real limit doubles — or worse, splits unevenly. When the limit is tight compared to normal traffic, or the instance count changes under autoscaling, the counter has to live somewhere every instance can see, which in practice means Redis and an atomic increment. That is a real step up in complexity, and it is the step most small APIs can defer: start per instance, and move to a shared store when the limit actually matters.
Per-IP limits also break where many users share one address — an office, a university, a mobile carrier — so never use IP as the only key for authenticated traffic. Do not rate-limit your own health checks, or your load balancer will declare the service dead during a traffic spike. And a rate limit does not fix a slow query: it buys time and protects everyone else while you fix the query. It is a guardrail, not a performance plan.
The fix for my open endpoint cost less than an hour, and most of that was reading the logs. The expensive version of this lesson is the one I already paid for: finding out from 421,000 calls that nobody was watching the door.