NodeJS

Implementing Rate Limiting in NodeJS APIs


Introduction

There is nothing more important in managing the frequency of the incoming requests to an API than rate limiting. In this case, bounded calls per user are useful as they sliced the brute force attack problem to specific time slicers, avoid server overload or maybe overloaded by a malicious user and also ensure that all user get an equal and fair use of the service.

 

Why Use Rate Limiting?

  • Prevent server overload: Also, when making request calls that exceed the number of times a resource can be called in a given time or when calling a resource at a frequency that is above its limit will reduce its efficiency.
  • Mitigate security risks: Other security threats that rate limiting works to prevent include brute force, where attackers try to guess passwords in order to login into any account.
  • Ensure fair resource allocation: Here the concept of API limit request means that each user must get equal access to the resources.

Quick start to include Rate Limiting in NestJS which is a NodeJS Framework

Unfortunately, rate limiting in NestJS lacks flexibility and efficiency until now when a package named @nestjs/throttler can be used. Here's a basic example:

 

rate limiting strategies for Node.js APIs

 

In the above example, we set the ThrottlerModule to have a API limit of 10 requests in the time period of sixty seconds. The ThrottlerGuard is used on the ProtectedController so that all the method calls are limited by the rate. It reduces the health risk of building up a huge traffic on the server resulting in vulnerability to some malicious attacks.

 

Additional Considerations

  • Sliding window algorithm: It is recommended to try the sliding window algorithm as a more accurate NodeJS rate limiting tool.
  • Multiple rate limits: This means to do NodeJS rate limiting for various endpoints or various user classes.
  • IP address whitelisting/blacklisting: Do not apply rate limiting to certain IP address.
  • Circuit breaker pattern: When using this pattern, it is best used alongside the rate limiting pattern to guarantee that an application will recover gracefully from transient errors. So in our NestJS application, it will be beneficial to enforce rate limiting in order to support its performance, stability and usability.

Steps to run the demo:

1) Click Here to Open the demo code

2) Click on the preview button to run the application.

3) Hit the URL twice, it will allow the code to run.

4) When you click a third time, it will block the API call, and you will receive the following error: {"statusCode":429,"message":"ThrottlerException: Too Many Requests"}

 

Ready to transform your business with our technology solutions?   Contact Us today to Leverage Our NodeJS Expertise.

0

NodeJS

Related Center Of Excellence