API Rate Limiting: Protecting Your Backend Services

September 25, 20241 min read
APIRate LimitingSecurityBackend
# API Rate Limiting: Protecting Your Backend Services Rate limiting protects APIs from abuse and ensures fair resource usage. This guide covers implementation strategies. ## Rate Limiting Strategies ### Fixed Window Limit requests per time window: ```typescript import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler'; @Module({ imports: [ ThrottlerModule.forRoot({ ttl: 60, limit: 10, }), ], }) export class AppModule {} @UseGuards(ThrottlerGuard) @Controller('api') export class ApiController {} ``` ### Sliding Window More accurate rate limiting: ```typescript async function slidingWindowRateLimit( key: string, limit: number, window: number ): Promise<boolean> { const now = Date.now(); const pipeline = redis.pipeline(); pipeline.zremrangebyscore(key, 0, now - window); pipeline.zcard(key); pipeline.zadd(key, now, now); pipeline.expire(key, Math.ceil(window / 1000)); const results = await pipeline.exec(); const count = results[1][1] as number; return count < limit; } ``` ## Implementation ```typescript @Injectable() export class RateLimitGuard implements CanActivate { async canActivate(context: ExecutionContext): Promise<boolean> { const request = context.switchToHttp().getRequest(); const key = `rate:${request.ip}`; return slidingWindowRateLimit(key, 100, 60000); } } ``` ## Conclusion Rate limiting is essential for API protection. Implement appropriate strategies based on your use case and scale.
API Rate Limiting: Protecting Your Backend Services - Blog - Websezma LLC