Chuyển đến nội dung chính

Bài 18: Performance Profiling & Optimization

V8 profiler, --prof flag, flamegraphs. Memory leak detection, heap snapshots. Clinic.js (Doctor, Bubbleprof, Flame). Event Loop lag monitoring, 0x profiler. GC tuning.

💻 Lập trình — Bài 18 Bài 18: Performance Profiling & Optimization

Node.js Core: Từ Cơ bản đến Nâng cao

Phần 5: Testing, Performance & Production

xdev.asia

1. V8 Profiler

# CPU profiling
node --prof app.js
# Tạo isolate-*.log
node --prof-process isolate-0x*.log > processed.txt

# Flamegraph với 0x
npx 0x app.js
# Mở browser tại flamegraph output

2. Clinic.js

# Clinic Doctor — phân tích tổng quát
npx clinic doctor -- node app.js
# Output: HTML report với CPU, memory, event loop, handles

# Clinic Flame — flamegraph
npx clinic flame -- node app.js
# Output: Interactive flamegraph

# Clinic Bubbleprof — async visualization
npx clinic bubbleprof -- node app.js
# Output: Async flow visualization

3. Memory Leak Detection

import v8 from 'node:v8'

// Heap snapshot
v8.writeHeapSnapshot() // Tạo file .heapsnapshot → mở trong Chrome DevTools

// Programmatic monitoring
function monitorMemory() {
  const { heapUsed, heapTotal, external, rss } = process.memoryUsage()
  return {
    heapUsed: Math.round(heapUsed / 1e6),
    heapTotal: Math.round(heapTotal / 1e6),
    external: Math.round(external / 1e6),
    rss: Math.round(rss / 1e6),
  }
}

// Detect memory growth
let lastHeap = 0
setInterval(() => {
  const { heapUsed } = monitorMemory()
  const growth = heapUsed - lastHeap
  if (growth > 10) console.warn(`Memory grew by ${growth}MB`)
  lastHeap = heapUsed
}, 30000)

4. Event Loop Lag

import { monitorEventLoopDelay } from 'node:perf_hooks'

const histogram = monitorEventLoopDelay({ resolution: 20 })
histogram.enable()

setInterval(() => {
  console.log({
    min: (histogram.min / 1e6).toFixed(2) + 'ms',
    max: (histogram.max / 1e6).toFixed(2) + 'ms',
    mean: (histogram.mean / 1e6).toFixed(2) + 'ms',
    p99: (histogram.percentile(99) / 1e6).toFixed(2) + 'ms',
  })
  histogram.reset()
}, 10000)

5. GC Tuning

# Xem GC events
node --trace-gc app.js

# GC flags
node --max-old-space-size=4096 \
     --max-semi-space-size=64 \
     --optimize-for-size \
     app.js

# Expose GC cho manual trigger (chỉ dev/debugging)
node --expose-gc -e "global.gc(); console.log(process.memoryUsage())"

6. Optimization Checklist

Kỹ thuậtImpactKhi nào
Stream thay BufferCaoFile processing lớn
Connection poolingCaoDatabase/Redis connections
Caching (Redis/LRU)CaoFrequent reads
Worker ThreadsTrung bìnhCPU-intensive tasks
Cluster modeTrung bìnhMulti-core utilization
Native addonsCaoCrypto, image processing

Bài tiếp theo: Docker & CI/CD — multi-stage build, GitHub Actions.