Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rate limit a NestJS API by multiple time intervals?

I am trying to rate limit my API with @NestJs/throttler. I want to set two different limit caps:

  • 100 requests per 1 second
  • 10,000 requests per 24 hours.

Setting either one of these rate limits is explained in the docs and is pretty straight forwad. But, setting both limitations is not articulated in the docs.

How can I rate limit my API by both time intervals?

like image 342
Julian Dave Avatar asked Nov 17 '25 05:11

Julian Dave


2 Answers

A bit late to the discussion, but here's my take on it.The following features are now available in NestJS version 10:

  @Module({
  imports: [
    ThrottlerModule.forRoot([
      {
        name: 'short',
        ttl: 1000,
        limit: 3,
      },
      {
        name: 'medium',
        ttl: 10000,
        limit: 20
      },
      {
        name: 'long',
        ttl: 60000,
        limit: 100
      }
    ]),
  ],
})
export class AppModule {}

You have the flexibility to specify when you want to modify or ignore these predefined options. For example:

// Override default configuration for Rate limiting and duration.
@Throttle({ default: { limit: 3, ttl: 60000 } })
@Get()
findAll() {
  return "List users works with custom rate limiting.";
}

or

@SkipThrottle()
@Controller('users')
export class UsersController {
  // Rate limiting is applied to this route.
  @SkipThrottle({ default: false })
  dontSkip() {
    return 'List users work with Rate limiting.';
  }
  // This route will skip rate limiting.
  doSkip() {
    return 'List users work without Rate limiting.';
  }
}

All code examples are taken directly from the official documentation.

like image 91
Giancarlo Sotelo Avatar answered Nov 19 '25 20:11

Giancarlo Sotelo


As I told you on Discord, with @nestjs/throttler, this functionality currently doesn't exist. You can have one or the other, or you can override the global config to be more specific for one endpoint, but there's not currently a way to have two limits set up.

like image 30
Jay McDoniel Avatar answered Nov 19 '25 19:11

Jay McDoniel