Node.js Performance — Profiling and Optimization

Sanjeev SharmaSanjeev Sharma
1 min read

Advertisement

Performance is critical. Profile, identify bottlenecks, optimize systematically.

Profiling

# CPU profiling
node --prof app.js
node --prof-process isolate-*.log > profile.txt

# Inspect
node --inspect app.js
# Open chrome://inspect

Memory Profiling

// Check memory
console.log(process.memoryUsage());
// {
//   rss: 27.1 MB,
//   heapTotal: 8.8 MB,
//   heapUsed: 4.2 MB,
//   external: 0.2 MB
// }

// Monitor
setInterval(() => {
  const mem = process.memoryUsage();
  console.log(`Memory: ${Math.round(mem.heapUsed / 1024 / 1024)}MB`);
}, 1000);

Optimization Tips

  1. Use clustering - Multi-core utilization
  2. Connection pooling - Reuse database connections
  3. Cache aggressively - Redis, memory cache
  4. Stream large files - Don't load into memory
  5. Compress responses - gzip middleware
  6. Use CDN - Static assets

FAQ

Q: How to find memory leaks? A: Profile heap, compare snapshots, use clinic.js.

Q: When to scale horizontally? A: When single node maxed out. Use load balancer.


Performance tuning is continuous. Profile regularly, optimize based on data.

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro