API throttling is an essential mechanism to control and limit the number of requests made to an API within a specified timeframe. It helps protect the API from abuse, ensures fair usage, and prevents server overload. In this tutorial, I will tell you how to implemented API throttling using NestJS, Redis, and Docker Compose.
Why API Throttling with Redis?
In a distributed architecture, it becomes challenging to synchronize throttling limits across instances. This is where a shared storage solution like Redis comes into play. Redis provides a centralized storage mechanism that allows all instances to access and update throttling information consistently.
Below are the steps I had to do to use a shared storage for api throttling (note - this uses a single redis instance not a cluster. Will come up with a separate post for using redis clusters for the same)
Step 1: Changes to Docker Compose
services:
redis:
image: 'redis:alpine'
ports:
- 6379:6379
api:
depends_on:
- redis
Step 2: Install Required Packages
Install the necessary packages by updating the package.json file:
"dependencies": {
"ioredis": "^5.3.2",
"nestjs-throttler-storage-redis": "^0.3.3"
}
Run the command npm install to install the packages.
Step 3: Implement API Throttling in NestJS
In the app.module.ts file, update the imports and configuration:
import { ThrottlerStorageRedisService } from 'nestjs-throttler-storage-redis';
import Redis from 'ioredis';
@Module({
imports: [
// Other imports...
ThrottlerModule.forRoot({
ttl: 60,
limit: 60,
storage: new ThrottlerStorageRedisService(new Redis('redis://redis')),
}),
],
// Other module properties...
})
We configure the ThrottlerModule with the desired ttl (time to live) and limit values. the above means we allow 60 requests in 60 seconds.
The connection URL redis://redis consists of two parts. The first part, redis://, specifies the Redis protocol. It indicates that the connection is being made to a Redis server. The second part, redis, refers to the hostname of the redis service defined in the Docker Compose configuration. By using redis
Top comments (0)