Performance: Rate limiting with throttler
This affects server response time and client perceived latency by controlling request flow to avoid overload.
import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler'; import { APP_GUARD } from '@nestjs/core'; import { Module } from '@nestjs/common'; @Module({ imports: [ ThrottlerModule.forRoot({ ttl: 60, limit: 10, }), ], providers: [ { provide: APP_GUARD, useClass: ThrottlerGuard, }, ], }) export class AppModule {}
import { Injectable, NestMiddleware } from '@nestjs/common'; @Injectable() export class RateLimitMiddleware implements NestMiddleware { private requests = new Map<string, number[]>(); use(req, res, next) { const ip = req.ip; const now = Date.now(); const windowTime = 60000; // 1 minute const maxRequests = 10; if (!this.requests.has(ip)) { this.requests.set(ip, []); } const timestamps = this.requests.get(ip).filter(time => now - time < windowTime); timestamps.push(now); this.requests.set(ip, timestamps); if (timestamps.length > maxRequests) { res.status(429).send('Too many requests'); } else { next(); } } }
| Pattern | CPU Usage | Memory Usage | Response Delay | Verdict |
|---|---|---|---|---|
| Manual timestamp filtering | High CPU per request | Grows with clients | Increases under load | [X] Bad |
| NestJS ThrottlerModule | Low CPU overhead | Managed internally | Stable under load | [OK] Good |
@Throttle(ttl, limit) decorator in a NestJS application?@Throttle(ttl, limit)@Throttle(ttl, limit) parameter order@Throttle(60, 10).import { Controller, Get } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
@Controller('api')
export class ApiController {
@Get('data')
@Throttle(10, 5)
getData() {
return 'Success';
}
}@Throttle(60, 10) to a controller method but it does not limit requests as expected. What is the most likely cause?ThrottlerModule is configuredThrottlerModule.forRoot() to be imported in the app module.@Throttle(60, 10).ThrottlerModule in your app module -> Option CThrottlerModule.forRoot(){ ttl: 60, limit: 100 } for 100 requests per 60 seconds.@Throttle(60, 200)@Throttle(ttl, limit), so 200 requests per 60 seconds overrides global limit.ThrottlerModule.forRoot({ ttl: 60, limit: 100 }) globally and add @Throttle(60, 200) on the specific controller -> Option DThrottlerModule.forRoot({ ttl: 60, limit: 100 }) globally and add @Throttle(60, 200) on the specific controller [OK]Pass the test and this pattern moves unknown