You ask for an OTP code (a one-time code to log in), but it never arrives. You tap "Resend". The button goes grey and says "Try again in 60 seconds". The app isn't broken. Your requests are capped on purpose: the server counts how many times you've asked.
A cap like this is called rate limiting: a rule for how many requests one client may send in a span of time, for example 5 requests per minute. Think of an office coffee machine that gives each employee 5 cups per hour. The sixth cup is refused, and the screen says "try again in 12 minutes". The coffee machine has a cap (5 cups), a span (1 hour), a refusal, and a note on when to try again. An API with rate limiting has these four things too, for requests.
Why an API needs a cap
- Holding back abuse. Without a cap, someone can try thousands of passwords a minute at
POST /login. - Fair for everyone. One script calling the API nonstop can make the server slow for everyone.
- Cost. Every request uses CPU (the server's processor), database queries, and the quota of other services you pay for.
The answer when the cap is passed: 429
Say the cap is 5 requests per minute. The sixth request in a minute is answered like this:
HTTP/1.1 429 Too Many Requests
Retry-After: 42
RateLimit-Limit: 5
RateLimit-Remaining: 0
RateLimit-Reset: 42
Content-Type: application/json
{"error": "Too many requests, please try again later."}
429 Too Many Requestsis the status made for "too many requests". It is not403(forbidden) or500(the server broke).- The header
Retry-After: 42tells the client: wait 42 seconds before trying again. - The
RateLimit-*headers (headers whose names start withRateLimit-) come with every answer,200ones included.RateLimit-Limitis the cap,RateLimit-Remainingthe requests still allowed, andRateLimit-Resethow many seconds from now the quota (the requests allowed) recovers. - Many APIs use the older names:
X-RateLimit-Limit,X-RateLimit-RemainingandX-RateLimit-Reset. Careful: on GitHub,X-RateLimit-Resetholds a Unix time (the number of seconds since 1970), not the seconds left. Read the API's docs. - The
RateLimit-*headers have no official standard yet.RateLimit-Limit,RateLimit-RemainingandRateLimit-Resetcome from an older draft (a proposed standard) by the IETF, the group that writes internet standards. Its newest draft (May 2026) uses two other headers:RateLimit-PolicyandRateLimit, for exampleRateLimit: "default";r=0;t=42. What every client understands is still429withRetry-After.
Three ways to count
In all three ways the cap is the same: 5 requests per 60 seconds. Only the way of counting differs.
- Fixed window: a window (a span of counting time) that is fixed. There is one counter for each minute on the clock. When the minute changes, the counter goes back to 0. It's the simplest, and light on memory.
- Sliding window (a window that moves): the server counts the requests accepted in the last 60 seconds. So the server keeps the time of each request.
- Token bucket: picture a bucket holding 5 tokens. A token here isn't a login token: one token is the right to send one request. Each request takes 1 token, and 1 new token is added every 12 seconds (60 / 5). A full bucket allows 5 requests at the same time. After that, the pace is 1 request per 12 seconds.
Try this scenario: 5 requests at second 55, then 5 more at second 60. Before you look at the table, guess: with a fixed window, how many requests get accepted?
| Algorithm | Second 55 (5 requests) | Second 60 (5 requests) | Total accepted |
|---|---|---|---|
| Fixed window | 5 accepted (minute 0) | 5 accepted (minute 1, a new counter) | 10 in 5 seconds |
| Sliding window | 5 accepted | 5 refused (the last 60 seconds already hold 5) | 5 |
| Token bucket | 5 accepted, bucket empty | 5 refused (only 5/12 of a token refilled) | 5 |
So with a fixed window, 10 requests are accepted within 5 seconds, twice the cap. That's its weakness when the minute changes. Sliding window and token bucket don't have that hole, but there is a price: the server has to store more data.
Writing a limiter yourself (fixed window)
A limiter is code that caps requests. Here is a fixed window limiter for GET /api/data, 5 requests per minute per client:
const WINDOW_MS = 60 * 1000; // 1 minute, in milliseconds
const LIMIT = 5;
const counters = {}; // "ip:start of minute" -> request count
app.get("/api/data", (req, res) => {
const now = Date.now();
const windowStart = Math.floor(now / WINDOW_MS) * WINDOW_MS;
const key = (req.ip ?? "local") + ":" + windowStart;
counters[key] = (counters[key] ?? 0) + 1;
const resetIn = Math.ceil((windowStart + WINDOW_MS - now) / 1000);
res.set("RateLimit-Limit", String(LIMIT));
res.set("RateLimit-Remaining", String(Math.max(LIMIT - counters[key], 0)));
res.set("RateLimit-Reset", String(resetIn));
if (counters[key] > LIMIT) {
res.set("Retry-After", String(resetIn));
return res.status(429).json({ error: "Too many requests, please try again later." });
}
res.json({ data: "Hello!" });
});
Date.now()gives the time now in milliseconds.windowStartis the start of this minute: now, rounded down to a multiple of 60,000 ms (1 minute).keyjoins the client's IP (req.ip, the number that identifies its device on the internet) and the start of its minute. So each client has its own counter, and a new minute starts from 0 automatically.??takes the right side when the left side doesn't exist, socounters[key] ?? 0is 0 for a new key.resetInis the seconds left until the next minute. The same value goes intoRateLimit-ResetandRetry-After.returnbeforeres.status(429)stops the handler, sores.json({ data: "Hello!" })isn't sent as well.
This table shows the requests from one client within one minute:
| Request no. | counters[key] |
Status | RateLimit-Remaining |
|---|---|---|---|
| 1 | 1 | 200 | 4 |
| 5 | 5 | 200 | 0 |
| 6 | 6 | 429 | 0 |
With express-rate-limit
In a real Express app you'd usually use the express-rate-limit package, a ready-made library for rate limiting. This code caps each IP at 100 requests per 15 minutes, on every path that starts with /api/:
const rateLimit = require("express-rate-limit");
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes = 900,000 ms
limit: 100, // older versions write it max: 100
standardHeaders: "draft-6", // send RateLimit-Limit, -Remaining, -Reset
legacyHeaders: false, // no X-RateLimit-*
});
app.use("/api/", limiter);
windowMsis always in milliseconds: 15 minutes =15 * 60 * 1000= 900,000.limit(its older name ismax) is the number of requests each IP may send in one window.- A request over the cap gets
429automatically, with the messageToo many requests, please try again later.
The exercise's tester doesn't have this package. So in the exercise, you write the counter yourself, as in the fixed window example above.
🤔 Per IP, per user, or per API key?
- Per IP needs no login. But one office, or one mobile network, can share the same IP, so everyone there shares one cap. If your server sits behind a proxy (a server in the middle that passes requests on), set
app.set("trust proxy", 1). Thenreq.ipholds the client's IP, not the proxy's. - Per user or per API key is fairer for endpoints that need a login.
- Login is best capped per email and per IP, because an attacker can switch IPs.
- A counter in memory, like the
countersobject above, is lost when the server restarts and isn't shared with other servers. With more than one server, keep the counters in Redis (an in-memory database many servers can share).
⚠️ Limiters that leak, or block everyone
- Forgetting
returnafter429. The handler keeps running and sends a second answer. windowMsin seconds.windowMs: 60means 60 milliseconds, not 1 minute. Write60 * 1000.- One counter for every client. Without the IP in
key, one greedy client uses up the cap and blocks everyone. - A client that ignores
Retry-After. Retrying nonstop only adds more429s. Wait as long as the number from the server says.
TL;DR: Rate limiting caps the number of requests from one client in a span of time. A request over the cap is answered 429 Too Many Requests with the header Retry-After (how many seconds the client must wait). The headers RateLimit-Limit (the cap), RateLimit-Remaining (requests left) and RateLimit-Reset (seconds until the count restarts) come with every answer. They come from an IETF draft (a proposed internet standard), not an official standard. Their older names are X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset. A fixed window (one counter per minute) is the simplest, but can accept 2x the cap when the minute changes. A sliding window counts the last 60 seconds. A token bucket uses a bucket of tokens (rights to send a request): they can all be used at the same time, then the bucket refills at a steady pace. In the express-rate-limit library, windowMs is in milliseconds (15 * 60 * 1000 = 900,000) and limit (formerly max) is the request count. Keep counters per IP (a device's number) or per user, and return after 429.
⚡ Why an API needs a cap
Meaning: Rate limiting caps the number of requests from one client in a span of time, for example 5 requests per minute. Without a cap, someone can try thousands of passwords a minute at POST /login. One script calling the API nonstop can make the server slow for everyone. And every request costs money.
⚡ Past the cap: 429
Meaning: A request past the cap is answered with the status 429 Too Many Requests, not 403 (forbidden) or 500 (the server broke). The header Retry-After: 42 tells the client: wait 42 seconds first. The header RateLimit-Remaining, which comes with every answer, names the requests still allowed.
⚡ A fixed window leaks at the minute boundary
Guess first: a fixed window uses one counter for each minute on the clock. The cap is 5 requests per 60 seconds. 5 requests come at second 55, then 5 more at second 60. How many get accepted?
Ten in 5 seconds, twice the cap. The minute changes at second 60, so the counter starts from 0 again.
Meaning: A fixed window has a hole when the minute changes. A sliding window (it counts the last 60 seconds) and a token bucket (a bucket of rights to send a request) don't have that hole. But the server has to store more data.
⚡ With express-rate-limit
Write:
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes = 900,000 ms
limit: 100, // older versions write it max: 100
});
app.use("/api/", limiter);
Meaning: rateLimit comes from the express-rate-limit package, a ready-made library for rate limiting. windowMs is the span of time, in milliseconds. limit is the number of requests each IP (the number that identifies a device on the internet) may send in that span. So this cap is 100 requests per 15 minutes, on every path that starts with /api/.