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
| Technical | Impact | When |
|---|---|---|
| Stream instead of Buffer | High | Large file processing |
| Connection pooling | High | Database/Redis connections |
| Caching (Redis/LRU) | High | Frequent reads |
| Worker Threads | Average | CPU-intensive tasks |
| Cluster mode | Average | Multi-core utilization |
| Native addons | High | Crypto, image processing |
Next article: Docker & CI/CD — multi-stage build, GitHub Actions.