nodejs-rate-limiter
A production-shaped, plan-aware rate limiter for Node.js — the kind of control plane that sits in front of AI endpoints at companies like OpenAI or Stripe. Users are grouped by plan (free, pro, team, enterprise), each plan defines per-endpoint limits, and the limiter enforces them atomically in Redis using one of three algorithms.
Built with TypeScript, Express 5, PostgreSQL (Drizzle ORM), Redis, and Docker.
Why this exists
Most Node rate-limiter examples on the internet are express-rate-limit with an in-memory Map. That falls apart the moment you run more than one process — every instance has its own counter, so a 2-node deploy silently doubles every limit. It’s also not plan-aware: everyone gets the same limit regardless of what they pay.
This project answers a different question: what would a rate limiter look like if you actually had to ship it?
- Plan-aware — free-tier and enterprise users hit the same endpoint with different ceilings.
- Multi-instance safe — counters live in Redis, incremented atomically with Lua.
- Three algorithms — fixed window, sliding window, token bucket — swappable per policy.
- Cached policy resolution — 0 DB queries per request in the hot path.
- Real logout — JWT revocation via Redis, not just client-side token discard.
- Fail-open with alerting — if Redis dies, traffic keeps flowing and an ERROR-level log fires with
failOpen: true.
Architecture
Two data stores, two jobs:
- Postgres — durable config: users, plans, endpoints, policies. Read rarely (cached), written by admins.
- Redis — ephemeral state: rate-limit counters, revoked JWTs, IP/email attempt counts. Read on every request.
The rate-limiting algorithms
algorithm on each policy chooses how the counter behaves. All three run as atomic Redis Lua scripts — no race between check and increment.
| Algorithm |
Behavior |
Use for |
fixed_window |
Simple counter reset every N seconds. Cheapest. |
Free-tier endpoints, DDoS shields. |
sliding_window |
Weighted count across two adjacent windows — no double-allowance at the boundary. |
Enterprise SLAs where smoothness matters. |
token_bucket |
Refills continuously; allows short bursts up to burst_limit, then throttles to sustained rate. |
Paid tiers that need burst headroom (Stripe’s model). |
fixed_window’s well-known weakness is that a client can send N requests at the end of a window and another N at the start of the next — 2× the intended rate for a brief spike. sliding_window and token_bucket don’t have this bug.
Data model
plans (id, name, description, price, is_active)
api_endpoints (id, name, route, method, category, is_active)
rate_limit_policies (
id, plan_id, endpoint_id,
algorithm, max_requests, window_seconds,
burst_limit, quota_type, priority, is_active
) UNIQUE (plan_id, endpoint_id)
users (id, name, email, password, salt, plan_id, role, created_at)
A policy is a (plan × endpoint × algorithm × limit) row. Free users hitting /ai/chat resolve to the (free, /ai/chat) policy row; enterprise users to (enterprise, /ai/chat). New users auto-assigned the free plan at signup.
API
Public
| Method |
Path |
Purpose |
| POST |
/user/signup |
Register (IP+email rate-limited) |
| POST |
/user/login |
Log in, get JWT (IP+email rate-limited) |
| GET |
/health |
Liveness probe |
| GET |
/ready |
Readiness probe (checks Postgres + Redis) |
Authenticated (any user)
| Method |
Path |
Purpose |
| POST |
/user/logout |
Revoke the presented JWT server-side |
| GET |
/user/profile |
Current user info (rate-limited) |
| POST |
/ai/chat |
Stub AI endpoint (plan-limited) |
| POST |
/ai/generate-image |
Stub AI endpoint (plan-limited, stricter) |
| GET |
/plans, /plans/:id |
List/read plans |
| GET |
/endpoints, /endpoints/:id |
List/read endpoints |
| GET |
/policies, /policies/:id |
List/read policies |
Admin only (role = 'admin' in the JWT)
| Method |
Path |
Purpose |
| POST |
/plans |
Create a plan |
| POST |
/endpoints |
Register a new rate-limited route |
| POST |
/policies |
Attach a policy to a (plan, endpoint) |
Every response has a stable shape. Errors:
{
"error": {
"code": "PLAN_NOT_FOUND",
"message": "Plan not found",
"requestId": "8f2a1c4e-…"
}
}
Validation errors (from zod) additionally include a fields array with per-field messages.
Every rate-limited response carries:
X-RateLimit-Limit: 200
X-RateLimit-Remaining: 197
X-RateLimit-Reset: 1728486000
Retry-After: 43 (429 only)
Setup
Prereqs: Node ≥ 20 (tested on 22), Docker Desktop, Git Bash (on Windows) for the shell snippets below.
git clone https://github.com/Chiranjeevi1923/nodejs-rate-limiter
cd nodejs-rate-limiter
cp .env.example .env # then edit JWT_SECRET
npm install
docker compose up -d # starts Postgres + Redis
npm run db:push # pushes schema to Postgres
npm run db:studio # optional: open Drizzle Studio to inspect the DB(https://local.drizzle.studio/)
npm start # tsx watch — auto-reloads on save
npm test # everything (needs Redis)
npm run test:watch # watch mode
npm run test:unit # unit only — no Redis needed
npm run test:integration # algorithms only — needs Redis
Server on http://localhost:3000. Pretty logs in dev, JSON in prod.
Environment variables
| Variable |
Required |
Default |
Notes |
DATABASE_URL |
✅ |
— |
Postgres connection string |
JWT_SECRET |
✅ |
— |
Long random string — treat as secret |
PORT |
|
3000 |
|
NODE_ENV |
|
development |
production disables pretty logs and stack traces in responses |
LOG_LEVEL |
|
debug/info |
pino level: trace/debug/info/warn/error/fatal |
REDIS_URL |
|
redis://localhost:6379 |
|
TRUST_PROXY |
|
unset |
Set when behind a load balancer so req.ip reads X-Forwarded-For |
Design decisions worth calling out
Fail-open on Redis outage
If Redis goes down, both the main rate limiter and the auth (login/signup) limiter log an ERROR with failOpen: true and let the request through rather than rejecting everyone. This is a deliberate tradeoff: a Redis blip should not lock every user out of your app. The failOpen: true field is designed to be alertable — set up a log alert on that string and you’ll know within seconds if the limiter is silently degraded.
Flip to fail-closed if your threat model requires strict enforcement (financial APIs, e.g.).
Policy caching
Every rate-limited request would otherwise hit Postgres twice: once for the user’s plan, once for the (plan, endpoint) policy. Both are cached in an in-process TTL+LRU (5-min TTL, 10k entry cap) with negative caching for unmapped pairs. The policy controller invalidates the cache on write so admin changes take effect immediately.
For multi-instance deploys: cache drift is bounded by the 5-min TTL. Upgrade path to Redis pub/sub for instant cross-instance invalidation is straightforward when it matters.
Real logout via JWT revocation
Signed-in tokens carry a jti (JWT ID). Logout writes auth:revoked:<jti> to Redis with TTL equal to the token’s remaining lifetime — Redis expires the key at exactly the moment the token would have expired anyway. Auth middleware checks the revocation list on every request. Cost: one EXISTS per authenticated request.
Centralized error handling
Zero try/catch blocks in the controllers. Handlers throw typed AppErrors; a single errorHandler middleware maps them, plus Postgres error codes (unique violation → 409, FK violation → 400, invalid UUID → 400), JWT errors, and zod validation errors — into one consistent JSON response shape with a requestId for tracing.
Structured logging
Everything goes through pino. Every request gets a x-request-id (generated or forwarded) that’s stamped on every log line, so you can grep one request end-to-end. Sensitive fields (authorization, password, token, salt, hash) are redacted.
Log-level policy:
- 5xx and programmer bugs →
error with stack
- 429 rate-limit exceeded →
warn with userId, route, algorithm, limit
- 4xx client errors →
warn
- Fail-open events →
error with failOpen: true (alertable)
- Admin mutations →
info with actor + resource IDs
Graceful shutdown
On SIGTERM / SIGINT:
/health and /ready flip to 503 — the load balancer pulls this instance.
- Stop accepting new HTTP connections; in-flight requests drain.
- Close Redis, close Postgres pool.
- Exit 0.
Hard deadline of 15s if any step hangs. Never leaves zombies.
Project layout
config/ Redis client (lazy connect)
controllers/ HTTP handlers — no try/catch, throw AppError
db/ Drizzle setup + schema
dto/schemas/ Zod schemas (types inferred from these)
middlewares/ auth, role, validate, rate limiter, error handler, shutdown, logger
modules/rate-limiter/
algorithms.ts fixed_window, sliding_window, token_bucket (Redis Lua)
services/ policy caching + default plan bootstrap
repositories/ Drizzle queries used by services
routes/ Router files — wire middleware chains
utils/ logger, hashing (scrypt), AppError, shutdown, token revocation
Testing
The suite covers the parts most likely to break: the three rate-limiter algorithms (integration tests against a real Redis), the cache/service layer (mocked repos), the zod schemas, and the AppError shape.
Prereqs: Redis must be running (docker compose up -d redis).
npm test # run everything once
npm run test:watch # watch mode while developing
npm run test:unit # unit tests only (no Redis needed)
npm run test:integration # algorithm tests (needs Redis)
What’s covered
| Area |
Type |
What we assert |
fixed_window |
integration |
Allows exactly limit; 429s the next; resets after window; atomic under concurrent load |
sliding_window |
integration |
Same, plus no double-allowance across the window boundary — the classic fixed-window bug |
token_bucket |
integration |
Absorbs a burst up to capacity, throttles once drained, refills over time, returns positive retryAfter |
| Dispatcher |
integration |
Unknown algorithm names fall back to fixed_window |
policyService cache |
unit (mocked) |
Cache hit avoids repo call, TTL/invalidation busts the right key, negative caching works, users share policy cache but not plan cache |
| Zod schemas |
unit |
Email normalization, password min length, UUID checks, enum rejection, defaults applied |
AppError |
unit |
Factories, code defaults, context.fields passthrough, isAppError narrowing |
The concurrency tests fire 25–30 parallel requests and assert exactly limit are allowed — this is the check that would fail if the Lua atomicity was ever broken.
License
ISC (see package.json).
评论