Rate Limiting and Throttling in Express.js

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:

  • Prevent API abuse and brute force attacks
  • Protect server resources from excessive load
  • Ensure fair usage among users
  • Improve overall API reliability and performance

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:

  • Per IP Rate Limiting: Restrict requests from a single IP address.
  • User-based Rate Limiting: Restrict requests based on user authentication tokens.
  • Endpoint-Specific Rate Limiting: Apply limits only to certain API routes (e.g., /login or /signup).

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

  • Use IP-based limits for public APIs and user-based limits for authenticated endpoints.
  • Implement separate limits for critical endpoints (e.g., /login, /signup).
  • Use Redis-based rate limiting for better scalability.
  • Log and monitor blocked requests to identify potential abuse patterns.
  • Provide users with proper error messages and headers so they understand their rate limits.

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

  • Whitelist Admin IPs: let's you want to allow unlimited requests for yourself (admin), add a skip function.

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
});        

  • Custom Error Messages

handler: (req, res) => {
  res.status(429).json({ error: "Too many requests. Try again later!" });
}        

要查看或添加评论,请登录

Ritu Raj Singh的更多文章

社区洞察

其他会员也浏览了