So you built an API. It works. Postman is green. You deployed it and shared the link in three WhatsApp groups. You are feeling like a backend engineer 😎
Then one person writes a tiny loop:
while (true) fetch("https://your-api.com/api/menu"); Your server starts sweating. Your database starts sweating. Your cloud bill starts sweating. And on your login route, a script is quietly trying password after password on the same account, 50 times a second 👀
Nothing in your code says "slow down". So nobody slows down.
Today we fix that with rate limiting: a rule that says how many requests one client may send in a period of time. And we will build it ourselves, from scratch, with the token bucket algorithm, so you actually understand what the npm packages do for you.
The puff-puff tray analogy 😋😋
Picture a puff-puff seller at the market. Every regular customer gets their own tray.
- The tray holds at most 5 puff-puff. That's the capacity, also called the burst: the most you can grab at once.
- The seller drops 2 fresh ones onto your tray every second. That's the refill rate: your steady speed over time.
- Every time you want one, you take one from your tray. No puff-puff on the tray? The seller says "come back in 1 second" and you leave empty-handed. You don't get to take from someone else's tray.
- The tray never overflows. If you go home for an hour, you come back to 5, not 7,200 (2 per second × 3,600 seconds).
In code, a puff-puff is a token, the tray is a bucket, and "taking one" is making one request.
request comes in │ ▼ who is this? ──► find their bucket (create a full one if new) │ ▼ add tokens earned since last time (max = capacity) │ ▼ at least 1 token? ├── yes ─► take 1 token ─► run the route ─► 200 OK └── no ─► 429 Too Many Requests + "Retry-After: N" Two new words in that diagram:
- 429 Too Many Requests is the official HTTP status code for "you sent too many requests in a given amount of time". It was defined in RFC 6585 (an RFC is an internet standards document).
- Retry-After is a response header that tells the client how long to wait before trying again. We'll send it as a number of seconds.
Why a token bucket and not just "max 100 requests per minute"? Because real users are bursty. A page might load and fire 4 requests at the same moment, then go quiet. The token bucket says "a short burst is fine, but over time you must stay at my steady rate." This isn't a toy idea either: AWS API Gateway (Amazon's service that sits in front of APIs) documents that it uses the token bucket algorithm for its own throttling ("throttling" is just another word for rate limiting), with a rate (tokens added per second) and a burst (the bucket's capacity).
Prerequisites
- Node.js 18 or newer (we use the built-in
fetch, which arrived in Node 18. I tested on Node 22) - Basic Express: you know what a route is and what
reqandresare - A little TypeScript (if you know JavaScript, you'll be fine, I promise 🤗). Quick cheat sheet for the bits you'll see:
: numberand<string, TokenBucket>are type labels,import typeimports only types (it disappears after compiling),a ?? bmeans "usea, unless it'snullorundefined, then useb", andreq.body?.emailmeans "reademailonly ifreq.bodyexists, otherwise giveundefinedinstead of crashing". A parameter starting with_(like_req) is just a hint that we don't use it.
One more word before we start: middleware. In Express, a middleware is a function that runs before your route handler. It receives req, res and next. If it calls next(), the request moves on to the route. If it sends a response instead, the route never runs. Our rate limiter will be a middleware: the security man at the gate who decides who goes in.
Let's Dive Right In 😁😁
mkdir rate-limit-express && cd rate-limit-express npm init -y npm i express@5 npm i -D typescript @types/express @types/node mkdir src test scripts -D saves packages as dev dependencies: tools we only need while building. typescript gives us the tsc compiler, and the @types/... packages teach TypeScript what Express and Node look like.
Here's where we're going:
rate-limit-express/ ├── src/ │ ├── tokenBucket.ts ← one customer's tray │ ├── rateLimit.ts ← the middleware (a tray per customer) │ ├── app.ts ← routes + limits │ └── server.ts ← starts the server ├── test/ │ └── tokenBucket.test.ts ├── scripts/ │ └── hammer.ts ← an impatient client ├── tsconfig.json └── package.json Step 1: The config nobody reads (but you should) — tsconfig.json
This file tells TypeScript how to turn our .ts files into plain JavaScript in a dist folder.
{ "compilerOptions": { "target": "ES2022", "module": "commonjs", "rootDir": ".", "outDir": "dist", "strict": true, "esModuleInterop": true, "skipLibCheck": true }, "include": ["src", "test", "scripts"] } "strict": true means TypeScript will shout at us about anything sloppy. Good. Let it shout 😅
Now open package.json and replace the "scripts" section with this:
"scripts": { "build": "tsc", "start": "node dist/src/server.js", "test": "node --test dist/test/tokenBucket.test.js", "hammer": "node dist/scripts/hammer.js" } npm run build compiles, npm start runs the server, npm test runs our tests, and npm run hammer attacks our own server (lovingly).
Step 2: The puff-puff tray — src/tokenBucket.ts
This file does one thing: it manages the tokens for one client. No Express here at all.
// One tray of puff-puff for ONE customer. export class TokenBucket { private tokens: number; private lastRefill: number; constructor( private readonly capacity: number, // biggest burst allowed (tray size) private readonly refillPerSec: number, // steady rate (puff-puff added per second) now: number = Date.now() ) { this.tokens = capacity; // a new customer starts with a full tray this.lastRefill = now; } // Add the tokens earned since the last visit, but never above capacity. private refill(now: number): void { const secondsPassed = (now - this.lastRefill) / 1000; this.tokens = Math.min(this.capacity, this.tokens + secondsPassed * this.refillPerSec); this.lastRefill = now; } // Try to spend one token. Returns whether the request may pass, // and if not, how many whole seconds until one token is back. take(now: number = Date.now()): { allowed: boolean; remaining: number; retryAfterSec: number } { this.refill(now); if (this.tokens >= 1) { this.tokens -= 1; return { allowed: true, remaining: Math.floor(this.tokens), retryAfterSec: 0 }; } const missing = 1 - this.tokens; // fraction of a token we still need const retryAfterSec = Math.ceil(missing / this.refillPerSec); return { allowed: false, remaining: 0, retryAfterSec }; } } The important lines, don't skip them:
-
private readonly capacity: numberinside the constructor is a TypeScript shortcut. Writingprivate(orreadonly) in front of a constructor parameter automatically createsthis.capacityand saves the value there. That's whythis.capacityandthis.refillPerSec"appear from nowhere" later.readonlymeans it can't be changed after. - There is no timer. The seller doesn't stand there adding puff-puff every second. Instead, when you show up, he checks how long you've been gone and adds what you earned.
Date.now()gives the current time in milliseconds, so we divide by 1000 to get seconds. -
Math.min(this.capacity, ...)is the "tray never overflows" rule. Without it, a user who went quiet for a day could come back with thousands of tokens and blast you all at once. - Tokens can be fractions. Half a second at 2 per second = 1 token. A quarter second = 0.5 tokens. We only let a request through when there's at least one whole token.
-
retryAfterSec: if we have 0.4 tokens and earn 2 per second, we need 0.6 more, which takes 0.3 seconds.Math.ceilrounds up to 1, becauseRetry-Afteris sent in whole seconds. -
remainingis how many whole tokens are left. We don't use it today, but it's handy if you later want to tell clients how many requests they have left. -
nowis a parameter withDate.now()as the default. In real life we never pass it. In tests we pass a fake time, so we don't have to actually wait. You'll see why that's lovely in Step 5.
Step 3: One tray per customer — src/rateLimit.ts
A bucket for one person is cute. But our API has many people. This file keeps a separate bucket for every client and turns it into Express middleware.
import type { Request, Response, NextFunction } from "express"; import { TokenBucket } from "./tokenBucket"; type Options = { capacity: number; refillPerSec: number; keyFor: (req: Request) => string; // who is this request from? }; // Returns an Express middleware that gives every key its own bucket. export function rateLimit({ capacity, refillPerSec, keyFor }: Options) { const buckets = new Map<string, TokenBucket>(); // key -> that customer's tray return (req: Request, res: Response, next: NextFunction) => { const key = keyFor(req); let bucket = buckets.get(key); if (!bucket) { bucket = new TokenBucket(capacity, refillPerSec); buckets.set(key, bucket); } const result = bucket.take(); if (result.allowed) { return next(); // token spent, go on to the route } res.set("Retry-After", String(result.retryAfterSec)); // seconds to wait return res.status(429).json({ error: "Too many requests. Please slow down.", retryAfterSec: result.retryAfterSec, }); }; } What's happening:
-
rateLimit(...)is a function that returns a middleware. We call it once per rule ("normal routes", "login") and each rule gets its ownMapof buckets. - Why doesn't
bucketsstart empty on every request? Becauseconst buckets = new Map()runs only once, when we callrateLimit(...)at startup. The middleware it returns runs on every request, and it keeps "remembering" that sameMap(JavaScript calls this a closure: an inner function keeps access to the variables of the function that created it). Same seller, same trays, all day. - A
Mapis like an object made for lookups:buckets.get("102.89.1.7")gives that client's bucket. First visit? We create a full one. -
keyFordecides "who is this?". It could be the IP address, the logged-in user's ID, an API key, or an email. You choose per route. This is the most important design decision in rate limiting, so we made it a parameter instead of hard-coding it. - Allowed →
next(). Not allowed →429+Retry-After. The route never runs, so your database never even hears about it 🎉
Step 4: The menu and the gate — src/app.ts
Now we decide the actual numbers.
import express from "express"; import { rateLimit } from "./rateLimit"; export const app = express(); app.use(express.json()); // Normal routes: burst of 5, then 2 requests per second, per IP address. const apiLimiter = rateLimit({ capacity: 5, refillPerSec: 2, keyFor: (req) => req.ip ?? "unknown", }); // Login: much stricter. Burst of 3, then 1 try every 20 seconds, // counted per email so changing IP addresses doesn't reset it. const loginLimiter = rateLimit({ capacity: 3, refillPerSec: 1 / 20, keyFor: (req) => String(req.body?.email ?? "unknown").toLowerCase(), }); app.get("/api/menu", apiLimiter, (_req, res) => { res.json({ items: ["puff-puff", "buns", "chin chin"] }); }); app.post("/auth/login", loginLimiter, (req, res) => { // Fake login: we only care about the limiter today. res.status(401).json({ error: "Invalid email or password", email: req.body?.email }); }); See how apiLimiter sits in the middle of app.get("/api/menu", apiLimiter, handler)? That's how you attach a middleware to just one route: Express runs the arguments left to right, so the gate runs first.
Two rules, two very different trays:
-
/api/menuis keyed byreq.ip, the client's IP address as Express sees it.?? "unknown"is a fallback in case it's missing. Burst of 5, then 2 per second. Generous, because reading a menu is cheap. -
/auth/loginis keyed by email, not IP. Why? If you count per IP, an attacker just spreads their guesses across many IP addresses and each one starts with a fresh tray. The OWASP Authentication Cheat Sheet (OWASP is a respected web security community) recommends tying the failed-login counter to the account, for exactly this reason..toLowerCase()stops "ADA@example.com" from getting a second tray. -
refillPerSec: 1 / 20means one token every 20 seconds. Slow on purpose. Humans don't type 50 passwords a second. Scripts do. - The login route always answers
401(Unauthorized, meaning "wrong details") because it's fake. We're testing the gate, not the house 😅
A real app would count only failed logins, and would also have a per-IP limit on login. There's a catch with counting per account too: an attacker can deliberately burn Ada's tokens so the real Ada can't log in for a while. OWASP warns about exactly this and suggests giving users another way in (like the forgotten-password flow). I kept one rule so the idea stays clear.
Step 5: The server and the proof — src/server.ts and test/tokenBucket.test.ts
The server file is tiny on purpose:
import { app } from "./app"; const PORT = Number(process.env.PORT ?? 3000); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT} 🚀`); }); Now the test. Remember the now parameter from Step 2? Here's the payoff: we test "1 second later" and "1 hour later" without waiting a single second. We use node:test, the test runner that comes built into Node, so there's nothing extra to install.
import { test } from "node:test"; import assert from "node:assert/strict"; import { TokenBucket } from "../src/tokenBucket"; test("full bucket allows a burst of 5, then blocks", () => { const start = 0; // fake clock, in milliseconds const bucket = new TokenBucket(5, 2, start); for (let i = 0; i < 5; i++) { assert.equal(bucket.take(start).allowed, true); } const sixth = bucket.take(start); assert.equal(sixth.allowed, false); assert.equal(sixth.retryAfterSec, 1); // 1 token at 2/sec = 0.5s, rounded up to 1 }); test("refills 2 tokens per second, never above capacity", () => { const bucket = new TokenBucket(5, 2, 0); for (let i = 0; i < 5; i++) bucket.take(0); // empty it // 1 second later: exactly 2 tokens are back assert.equal(bucket.take(1000).allowed, true); assert.equal(bucket.take(1000).allowed, true); assert.equal(bucket.take(1000).allowed, false); // 1 hour later: still only 5, not 7,200 const results = Array.from({ length: 6 }, () => bucket.take(3_600_000).allowed); assert.deepEqual(results, [true, true, true, true, true, false]); }); 3_600_000 is just 3,600,000 milliseconds (one hour). The underscores are allowed in JavaScript numbers to make them easier to read.
npm run build npm test ok 1 - full bucket allows a burst of 5, then blocks ok 2 - refills 2 tokens per second, never above capacity # tests 2 # pass 2 # fail 0 Your terminal may show this with ✔ ticks and slightly different formatting. That's fine. What matters is pass 2 and fail 0.
These are unit tests: tests that check one small piece of code (here, just the TokenBucket class) on its own, with no server running.
Step 6: Be the villain — scripts/hammer.ts
Unit tests are nice, but I want to see real HTTP requests bounce off the gate. This script plays the impatient client.
// Pretend to be an impatient client. Run this while the server is running. const BASE = "http://localhost:3000"; async function menu(): Promise<number> { const res = await fetch(`${BASE}/api/menu`); return res.status; } async function login(email: string): Promise<string> { const res = await fetch(`${BASE}/auth/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, password: "wrong" }), }); const retry = res.headers.get("retry-after"); return retry ? `${res.status} (Retry-After: ${retry})` : String(res.status); } const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); async function main() { // 1. Ten requests at the same time const burst = await Promise.all(Array.from({ length: 10 }, menu)); console.log("10 at once:", burst.join(" ")); // 2. Wait one second, then try 3 more await sleep(1000); const later = [await menu(), await menu(), await menu()]; console.log("1s later: ", later.join(" ")); // 3. Someone guessing passwords for one account for (let i = 1; i <= 4; i++) { console.log(`login try ${i} (ada):`, await login("ada@example.com")); } // 4. A different account is not punished console.log("login try 1 (tunde):", await login("tunde@example.com"));Source:https://dev.to/fredabod/stop-letting-one-client-flood-your-api-token-bucket-rate-limiting-in-express-for-beginners-1l4bRelated posts
2026 Saudi E-Commerce TCO & Architecture Benchmark: Hosted SaaS (Salla / Zid) vs Self-Owned WooCommerce + ZATCA Phase 2


