icon

성능 모니터링과 프로파일링


 성능 모니터링과 프로파일링은 NestJS 애플리케이션의 효율성을 지속적으로 개선하고 최적화하는 데 필수적인 과정입니다.

 이를 통해 애플리케이션의 병목 지점을 식별하고, 리소스 사용을 최적화하며, 사용자 경험을 향상시킬 수 있습니다.

주요 성능 지표 및 측정 방법

 1. 응답 시간 (Response Time)

  • 측정 : NestJS 인터셉터 사용
@Injectable()
export class TimingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const now = Date.now();
    return next
      .handle()
      .pipe(
        tap(() => console.log(`Request took ${Date.now() - now}ms`)),
      );
  }
}

 2. 처리량 (Throughput)

  • 측정 : 로드 밸런서나 API 게이트웨이 로그 분석

 3. 에러율 (Error Rate)

  • 측정 : 글로벌 예외 필터 사용
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
 
    // 에러 로깅 및 카운팅
    console.error(`Error occurred: ${exception}`);
 
    response
      .status(500)
      .json({
        statusCode: 500,
        timestamp: new Date().toISOString(),
        path: request.url,
      });
  }
}

Node.js 내장 프로파일링 도구 사용

  1. CPU 프로파일링
node --prof dist/main.js
  1. 프로파일 데이터 분석
node --prof-process isolate-0xnnnnnnnnnnnn-v8.log > processed.txt

메모리 누수 탐지 및 해결

  1. 힙 스냅샷 생성
import * as heapdump from 'heapdump';
 
// 애플리케이션 코드 내
heapdump.writeSnapshot((err, filename) => {
  console.log('Heap snapshot written to', filename);
});
  1. Chrome DevTools를 사용하여 힙 스냅샷 분석

APM 도구 통합

 예 : New Relic 통합

  1. 의존성 설치
npm install newrelic
  1. 설정 파일 생성 (newrelic.js)
exports.config = {
  app_name: ['Your NestJS App'],
  license_key: 'your_license_key_here',
  logging: {
    level: 'info'
  }
};
  1. 메인 파일에 New Relic 초기화 추가
import 'newrelic';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
 
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

분산 추적 시스템 구현

 Jaeger를 사용한 분산 추적 예

  1. 의존성 설치
npm install @nestjs/opentelemetry @opentelemetry/instrumentation-http @opentelemetry/exporter-jaeger
  1. 트레이싱 모듈 설정
import { Module } from '@nestjs/common';
import { OpenTelemetryModule } from '@nestjs/opentelemetry';
 
@Module({
  imports: [
    OpenTelemetryModule.forRoot({
      serviceName: 'your-service-name',
      exporter: {
        type: 'jaeger',
        options: {
          endpoint: 'http://localhost:14268/api/traces',
        },
      },
    }),
  ],
})
export class AppModule {}

로깅 전략 및 로그 분석

 ELK 스택 (Elasticsearch, Logstash, Kibana) 사용 예

  1. Winston 로거 설정
import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';
 
@Module({
  imports: [
    WinstonModule.forRoot({
      transports: [
        new winston.transports.File({ filename: 'error.log', level: 'error' }),
        new winston.transports.File({ filename: 'combined.log' }),
      ],
    }),
  ],
})
export class AppModule {}
  1. Logstash를 사용하여 로그를 Elasticsearch로 전송
  2. Kibana를 사용하여 로그 시각화 및 분석

부하 테스트 및 결과 분석

 Apache JMeter를 사용한 부하 테스트

 1. JMeter 테스트 플랜 생성

 2. 다양한 시나리오에 대한 테스트 실행

 3. 결과 분석

  • 응답 시간 분포
  • 처리량 (Throughput)
  • 에러율

실시간 모니터링 대시보드 및 알림 시스템

 Grafana와 Prometheus를 사용한 대시보드 구축

  1. Prometheus 설정 (prometheus.yml)
scrape_configs:
  - job_name: 'nestjs'
    static_configs:
      - targets: ['localhost:3000']
  1. NestJS 애플리케이션에 Prometheus 메트릭 노출
import { Controller, Get } from '@nestjs/common';
import { register } from 'prom-client';
 
@Controller('metrics')
export class MetricsController {
  @Get()
  async getMetrics(): Promise<string> {
    return register.metrics();
  }
}
  1. Grafana 대시보드 설정 및 알림 규칙 정의

Best Practices 및 전략

  1. 지속적인 모니터링 : 주요 성능 지표를 실시간으로 모니터링
  2. 프로파일링 자동화 : CI/CD 파이프라인에 프로파일링 단계 포함
  3. 성능 테스트 정례화 : 정기적인 부하 테스트 수행
  4. 로그 중앙화 : 분산 시스템의 로그를 중앙 저장소에 집중
  5. 알림 체계 구축 : 주요 성능 지표 임계값 초과 시 즉시 알림
  6. 코드 최적화 : 프로파일링 결과를 바탕으로 지속적인 코드 개선
  7. 리소스 모니터링 : CPU, 메모리, 디스크 I/O 등 시스템 리소스 추적
  8. 데이터베이스 성능 추적 : 쿼리 실행 계획 분석 및 최적화
  9. 사용자 경험 모니터링 : 실제 사용자 메트릭(RUM) 수집 및 분석
  10. 성능 최적화 문화 : 팀 내 성능 인식 제고 및 지속적 개선 노력

 프로파일링은 지속적인 개선과 최적화의 기반이 됩니다. 주요 성능 지표를 정의하고 측정하는 것으로 시작하여, node.js 내장 도구와 외부 APM 솔루션을 활용한 심층 분석까지 다양한 접근 방식을 활용할 수 있습니다.

 메모리 누수 탐지는 애플리케이션의 장기적인 안정성을 위해 중요합니다. 힙 스냅샷 분석을 통해 메모리 사용 패턴을 파악하고 문제를 해결할 수 있습니다. APM 도구는 실시간 성능 모니터링과 문제 진단을 용이하게 해주며, 분산 추적 시스템은 마이크로서비스 아키텍처에서 특히 유용합니다.

 효과적인 로깅 전략과 로그 분석은 성능 문제 진단에 핵심적입니다. ELK 스택과 같은 도구를 활용하여 로그를 중앙화하고 분석할 수 있습니다. 부하 테스트는 애플리케이션의 한계를 파악하고 최적화 포인트를 식별하는 데 도움이 됩니다.

 실시간 모니터링 대시보드와 알림 시스템은 문제를 신속하게 감지하고 대응할 수 있게 해줍니다. Grafana와 Prometheus의 조합은 강력한 모니터링 솔루션을 제공합니다.