0
0
NestJSframework~8 mins

Rate limiting with throttler in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Rate limiting with throttler
MEDIUM IMPACT
This affects server response time and client perceived latency by controlling request flow to avoid overload.
Controlling API request rate to prevent server overload
NestJS
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 {}
Uses optimized built-in throttler with efficient in-memory or distributed storage and minimal CPU overhead.
📈 Performance GainNon-blocking request checks; memory managed internally; stable response times under load.
Controlling API request rate to prevent server overload
NestJS
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();
    }
  }
}
This manual approach stores timestamps in memory and filters on every request, causing CPU overhead and memory growth under load.
📉 Performance CostBlocks event loop briefly on each request; memory grows with active clients; can cause slow response under high traffic.
Performance Comparison
PatternCPU UsageMemory UsageResponse DelayVerdict
Manual timestamp filteringHigh CPU per requestGrows with clientsIncreases under load[X] Bad
NestJS ThrottlerModuleLow CPU overheadManaged internallyStable under load[OK] Good
Rendering Pipeline
Rate limiting affects server-side request handling before response rendering, impacting how quickly the server can send data back.
Request Handling
Response Time
⚠️ BottleneckCPU overhead during request counting and validation
Core Web Vital Affected
INP
This affects server response time and client perceived latency by controlling request flow to avoid overload.
Optimization Tips
1Use built-in throttling libraries to minimize CPU and memory overhead.
2Avoid manual timestamp filtering on every request to prevent blocking the event loop.
3Monitor 429 responses and response times in DevTools Network tab to verify throttling effectiveness.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using NestJS ThrottlerModule over manual rate limiting?
AIt reduces CPU overhead by using optimized request counting
BIt increases memory usage to store more data
CIt blocks the event loop to ensure accuracy
DIt disables rate limiting under high load
DevTools: Network
How to check: Open DevTools Network tab, make rapid repeated requests to API, observe response status and timing.
What to look for: Look for 429 status codes indicating throttling and consistent response times without spikes.