DEV Community

Željko Šević
Željko Šević

Posted on • Originally published at sevic.dev on

8

Redis as custom storage for NestJS rate limiter

A rate limiter is a standard protection technique against brute force and DDoS attacks. NestJS provides a module for it, and the default storage is in-memory. Custom storage, Redis in this case, should be injected inside ThrottlerModule configuration.

Configuration

The configuration should contain

  • TTL (time to live) in seconds
  • maximum number of requests within TTL
  • Redis URL
// app.module.ts
import { APP_GUARD } from '@nestjs/core';
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
import { ThrottlerStorageRedisService } from 'nestjs-throttler-storage-redis';
// ...
@Module({
  imports: [
    ThrottlerModule.forRootAsync({
      inject: [CustomConfigService],
      useFactory: (configService: CustomConfigService) => ({
        ttl: configService.THROTTLER_TTL_SECONDS,
        limit: configService.THROTTLER_LIMIT,
        storage: new ThrottlerStorageRedisService(configService.REDIS_URL),
      }),
    }),
    // ...
  ],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

API endpoints setup

Binding the throttler guard can be done in multiple ways.

  • guard is bound globally for every API endpoint.
// app.module
import { ThrottlerGuard } from '@nestjs/throttler';
// ...
@Module({
  // ...
  providers: [{
    provide: APP_GUARD,
    useClass: ThrottlerGuard,
  }],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode
  • global guard is overridden for the specific API endpoint with the Throttle decorator.
import { Throttle } from '@nestjs/throttler';
// ...
@Controller('users')
export class UsersController {
  @Throttle(USERS_THROTTLER_LIMIT, USERS_THROTTLER_TTL_SECONDS)
  @Get()
  async getUsers() {}
}
Enter fullscreen mode Exit fullscreen mode
  • global guard is skipped for the specific API endpoint with the SkipThrottle decorator.
import { SkipThrottle } from '@nestjs/throttler';
// ...
@Controller('posts')
export class PostsController {
  @SkipThrottle()
  @Get()
  async getPosts() {}
}
Enter fullscreen mode Exit fullscreen mode

Course

Build your SaaS in 2 weeks - Start Now

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay