Performance: Rate limiting with throttler
MEDIUM IMPACT
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 |