Rate Limiting
Learn how to build a scalable Redis-backed rate limiter with Express from connection handling and route-specific limits to fail-open strategies, monitoring, and production best practices.
Rate Limiting
1/ Project Setup and Dependencies.
Instead of implementing Redis-based rate limiting logic from scratch, it's always recommended to use packages that have been used in production.
express-rate-limit: Express rate limiter middlewarerate-limit-redis: Adapter which uses the Redis store for rate limiting via express-rate-limitioredis: Production-quality Redis client (superior toredisin clustering, retry options, and connection pooling).
Redis Clustering: It's a distributed deployment method in Redis that allows for scalability and availability via partitioning of the data set among many nodes.
Execute the following commands in your root project folder
npm init -y
npm install express express-rate-limit rate-limit-redis ioredis
npm install -D dotenv @types/express @types/ioredisioredistakes care of automatic retries, lazy connects, and can work easily with Redis Cluster/Sentinel.- Using
dotenv, you will be able to handle redis credentials using environment variables. - Added type definition packages that will make our developer experience better.
Add this configuration in your .env file
REDIS_URL=redis://localhost:6379
RATE_LIMIT_WINDOW_MS=60000 // 60 sec
RATE_LIMIT_MAX_REQUESTS=100- RATE_LIMIT_WINDOW_MS: length of the rate-limit time window in milliseconds.
- RATE_LIMIT_MAX_REQUESTS: maximum number of requests allowed inside that window
Allow 100 requests per 60 seconds (commonly enforced per IP/user/token). When the limit is exceeded the middleware typically returns a 429 Too Many Requests response.
Exact behavior (fixed vs sliding window, how clients are identified) depends on the rate-limiter implementation.
2/ Redis Connection & Initialization
Isolate Redis configuration in its own file to improve separation of concerns and maintainability and to keep it decoupled from the application entry point.
-
Redis is always designed as a remote, network-accessible data store (Remote Dictionary Server) rather than a local library embedded within your application's code.
-
Because it operates over a network protocol, your application does not need to start, stop, or manage the Redis server process directly as part of its own execution flow.
Architectural Benefits of decoupling
-
Separate Lifecycle : Redis can run on a different server, container, or cloud instance, allowing your main app to scale independently of the cache layer.
-
Shared Access : Multiple application instances can connect to the same Redis instance simultaneously, enabling shared state management that local in-memory variables cannot support.
-
Network Dependency : Accessing Redis requires network requests, which introduces latency compared to direct memory access, but provides persistence and durability that local variables lack.
-
Standardized Connection: Your app connects to Redis via a host and port (e.g., redis://hostname:6379 in Docker) rather than instantiating a class within the same process space.
Exponential backoff
It is a network and system resilience algorithm that increases the waiting time between retry attempts exponentially after each failure .
This strategy prevents network congestion, avoids overwhelming a server with immediate, repeated requests by allowing transient ( temporary, non-permanent malfunction ) errors to resolve over time.
Spinning Up a Redis Instance with Docker Compose
Create a docker-compose.yml file:
services:
redis:
image: redis
container_name: redis-server
ports:
- "6379:6379"
volumes:
- redis-data:/data
command: redis-server --appendonly yes
volumes:
redis-data:Start the Redis container: docker compose up -d
Verify the container is running: docker ps
File: src/config/redis.ts
import Redis from "ioredis";
import dotenv from "dotenv";
dotenv.config();
if (!process.env.REDIS_URL) {
throw new Error("REDIS_URL is not defined in environment variables");
}
const redisClient = new Redis(process.env.REDIS_URL, {
// Redis configuration options for production safety and performance
maxRetriesPerRequest: 3, // Limit the number of retries to intialize connection to prevent hanging requests , preventing from infinite loops
retryStrategy(times) {
if (times > 10) return null; // Stop retrying after 10 attempts
return Math.min(times * 100, 2000); // Exponential backoff with a maximum delay of 2 seconds
},
enableOfflineQueue: true, // ioredis will queue commands in memory while the client is disconnected and send them when the connection is restored which can help with transient network issues
lazyConnect: true, // Don't block app startup if Redis is temporarily unavailable
name: "rate-limiter", // Makes debugging easier in Redis CLI / Redis logs and monitoring
});
redisClient.on("connect", () => console.log("Connected to Redis successfully"));
redisClient.on(
"error",
(err) => {
console.error("Redis connection error:", err.message);
},
// In production , forward this error to a monitoring service like Sentry or Datadog for alerting and diagnostics
);
// Gracefully shutdown Redis connection on app termination to prevent resource leaks during Docker/container restarts or scaling events.
process.on("SIGINT", async () => {
try {
await redisClient.quit();
console.log("Redis connection closed gracefully");
process.exit(0);
} catch (err) {
console.error("Error closing Redis connection:");
process.exit(1);
}
});
export default redisClient;Why These Flags Matter in Production
| Setting | Why It's Critical |
|---|---|
retryStrategy | Protects the system from excessive reconnection attempts during Redis failures by failing gracefully after 10 retries. |
enableOfflineQueue: false | Stops your app from memory-leaking or hanging when Redis goes down. Commands fail immediately instead of piling up. |
lazyConnect: true | Your Express server can start even if Redis is still booting. The connection initializes on first rate-limit hit. |
SIGTERM handler | Ensures Redis connections close cleanly during Docker/container restarts or scaling events. |
To test the connection
import redisClient from "./src/config/redis";
redisClient
.ping()
.then((result) => {
console.log("Redis connection successful:", result);
})
.catch((error) => {
console.error("Redis connection failed:", error);
});3/ Configure the Rate Limiter Middleware
- Create a dedicated middleware module for rate limiting.
- This keeps the application entry point clean, improves separation of concerns, and makes it easier to apply different limits across routes and services.
File: src/middleware/rate-limiter.ts
import rateLimit, { ipKeyGenerator } from "express-rate-limit";
import { RedisStore, type RedisReply } from "rate-limit-redis";
import redisClient from "../config/redis";
import type { Request, Response } from "express";
// Redis store configuration
const redisStore = new RedisStore({
sendCommand: (command: string, ...args: string[]) =>
redisClient.call(command, ...args) as Promise<RedisReply>, // Redis holds counters so limits are shared across app instances
prefix: "rl:", // Redis key prefix to prevent collisions and make metrics readable for easier monitoring and debugging
});
// Rate limiter middleware configuration
const rateLimiter = rateLimit({
store: redisStore, // Use Redis store for distributed rate limiting across multiple instances
windowMs: Number(process.env.RATE_LIMIT_WINDOW_MS) || 60 * 1000, // time window for counting requests
limit: Number(process.env.RATE_LIMIT_MAX_REQUESTS) || 100, // max requests allowed per window
// Use modern `RateLimit-*` headers and disable deprecated `X-RateLimit-*` headers
standardHeaders: true,
legacyHeaders: false,
// In production : IP for guests, UserID for authenticated users.
keyGenerator: (req) => ipKeyGenerator(req.ip || "unknown"), // Use client's IP address as the unique key for rate limiting
skip: (req) => req.path === "/health" || req.path.startsWith("/admin"), // Skip rate limiting for health checks and admin routes
// Custom handler for when a client exceeds the rate limit
handler: (req: Request, res: Response) => {
// rateLimit resetTime derive from Redis TTL by default
const retryAfterSec = Math.ceil(
((req as any).rateLimit.resetTime - Date.now()) / 1000,
);
res.status(429).json({
success: false,
error: "Too Many Requests",
message: `Rate limit exceeded. Try again in ${retryAfterSec}s.`,
retryAfter: retryAfterSec, // expected time when the rate-limit window resets.
});
},
});
export default rateLimiter;
Note:
trustProxy: true: Without this,req.ipresolves to your load balancer's IP. All users will share one rate limit bucket, causing legitimate users to get blocked instantly.
Why These Configs Matter in Production
| Option | Production Impact |
|---|---|
standardHeaders: true | Modern browsers, CDNs, and API clients understand RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset. Helps with client-side backoff strategies. |
keyGenerator | Using req.user?.id or req.ip prevents authenticated users from sharing a limit with anonymous traffic. |
skip | Prevents health probes (K8s, AWS, UptimeRobot) from consuming your rate limit quota. |
handler | Gives you a consistent JSON error shape. Frontends/mobile apps can parse retryAfter to auto-retry with exponential backoff. |
To verify
import express from "express";
import rateLimiter from "./src/middleware/rate-limiter";
const app = express();
app.use(rateLimiter); // Apply globally for testing
app.get("/test", (req, res) => {
res.json({ message: "Success", headers: req.headers["ratelimit-remaining"] });
});
app.listen(3000, () => console.log("Server running on port 3000"));Run node src/app.js, then hit http://localhost:3000/test repeatedly in your browser or terminal. You should see:
- JSON response with success
RateLimit-Remainingheader decreasing- After ~100 requests, a
429response with your custom JSON error
4/ Implement Route-Specific Limits & Graceful Failure Handling
- Different endpoints require different rate-limiting strategies - authentication routes typically need stricter protection, while public APIs can tolerate higher request volumes.
- Additionally, the system should adopt a fail-open strategy so temporary Redis outages do not bring down the entire API.
4.1 Create a limiter configurable Factory
File: src/middleware/limiter-factory.ts
import rateLimit, { ipKeyGenerator, type Options } from "express-rate-limit";
import { RedisStore, type RedisReply } from "rate-limit-redis";
import type { Request, Response, NextFunction } from "express";
import redisClient from "../config/redis";
// Redis store configuration for rate limiting
const createRedisStore = () =>
new RedisStore({
sendCommand: (command: string, ...args: string[]) =>
redisClient.call(command, ...args) as Promise<RedisReply>, // Redis holds counters so limits are shared across app instances
prefix: "rl:", // Redis key prefix to prevent collisions and make metrics readable for easier monitoring and debugging
resetExpiryOnChange: true, // Reset the expiry time on each request
});
// Factory function creating multiple rate limiters with customizable options
export const createLimiter = (options: Partial<Options> = {}) =>
rateLimit({
store: createRedisStore(), // Use Redis store for distributed rate limiting across multiple instances
windowMs: Number(process.env.RATE_LIMIT_WINDOW_MS) || 60 * 1000, // time window for counting requests
limit: Number(process.env.RATE_LIMIT_MAX_REQUESTS) || 100, // max requests allowed per window
// Use modern `RateLimit-*` headers and disable deprecated `X-RateLimit-*` headers
standardHeaders: true,
legacyHeaders: false,
// In production : IP for guests, UserID for authenticated users.
keyGenerator: (req) => ipKeyGenerator(req.ip || "unknown"), // Use client's IP address as the key for rate limiting
...options, // Allow overriding default options like skip, handler, etc.
});
export const safeRateLimiter =
(limiter: ReturnType<typeof rateLimit>) =>
(req: Request, res: Response, next: NextFunction) => {
limiter(req, res, (err?: string | Error) => {
if (err) {
console.error(
"Rate limiter error , Redis store failed, failing open",
err,
);
return next(); // Fail open: allow the request to proceed if there's an error with the rate limiter
}
next();
});
};4.2 Define Route-Specific Limits
Create src/middleware/index.ts to keep configs organized
import { createLimiter, safeRateLimiter } from "./limiter-factory";
export const globalLimiter = safeRateLimiter(
createLimiter({
limit: Number(process.env.RATE_LIMIT_MAX_REQUESTS) || 100, // 100 requests per window per IP by default
windowMs: Number(process.env.RATE_LIMIT_WINDOW_MS) || 60 * 1000, // 1 mins default
}),
);
export const authLimiter = safeRateLimiter(
createLimiter({
windowMs: 60 * 1000, // 1 mins window for auth routes
limit: 5, // 5 requests per window per IP for auth routes
}),
);
export const uploadLimiter = safeRateLimiter(
createLimiter({
windowMs: 60 * 1000, // 1 mins window for upload routes
limit: 10, // 10 requests per window per IP for upload routes
}),
);4.3 Final Integration in index.ts(entry point of app)
Order matters in Express. Apply global rate limiter first, then override specific routes before your main router
import express, {
type NextFunction,
type Request,
type Response,
} from "express";
import { authLimiter, globalLimiter, uploadLimiter } from "./src/middleware";
const app = express();
app.use(globalLimiter); // Global rate limiter (covers 90% of traffic)
// Route-specific overrides (applied BEFORE your main router)
app.use("/api/auth", authLimiter);
app.use("/api/upload", uploadLimiter);
// Health check (this route is not rate limited to allow monitoring tools to check service health without restrictions)
app.get("/health", (req, res) => res.json({ status: "ok" }));
app.get("/tests", (req, res) => {
res.json({ message: "Success", headers: req.headers["ratelimit-remaining"] });
});
app.use(
(err: Error, req: Request, res: Response, _next: NextFunction): void => {
console.error("Unhandled error:", err);
res.status(500).json({ success: false, error: "Internal Server Error" });
},
);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));| Concept | Production Benefit |
|---|---|
| Factory Pattern | Creates isolated limiter instances with independent Redis key spaces, preventing rate-limit collisions across routes such as /api/auth and /api/upload. |
| Fail-Open Wrapper | Ensures API availability during Redis outages by allowing requests to continue instead of failing the entire application. Prioritizes uptime over temporary enforcement. |
| Middleware Execution Order | Express processes middleware sequentially, enabling global protection first while allowing route-specific limiters to apply stricter or more specialized policies afterward. |
resetExpiryOnChange: true --> Keeps Redis keys fresh by resetting their expiration time whenever the rate limit updates, helping prevent unnecessary stale keys from piling up.
5/ Monitoring, Key Management & Production Checklist
Before shipping to production, let’s review monitoring, Redis key expiration behavior, and deployment best practices.
5.1 Add Metrics & Alerting Hooks
Production rate limiting needs visibility. Update your rate-limiter.ts handler to emit metrics/logs without blocking requests
// Inside your rateLimiter handler:
handler: (req, res) => {
const retryAfterSec = Math.ceil((req.rateLimit.resetTime - Date.now()) / 1000);
// Emit to your observability stack
console.warn('[RATE_LIMIT] 429 Triggered', {
ip: req.ip,
userId: req.user?.id,
path: req.path,
retryAfterSec,
timestamp: new Date().toISOString()
});
res.status(429).json({
success: false,
error: 'Too Many Requests',
message: `Rate limit exceeded. Try again in ${retryAfterSec}s.`,
retryAfter: retryAfterSec,
});
}Alerting Rule Suggestion:
- Trigger PagerDuty/Slack if
rate_limit.exceeded> 50 req/min from a single IP - Trigger warning if
429rate on/api/auth/*spikes (indicates credential stuffing)
PagerDuty is a cloud-based incident management platform to resolve critical infrastructure issues and outages.
- It functions as an orchestration layer that aggregates alerts from various monitoring tools, automatically notifies the appropriate on-call personnel via phone, SMS, or email, and manages escalation policies to ensure rapid response.
5.2 Redis Key Management & Debugging
rate-limit-redis automatically sets TTLs equal to your windowMs. Keys expire cleanly, but you'll occasionally need to inspect or reset them.
| Action | Redis CLI Command |
|---|---|
| List all rate limit keys | redis-cli --scan --pattern "rl:*" |
| Check TTL & value for an IP | TTL "rl:global:192.168.1.10" + GET "rl:global:192.168.1.10" |
| Unban a specific user/IP | DEL "rl:global:192.168.1.10" |
| Ban a specific user/IP | SET rl:global:192.168.1.10 999999 EX 86400 |
| Flush all rate limits (dev only) | redis-cli --scan --pattern "rl:*" | xargs redis-cli DEL |
Redis Memory Policy
Set this in your redis.conf or managed service config:
maxmemory-policy volatile-lruThis ensures Redis only removes keys with TTLs (your rate limits) if memory fills up, leaving your app cache/data intact.
5.3 Production Deployment Checklist
Run through this before pushing to staging/prod:
- Env Var Validation: Use
zodorjoito validateREDIS_URL,RATE_LIMIT_WINDOW_MS, etc. Fail fast on missing configs. trustProxy: trueis set AND your load balancer forwardsX-Forwarded-Forcorrectly.- Health check
/healthis excluded viaskip(3/). - Redis runs with
volatile-lrumaxmemory policy. - Fail-open wrapper is active [ tested Redis downtime in (4/) ].
ioredisconnection retries are tuned for your cloud provider or docker in local setup (2/).- Custom
handlerreturns RFC-compliantRetry-Afterheader + JSON. - Rate limits are documented in your API spec (OpenAPI/Swagger).
- Load test completed: Use
k6orartilleryto simulate burst traffic and verify 429 behavior. - Internal/microservice traffic bypasses rate limits (use
skipwithreq.headers['x-internal-secret']).
5.4 Final Architecture Recap
Client → LB/CDN (X-Forwarded-For) → Express → Global Rate Limiter (Redis)
↓
Route Overrides (Auth/Upload) → Fail-Open on Redis Error
↓
Custom 429 Handler → Logs/Metrics → RFC Headers
You now have:
- Cluster-ready, connection-resilient Redis integration
- Route-specific limits with clean key scoping
- Graceful degradation (fail-open) for Redis outages
- Production metrics, TTL management, and debugging paths
- Security & compliance best practices baked in