백엔드/NestJS

[NestJS] API 호출 횟수 제한하기 ( Rate Limiting )

SparkIT 2025. 1. 21. 17:51

 

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

 

클라이언트가 API를 무제한으로 요청할 수 있다면 서버에 부하가 심해질 수 있습니다. 일반적으로 AWS 같은 CDC를 이용하면 디도스 공격을 방어해주긴 하지만 더 확실하게 안정성을 부여하기 위해서 API 호출 횟수에 제한을 두는 것도 좋다고 생각합니다.

 

설치

npm install @nestjs/throttler

// yarn 사용시
yarn add @nestjs/throttler

 

 

호출 횟수 제한 방법

1. 특정 API에만 적용하기

@Throttle 데코레이터를 활용해 특정 API에만 호출 횟수 제한을 둘 수 있습니다.

// 예제

@Throttle({ default: { limit: 3, ttl: 60000 } })
@Get()
findAll() {
  return "List users works with custom rate limiting.";
}

 

 

2. 전역으로 적용하기

다음과 같이 app.module.ts 에 전역으로 설정할 수도 있습니다.

✅ 저는 현재 yarn berry(3버전)을 이용해 패키지를 설치하고 있습니다. 이로 인해 설치하는 패키지 버전이 달라 설정이 다를 수 있습니다! 예를 들면 구 버전과 달리 현재 yarn을 통해 설치한 @nestjs/throttler는 limit이나 ttl같은 옵션을 throttlers라는 파라미터에 배열 형식으로 설정해야하는 식으로 수정되었습니다.

// app.module에 해당 코드 추가

imports: [
    ThrottlerModule.forRoot({
        throttlers: [
            {
                limit: 2,
                ttl: 6000000,
            },
        ],
    }),
],
providers: [
    {
        provide: APP_GUARD,
        useClass: ThrottlerGuard,
    },
],

 

그리고 해당 방법을 사용했을 때는 역으로 특정 API에만 호출 횟수 제한을 제거하고 싶을 수 있습니다. 이 경우에는 @SkipThrottle 데코레이터를 사용합니다.

// 예제

@SkipThrottle()
@Controller('users')
export class UsersController {}