SHIN STORYSHIN STORY
홈포스트C#TypeScriptNext.jsNode.js시리즈
</>SHIN STORY

sdf

탐색

  • 홈
  • 모든 포스트
  • 시리즈
  • 검색

카테고리

  • C#
  • TypeScript
  • Next.js
  • Node.js
  • 알고리즘
  • 개발 도구

© 2025 Shin Blog. All rights reserved.

GitHubRSS
목록으로
Node.js#Node.js#Performance

Node.js 성능 프로파일링 실전 가이드

SHIN

2026년 5월 3일2분 읽기1
📚

Node.js 실전 팁 20선

20편
  1. 3Node.js Stream으로 대용량 파일 처리하기
  2. 4Worker Threads로 CPU 집약 작업 처리하기
  3. 5cluster 모듈로 멀티코어 CPU 100% 활용하기
  4. 6child_process로 외부 명령 실행하기
  5. 7fs/promises로 파일 시스템 다루기
  6. 20Node.js Event Loop 완전 정복
  7. 20Node.js path 모듈 완전 정복
  8. 20환경 변수 관리 — .env, dotenv, 그리고 검증
  9. 20EventEmitter 패턴으로 느슨한 결합 구현하기
  10. 20Node.js crypto 모듈로 해싱과 암호화 구현하기
  11. 20Node.js 메모리 누수 찾고 수정하기
  12. 20Express 미들웨어 패턴과 에러 처리
  13. 20Node.js CJS vs ESM 모듈 시스템 완전 정리
  14. 20Node.js Buffer와 인코딩 완전 가이드
  15. 20PM2로 Node.js 프로세스 관리하기
  16. 20Node.js HTTP 서버 직접 구현하기
  17. Node.js 성능 프로파일링 실전 가이드현재
  18. 20Node.js npm 스크립트 완전 활용하기
  19. 20Node.js 보안 체크리스트 10가지
  20. 20Node.js 테스팅 전략 — 단위, 통합, E2E 테스트

Node.js 성능 프로파일링 실전 가이드

"추측하지 말고 측정하라." 최적화 전에 프로파일러로 실제 병목을 찾아야 합니다.

내장 --prof 프로파일러

CODE
# 프로파일링하며 실행
node --prof app.js

# 부하 테스트 (wrk, autocannon 등)
npx autocannon -c 100 -d 10 http://localhost:3000/api

# isolate-*.log 파일 생성됨
node --prof-process isolate-*.log > profile.txt

clinic.js — 시각적 프로파일링

CODE
npm install -g clinic

# Flame Graph (CPU 병목 시각화)
clinic flame -- node app.js

# Bubbleprof (비동기 병목 시각화)
clinic bubbleprof -- node app.js

# Doctor (종합 진단)
clinic doctor -- node app.js

console.time으로 빠른 측정

CODE
// 간단한 코드 경로 측정
console.time('db-query');
const users = await db.user.findMany({ include: { posts: true } });
console.timeEnd('db-query'); // db-query: 42.3ms

// 더 정밀한 측정
const start = performance.now();
await heavyOperation();
const elapsed = performance.now() - start;
console.log(`소요 시간: ${elapsed.toFixed(2)}ms`);

async_hooks로 비동기 추적

CODE
import { AsyncLocalStorage } from 'async_hooks';

const requestContext = new AsyncLocalStorage();

// 미들웨어: 요청별 컨텍스트 설정
app.use((req, res, next) => {
  requestContext.run({ requestId: crypto.randomUUID(), start: Date.now() }, next);
});

// 어디서나 요청 ID 접근
function logWithContext(message) {
  const ctx = requestContext.getStore();
  console.log(`[${ctx?.requestId}] ${message}`);
}

주요 병목 패턴

CODE
// ❌ N+1 쿼리 문제
const users = await db.user.findMany();
for (const user of users) {
  user.posts = await db.post.findMany({ where: { userId: user.id } });
}

// ✅ 한 번에 조인
const users = await db.user.findMany({
  include: { posts: true }
});

// ❌ 큰 JSON 동기 파싱 (이벤트 루프 블로킹)
const huge = JSON.parse(fs.readFileSync('huge.json', 'utf-8'));

// ✅ 스트림 파싱 (stream-json 라이브러리)
import { parser } from 'stream-json';
import { streamArray } from 'stream-json/streamers/StreamArray.js';

성능 측정 자동화

CODE
// 간단한 벤치마크 유틸
async function benchmark(name, fn, iterations = 1000) {
  const times = [];
  for (let i = 0; i < iterations; i++) {
    const start = performance.now();
    await fn();
    times.push(performance.now() - start);
  }
  times.sort((a, b) => a - b);
  console.log(`[${name}] avg: ${(times.reduce((s, t) => s + t, 0) / iterations).toFixed(2)}ms, p99: ${times[Math.floor(iterations * 0.99)].toFixed(2)}ms`);
}

await benchmark('user-query', () => db.user.findMany());
공유
S

SHIN

.NET 개발자입니다

GitHub
Node.js HTTP 서버 직접 구현하기

이전 포스트

Node.js HTTP 서버 직접 구현하기

다음 포스트

Node.js npm 스크립트 완전 활용하기

Node.js npm 스크립트 완전 활용하기

같은 카테고리 포스트

Node.js 테스팅 전략 — 단위, 통합, E2E 테스트

Node.js 테스팅 전략 — 단위, 통합, E2E 테스트

2026년 5월 6일· 2분
Node.js 보안 체크리스트 10가지

Node.js 보안 체크리스트 10가지

2026년 5월 5일· 2분
Node.js npm 스크립트 완전 활용하기

Node.js npm 스크립트 완전 활용하기

2026년 5월 4일· 1분

댓글