Rate limiting is used to control the amount of incoming and outgoing traffic to or from a network. It is essential for the following reasons:
-
Prevent Overload: Rate limiting helps prevent server overload by controlling the number of requests a client can make in a given time period, ensuring that resources are not exhausted.
-
Security: It helps mitigate denial-of-service (DoS) attacks by limiting the number of requests from a single source, thereby protecting the service from being overwhelmed.
-
Fair Usage: It ensures fair usage by preventing any single user from monopolizing resources, allowing equitable access for all users.
-
Cost Management: By controlling excessive usage, rate limiting can help manage costs associated with bandwidth and server resources.
-
Performance Optimization: It can enhance the performance and reliability of a service by maintaining a steady flow of requests, avoiding spikes that may lead to delays or failures.
Rate limiting can be applied in the following ways:
- Global Configuration: By setting a global configuration for all controllers and actions
- Controller Level: By setting a configuration for all actions in a controller
- Action Level: By setting a configuration for a single action
- Dynamic Configuration: By using a function to calculate the configuration based on the context of the request
This project uses the @nestjs/throttler package to implement rate limiting.
The global configuration for rate limiting is set in the AppModule using the ThrottlerModule:
The AppController is decorated with the @Throttle decorator to customize the throttle configuration for the controller as a whole.