Rate Limiting and Throttling in Express.js
Introduction
APIs are the backbone of modern applications, enabling seamless data exchange between clients and servers. However, exposing APIs without proper rate limiting can lead to abuse, excessive resource consumption, and even DDoS (Distributed Denial of Service) attacks.
Rate limiting is an essential technique used to restrict the number of requests a client can make within a specified timeframe. This helps to:
What is Rate Limiting?
Its a technique to restrict the number of API requests a client can make within a given time window (e.g., 100 requests per minute). Once the limit is reached, further requests are blocked or delayed.
Example of rate limiting policies:
What is Throttling?
Throttling is a dynamic version of rate limiting where requests exceeding the limit are slowed down instead of being completely blocked. It ensures that APIs remain available while reducing sudden traffic spikes.
For example, after exceeding the limit, additional requests may be delayed instead of outright rejected.
领英推荐
Best Practices for Rate Limiting
Implementation of Rate Limiting & Throttling
npm install express-rate-limit express-slow-down
const express = require("express");
const rateLimit = require("express-rate-limit");
const slowDown = require("express-slow-down");
const app = express();
const port = 3000;
// Rate Limiting: Limit each IP to 100 requests per 15 minutes
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.",
});
// Slow Down: After 50 requests, add a delay of 1 second per request
const speedLimiter = slowDown({
windowMs: 15 * 60 * 1000, // 15 minutes
delayAfter: 50, // Delay starts after 50 requests
delayMs: (req, res) => 1000, // Adds 1 sec delay per request
});
// Apply middleware globally
app.use(limiter);
app.use(speedLimiter);
// Your existing routes
app.get("/", (req, res) => {
res.send("Welcome to the Blog!");
});
// Blog API routes (apply rate limiting only to API requests)
app.use("/api", limiter, speedLimiter);
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Now Deploy the app and try sending the multiple request to test the rate limiting.
Additional Enhancements
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
message: "Too many requests",
skip: (req, res) => req.ip === "YOUR_ADMIN_IP", // Replace with your IP
});
handler: (req, res) => {
res.status(429).json({ error: "Too many requests. Try again later!" });
}