Rate Limiting — API

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…

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

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."}

Three ways to count

In all three ways the cap is the same: 5 requests per 60 seconds. Only the way of counting differs.

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!" });
});

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);

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?

⚠️ Limiters that leak, or block everyone

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/.

What you will learn