Thursday, December 4, 2025

thumbnail

Rate Limiting & Throttling with Express

 Rate Limiting & Throttling with Express

1. Introduction


Rate limiting and throttling are techniques used in Express applications to control how many requests a client can make in a certain time period. They protect your server from:


Abuse and malicious attacks (e.g., DDoS)


Accidental overload by clients


Excessive API usage


High server costs


Express does not include rate limiting by default, but you can easily add it using middleware.


2. What Is Rate Limiting?


Rate limiting restricts the number of requests from a client (IP, user, token) within a time window.


Example:

A client can make 100 requests per 15 minutes.


If the client exceeds that limit, the server returns HTTP 429 – Too Many Requests.


3. What Is Throttling?


Throttling slows down the rate of requests instead of blocking them entirely.


Types of throttling:


Soft throttling: Reduce response speed when a client nears limits.


Hard throttling: Reject requests once the maximum threshold is reached.


4. Implementing Rate Limiting with express-rate-limit


The most common and easy-to-use package is:


npm install express-rate-limit


Basic Usage

const express = require('express');

const rateLimit = require('express-rate-limit');


const app = express();


const limiter = rateLimit({

  windowMs: 15 * 60 * 1000, // 15 minutes

  max: 100, // limit each IP to 100 requests per window

  message: "Too many requests from this IP, please try again later.",

});


app.use(limiter);


app.get("/", (req, res) => {

  res.send("Welcome!");

});


app.listen(3000, () => console.log("Server running on port 3000"));


5. Different Rate Limits for Different Routes


You can set different rules for login, API routes, or sensitive endpoints.


Example: Stricter Limit for Login Route

const loginLimiter = rateLimit({

  windowMs: 15 * 60 * 1000,

  max: 5,

  message: "Too many login attempts. Please try again in 15 minutes.",

});


app.post("/login", loginLimiter, (req, res) => {

  res.send("Login attempt");

});


6. Using a Store (Redis / MemoryStore / Custom)


By default, express-rate-limit uses MemoryStore, which resets when the server restarts.


For production, use Redis (recommended for scaling).


With Redis:

npm install rate-limit-redis ioredis


const RedisStore = require('rate-limit-redis');

const Redis = require('ioredis');


const client = new Redis();


const limiter = rateLimit({

  store: new RedisStore({

    sendCommand: (...args) => client.call(...args),

  }),

  windowMs: 60000,

  max: 20,

});


7. Throttling with express-slow-down


If you want to slow down requests rather than block them:


npm install express-slow-down


Example:

const slowDown = require("express-slow-down");


const speedLimiter = slowDown({

  windowMs: 15 * 60 * 1000,

  delayAfter: 50,  // Allow 50 requests in 15 min

  delayMs: 500,    // Add 500ms delay per additional request

});


app.use("/api", speedLimiter);



Result:


First 50 requests → normal


Next requests → slower responses


Helps control bursts without rejecting clients


8. Combining Rate Limiting and Throttling


To be more robust:


app.use("/api", limiter);

app.use("/api", speedLimiter);



This ensures:


Users can’t exceed hard limits


Users slow down when nearing limit


9. Best Practices

✔ Use different limits for different routes


Authentication → very strict


Search → medium


Public info → high


✔ Use Redis or another distributed store in production


Memory limits don’t work across multiple servers.


✔ Set meaningful error messages


Help users understand how long to wait.


✔ Add rate limits per IP, user ID, or API key


IP-based may not be enough for authenticated apps.


✔ Log rate limit violations


Useful for detecting abuse patterns.


10. Example: Complete Express Setup with Rate Limiting & Throttling

const express = require('express');

const rateLimit = require('express-rate-limit');

const slowDown = require('express-slow-down');


const app = express();


// Rate Limit

const apiLimiter = rateLimit({

  windowMs: 10 * 60 * 1000, 

  max: 100,

});


// Throttle

const apiSpeedLimiter = slowDown({

  windowMs: 10 * 60 * 1000,

  delayAfter: 80,

  delayMs: 200,

});


app.use('/api', apiLimiter);

app.use('/api', apiSpeedLimiter);


app.get('/api/data', (req, res) => {

  res.json({ message: "Success" });

});


app.listen(3000, () => console.log("Server is running on port 3000"));


Summary


Rate limiting and throttling are essential tools for protecting your Express APIs.

Using packages like express-rate-limit and express-slow-down, you can:


Set request limits


Slow down excessive users


Prevent abuse


Improve performance and reliability


Scale safely, especially with Redis-backed stores

Learn 

MERN Stack Training in Hyderabad

Read More

Using Helmet for Express Security

Storing Passwords Securely with bcrypt

Role-Based Access Control in MERN Stack

Preventing XSS & CSRF in MERN

Visit Our Quality Thought Training Institute in Hyderabad

Get Directions 


Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive