/blogs/rate-limiting

← Back to blogs
Blog

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.

·14 min read·

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 middleware
  • rate-limit-redis: Adapter which uses the Redis store for rate limiting via express-rate-limit
  • ioredis: Production-quality Redis client (superior to redis in 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

>_ bash
npm init -y
npm install express express-rate-limit rate-limit-redis ioredis
npm install -D dotenv @types/express @types/ioredis
  • ioredis takes 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

>_ env
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

  1. Separate Lifecycle : Redis can run on a different server, container, or cloud instance, allowing your main app to scale independently of the cache layer.

  2. Shared Access : Multiple application instances can connect to the same Redis instance simultaneously, enabling shared state management that local in-memory variables cannot support.

  3. Network Dependency : Accessing Redis requires network requests, which introduces latency compared to direct memory access, but provides persistence and durability that local variables lack.

  4. 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:

>_ text
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

>_ text
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

SettingWhy It's Critical
retryStrategyProtects the system from excessive reconnection attempts during Redis failures by failing gracefully after 10 retries.
enableOfflineQueue: falseStops your app from memory-leaking or hanging when Redis goes down. Commands fail immediately instead of piling up.
lazyConnect: trueYour Express server can start even if Redis is still booting. The connection initializes on first rate-limit hit.
SIGTERM handlerEnsures Redis connections close cleanly during Docker/container restarts or scaling events.

To test the connection

>_ text
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

>_ text
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.ip resolves 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

OptionProduction Impact
standardHeaders: trueModern browsers, CDNs, and API clients understand RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset. Helps with client-side backoff strategies.
keyGeneratorUsing req.user?.id or req.ip prevents authenticated users from sharing a limit with anonymous traffic.
skipPrevents health probes (K8s, AWS, UptimeRobot) from consuming your rate limit quota.
handlerGives you a consistent JSON error shape. Frontends/mobile apps can parse retryAfter to auto-retry with exponential backoff.

To verify

>_ txt
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-Remaining header decreasing
  • After ~100 requests, a 429 response 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

>_ text
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

>_ text
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

>_ text
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}`));
ConceptProduction Benefit
Factory PatternCreates isolated limiter instances with independent Redis key spaces, preventing rate-limit collisions across routes such as /api/auth and /api/upload.
Fail-Open WrapperEnsures API availability during Redis outages by allowing requests to continue instead of failing the entire application. Prioritizes uptime over temporary enforcement.
Middleware Execution OrderExpress 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

>_ text
// 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 429 rate 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.

ActionRedis CLI Command
List all rate limit keysredis-cli --scan --pattern "rl:*"
Check TTL & value for an IPTTL "rl:global:192.168.1.10" + GET "rl:global:192.168.1.10"
Unban a specific user/IPDEL "rl:global:192.168.1.10"
Ban a specific user/IPSET 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:

>_ conf
maxmemory-policy volatile-lru

This 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 zod or joi to validate REDIS_URL, RATE_LIMIT_WINDOW_MS, etc. Fail fast on missing configs.
  • trustProxy: true is set AND your load balancer forwards X-Forwarded-For correctly.
  • Health check /health is excluded via skip (3/).
  • Redis runs with volatile-lru maxmemory policy.
  • Fail-open wrapper is active [ tested Redis downtime in (4/) ].
  • ioredis connection retries are tuned for your cloud provider or docker in local setup (2/).
  • Custom handler returns RFC-compliant Retry-After header + JSON.
  • Rate limits are documented in your API spec (OpenAPI/Swagger).
  • Load test completed: Use k6 or artillery to simulate burst traffic and verify 429 behavior.
  • Internal/microservice traffic bypasses rate limits (use skip with req.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
1,408 words left