ITZone

Rate time limit in NodeJS

Hi guys, it’s me again. Today I would like to introduce to you a very cool and useful technique that is Rate Limiting

1. What is Rate Limiting?

Rate limiting is simply understood as limiting (limit) the number of requests (requests) to the server. In fact, one must use a number of algorithms to ensure fast, accurate performance and less memory consumption. Suppose our system receives thousands of requests, but among them can only handle hundreds of requests / s, for example, and the rest of the requests fail (because the system CPU is overloaded and cannot handle it). ).

To solve this problem, the Rate Limiting mechanism was born. Its purpose is only to allow receiving a certain number of requests in 1 unit of time. If so, it will return an error response.

2. Benefits, practical applications

More about DDOS attack can be found Here, Brute force password here

3. express-rate-limit

In NodeJS, we can easily create Rate Limiting with express-rate-limit.

Setting

Like any other library, you can install express-rate-limit with the command

$ npm install –save express-rate-limit

Usage

After creating a project. We can use express-rate-limit with a few lines like this:

In the above example, I created Rate Limiting for each IP address that can only be accessed up to 2 times per minute. We can check with Postman

 

The first image is the result returned when we access the path for the first time. The second image is the result returned when accessing the 3rd time onwards within 1 minute compared to the first request. It’s that simple, isn’t it?

Rate limit options

There are also some other options you can see details here.

Script testing

To make it simpler to test the code with a large number of requests and a larger time, you can refer to the following script:

This script will request to the address http://localhost:3000/ every 1 second. You can customize it according to your purpose.

Epilogue

Hope this article will be of some help to you. In the article there are many shortcomings, hope everyone can comment

References:

Share the news now