Skip to Content
ZarexDocs

Rate limiting

Limit the number of requests a single visitor can make over a given period.

Rate limiting protects your routes from abuse: repeated login attempts, scraping, an overloaded API. Beyond the limit, the request is denied with a 429 response and a Retry-After header.

The problem

Without a limit, a single visitor can send as many requests as they want: try thousands of passwords on your login page, scrape your whole catalog, saturate an expensive API, or trigger hundreds of SMS and emails from your form, which you pay for.

What it stops

  • brute-force attacks and mass testing of stolen credentials;
  • mass scraping of your pages and prices;
  • form abuse: serial sign-ups, repeated SMS code requests;
  • a faulty client looping on your API.

When to use it

On sensitive routes with a strict limit (login, sign-up, forgotten password, code sending), and on the rest of the application with a wider limit.

Configuration

import { rateLimit } from "@zarex/express"; // or your framework's package

rules: [rateLimit({ max: 100, window: "1m" })],

Here, each visitor can make 100 requests per minute.

Options

OptionValuesDefaultRole
maxfrom 1 to 1,000,000requiredRequests allowed per window.
window"30s", "1m", "1h", "1d"… (366 days at most)requiredLength of the window.
algorithm"FIXED_WINDOW" · "SLIDING_WINDOW""FIXED_WINDOW"How the window is counted (see below).
characteristicslist of names (16 at most)["ip"]What identifies a visitor.
mode"LIVE" · "DRY_RUN" · "OFF""LIVE"Deny, only observe, or disable.

Fixed or sliding window

With max: 3 and window: "1m", both algorithms deny the 4th request of the minute. They differ on the rest:

FIXED_WINDOW (default)SLIDING_WINDOW
Start of the windowAt the visitor's first request; everything resets at the end.Always the last minute elapsed, sliding.
Denied requestsCounted too: a visitor who keeps trying gains nothing.Not counted.
Possible burstUp to 2 × max in a short time, across the end of one window and the start of the next.Never more than max over a window period.
Recommended forMost routes.Login, code sending, any route where a doubled burst is costly.

One counter per rule, not per route

The counter depends on the rule's settings and on the visitor, not on the URL being called. If the same rule (max: 3, window: "1m") protects /login and /signup, a visitor gets 3 requests per minute in total, not 3 on each route.

For separate counters, give each route different settings, or add a characteristic that names the route in addition to the IP:

rateLimit({ max: 5, window: "1m", characteristics: ["ip", "route"] }),
// …
call: () => ({ characteristics: { route: "login" } }),

Changing max, window, algorithm or characteristics starts a new counter: visitors start again from zero.

characteristics: who is "a visitor"

  • The listed characteristics combine: with ["ip", "route"], each address has its own counter for each route.
  • A characteristic missing from the request is ignored. If none is present (for example ["userId"] for a visitor who is not logged in), Zarex falls back to the IP address: the request is still limited.
  • IPv6 addresses are grouped by /64 block: a subscriber cannot bypass the limit by changing address within their block.

Never list only a shared value

characteristics: ["route"] without "ip" gives a single counter for all your visitors on that route: the first one to hit the limit makes everyone hit it. Always keep a characteristic specific to the visitor ("ip", "userId"…).

mode: observe before blocking

rules: [rateLimit({ mode: "DRY_RUN", max: 100, window: "1m" })],

In DRY_RUN, nothing is blocked: the decision log shows the visitors who would have exceeded the limit. Useful to choose max based on your real traffic.

Shared IP addresses (CGNAT)

An IP address is not a person

A per-IP limit that is too low can block visitors who did nothing wrong. Read this section before choosing your values.

The problem

In an internet café, every customer goes online through the same IP address. Mobile carriers do the same at a much larger scale: hundreds, sometimes thousands of subscribers share a single public address. This is called CGNAT. Companies, schools and public Wi-Fi networks do the same.

By default, rate limiting counts per IP address. With max: 5, window: "1m" on your login page:

  1. a mobile subscriber mistypes their password 5 times;
  2. their carrier's address reaches the limit;
  3. every subscriber sharing that address gets a 429 denial for one minute.

You won't see it when testing from home: your users, however, will no longer be able to log in.

The solution: two rules on public routes

On a route where the visitor is not logged in yet (login, sign-up, forgotten password, sending a code), combine:

  • a loose per-IP limit, which stops bots sending hundreds of requests without bothering subscribers of the same carrier;
  • a strict per-target-account limit (the email entered), which stops repeated attempts on the same account, even when the attacker changes IP address.
server.ts
import express from "express";
import { zarex, rateLimit } from "@zarex/express";

const app = express();
app.use(express.json());

app.post(
  "/login",
  zarex({
    key: process.env.ZAREX_KEY!,
    rules: [
      rateLimit({ max: 100, window: "1m" }), // per IP: loose
      rateLimit({ max: 5, window: "15m", characteristics: ["login"] }), // per target account: strict
    ],
    call: (req) => ({
      characteristics: {
        login: typeof req.body?.email === "string" ? req.body.email.trim().toLowerCase() : undefined,
      },
    }),
  }),
  (req, res) => {
    // … password check
  }
);

What happens then:

SituationResult
A subscriber gets their own password wrong 6 timesOnly that account is slowed down. Others sharing the address log in normally.
An attacker tries 6 passwords on one account, changing IP each timeDenied on the 6th attempt: the counter follows the account, not the address.
A bot sends 500 requests per minute from one addressDenied above 100 by the first rule.
The form arrives without an emailThe second rule counts per IP address.

Good to know:

  • the rules are placed on the login route only, not on the whole application: the strict limit does not affect your other pages;
  • the email is lowercased so that [email protected] and [email protected] count together, and only read if it really is a string;
  • it is hashed (SHA-256) by the SDK before being sent: Zarex never receives it in clear text;
  • the values 100 and 5 are examples: adapt them to your traffic.

Observe before blocking

First run your rules with mode: "DRY_RUN" for a few days: nothing is blocked, and the decision log shows who would have been denied. If some addresses regularly exceed the loose limit with traffic that looks normal, they are probably shared addresses: raise max before switching to LIVE.

Limit per user

On a route where the user is logged in, limit per account rather than per IP: each user then has their own limit, even when sharing their address with others (see Shared IP addresses). Put this rule on routes reserved for logged-in users: an anonymous visitor has no userId, so they would be counted per IP address with the same limit.

server.ts
app.use(
  zarex({
    key: process.env.ZAREX_KEY!,
    rules: [
      rateLimit({ max: 20, window: "1m", characteristics: ["userId"] }),
    ],
    call: (req) => ({ characteristics: { userId: req.user?.id } }),
  })
);

The values provided by call are hashed (SHA-256) before being sent to Zarex.

The response to the visitor

Beyond the limit, the SDK answers 429 with a Retry-After header (in seconds, based on the time left before the limit frees up):

{ "error": { "code": "rate_limited", "message": "Too many requests", "request_id": "…" } }

You can replace this response with your own (your framework's onDeny option).

What the decision contains

The rule's result, in decision.results (ruleType: "RATE_LIMIT"), contains in reason:

FieldMeaning
currentRequests counted in the window, this one included.
maxThe limit.
reset_in_msMilliseconds before the limit frees up.
windowThe rule's window.

Example, 4th request of a minute with max: 3 in a fixed window (denied):

{ "current": 4, "max": 3, "reset_in_ms": 59997, "window": "1m" }

The right IP address

A per-IP limit only makes sense if Zarex sees the visitor's real address. Behind a proxy, check your setting: see The visitor's IP address.

On this page