Rate Limiting and Throttling in Node.js

|
| By Sahil Kumar

When building web applications or APIs, sometimes too many requests from a single user or client can overload your server. To prevent this, we use Rate Limiting and Throttling. In this blog, we will explain what they are and how you can implement them in Node.js easily.

What is Rate Limiting?

Rate limiting is a technique used to control the number of requests a user can make to your server in a specific period of time.

Example:
If a user can only make 10 requests per minute, then after 10 requests, any further requests will be blocked until the next minute.

This is useful to:

  • Prevent abuse of your API.
  • Protect your server from being overloaded.
  • Avoid spamming of your services.

What is Throttling?

Throttling is slightly different from rate limiting. It slows down the request rate instead of blocking the user completely.

Example:
If a user sends 10 requests in a second, throttling might delay some requests instead of rejecting them, so the server can handle them smoothly.

Rate Limiting in Node.js

In Node.js, we can use the popular package express-rate-limit to implement rate limiting easily.

Installation:

npm install express-rate-limit

Example:

 const express = require(‘express’); 

const rateLimit = require(‘express-rate-limit’);

  const app = express();

 // Define rate limiting rule

 const limiter = rateLimit({

     windowMs: 60 * 1000, // 1 minute

     max: 6, // limit each IP to 6 requests per windowMs

     message: “Too many requests from this IP, please try again after a minute”

 });

 // Apply the rate limiter to all requests

 app.use(limiter);

 

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

     res.send(‘Welcome to my API!’);

 });

 app.listen(3000, () => {

     console.log(‘Server running on port 3000’);

 });

Explanation:

  • windowMs: Time window in milliseconds (here 1 minute).
  • max: Maximum number of requests allowed in that time window.
  • message: Response sent when limit is reached.

Now, if someone tries to make more than 6 requests per minute, they will receive the message defined above.

Throttling Example

We can also implement throttling manually using middleware. Here’s a simple example:

 let requestCounts = {}; function throttle(req, res, next) {

     const ip = req.ip;

     const currentTime = Date.now();

     const windowTime = 10000; // 10 seconds

     const maxRequests = 3;

     if (!requestCounts[ip]) {

         requestCounts[ip] = [];

     }

     // Remove outdated requests

     requestCounts[ip] = requestCounts[ip].filter(timestamp => currentTimetimestamp < windowTime);

     if (requestCounts[ip].length >= maxRequests) {

         return res.status(429).send(‘Slow down! Too many requests.’);

     }

     requestCounts[ip].push(currentTime);

     next();

 }

 app.get(‘/throttle’, throttle, (req, res) => {

     res.send(‘Request processed successfully!’);

 });

Explanation:

  • This code keeps track of each IP’s request timestamps.
  • It only allows a maximum of 3 requests every 10 seconds.
  • Extra requests are delayed or blocked with a 429 status.

Difference Between Rate Limiting and Throttling

Feature Rate Limiting Throttling
Definition Blocks requests after limit Slows down requests after limit
Purpose Protects server/API Prevents overload gracefully
User Experience Requests blocked Requests delayed

Conclusion

Rate limiting and throttling are essential techniques to make your Node.js application more secure and reliable.

  • Rate limiting is best for APIs to prevent abuse.
  • Throttling is best for smooth handling of high request rates.

Using packages like express-rate-limit or custom middleware makes it easy to implement.

By applying these techniques, your server stays safe, and your users enjoy a better experience.

Leave a Reply

Your email address will not be published. Required fields are marked *