express-request-limiter
v1.0.1
Published
Super light, super fast concurrency limiter middleware for Express 5/4, Connect and Node.js http. Limit concurrent in-flight requests globally, per route or per user/IP, queue or reject with 429. Zero dependencies, 20 kB, ~4x less overhead than express-ra
Maintainers
Keywords
Readme
express-request-limiter
Super light, super fast concurrency limiter for Express. Cap how many requests run at the same time, globally, per route, or per user/IP. Reject the rest with 429, or queue them until a slot frees.
import express from 'express';
import requestLimiter from 'express-request-limiter';
const app = express();
app.use(requestLimiter({ max: 20 })); // never more than 20 requests in flightLight, fast, tested
| | express-request-limiter | express-rate-limit | |---|---|---| | Overhead per request | ~240 ns | ~1070 ns | | Runtime dependencies | 0 | 2 | | Package size | 20 kB packed, 9 files | ~150 kB unpacked | | Test coverage | 100% lines, 166 tests, Express 5 and 4, Node 20/22/24 | | | Limits | concurrent in-flight requests | requests per time window |
Measured with npm run bench:compare on the same mock objects, Node 20. The two libraries solve different problems and stack well together; the table shows cost, not a replacement. Coverage thresholds are enforced in CI.
Install
npm install express-request-limiterNode 20+. ESM and CommonJS. Types included. Express is an optional peer dependency; the middleware also runs on Connect and plain http.createServer. Releases are published to npm with provenance, so every tarball is traceable to a CI run on this repository.
Use
// Only some routes
app.use(requestLimiter({ max: 10, routes: [{ path: '/api/*' }, { path: '/users/:id', methods: ['DELETE'] }] }));
// One route
app.post('/export', requestLimiter({ max: 2 }), exportHandler);
// Per user or IP
app.use(requestLimiter({ max: 4, keyGenerator: (req) => req.user?.id ?? req.ip }));
// Different limits per client
app.use(requestLimiter({ max: (req) => (req.user?.plan === 'pro' ? 50 : 5), keyGenerator: (req) => req.ip }));
// Queue instead of rejecting
app.use('/render', requestLimiter({ max: 4, queue: { maxSize: 100, timeout: 15000 } }));
// Exempt health checks
app.use(requestLimiter({ max: 20, skip: (req) => req.path === '/healthz' }));Rejected requests get:
HTTP/1.1 429 Too Many Requests
X-Concurrency-Limit: 20
X-Concurrency-Remaining: 0
Retry-After: 1Downstream handlers can read req.requestLimit as { key, limit, current, remaining }.
Without Express
The middleware only touches standard request/response APIs, so it runs anywhere Connect-style middleware does — plain node:http, Connect, Fastify via @fastify/middie:
import { createServer } from 'node:http';
import requestLimiter from 'express-request-limiter';
const limit = requestLimiter({ max: 10 });
createServer((req, res) => {
limit(req, res, (err) => {
if (err) { res.statusCode = 500; return res.end(); }
handle(req, res); // your handler; rejected requests never get here
});
}).listen(3000);Koa and Next.js adapters are two lines each — see recipes.
Options
All optional. Unknown names throw at startup. Full reference: docs/api.md.
| Option | Default | What it does |
|---|---|---|
| max | 100 | Concurrent requests per key. Number or (req, res) => number. |
| routes | all | [{ path, methods }]. Exact, :param, *, or RegExp paths. |
| keyGenerator | one shared key | (req, res) => string to partition counters. |
| skip | | (req, res) => boolean to bypass. |
| queue | false | true or { maxSize, timeout } to wait instead of reject. |
| statusCode | 429 | Rejection status. |
| message | text | String, JSON object, or (req, res, info) => body. |
| retryAfter | 1 | Seconds for Retry-After; false to omit. |
| headers | true | X-Concurrency-* headers, 'draft-8' for IETF RateLimit fields, false for none. |
| handler | built-in | (req, res, next, info) to customise the rejection. |
| onLimitReached | | Observe rejections. |
| store | in-memory | Share counts across processes. See docs/stores.md. |
| requestPropertyName | 'requestLimit' | Where to expose the state on req; false to skip. |
| passOnStoreError | false | Admit (true) or fail (false) when the store errors. |
Also: caseSensitive, legacyHeaders, onQueued. The middleware exposes store, options, resetKey(key), resetAll(), getQueueSize(key?).
TypeScript and CommonJS
import requestLimiter, { type Options, type Store } from 'express-request-limiter';
app.get('/jobs', (req, res) => res.json(req.requestLimit)); // typed on Express's Requestconst { requestLimiter } = require('express-request-limiter');When to use it
Protecting a database pool, a slow upstream, a CPU-heavy endpoint, or a render farm from being flooded. Backpressure, load shedding, the bulkhead pattern, per-tenant fairness. Pair it with a time-window rate limiter such as express-rate-limit when you need both "not too many at once" and "not too many per minute" — concurrency limiting vs. rate limiting explains which protects against what.
More
- API reference, recipes (incl. Prometheus, Koa, Fastify, Next.js), custom stores and Redis, concurrency vs. rate limiting, migrating from 0.x
llms.txtfor AI agents,AGENTS.mdfor contributorsnpm run checkruns lint, types, build, and the suite on Express 5 and 4;npm run benchandnpm run bench:comparereproduce the numbers
MIT © Iaroslav Zhbankov
