tezvyn:

What does PM2 do for Node.js applications?

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

production process lifecycle and automatic recovery.

OUTLINE

PM2 restarts crashed processes and manages multiple workers.

OUTLINE

solves (1) app crash requiring manual restart, (2) single-process bottleneck.

PROCESS SUPERVISION

When a Node.js app crashes, it exits immediately. Users see a connection error. Without PM2, someone must SSH to the server and restart the process manually, which is slow and error-prone. PM2 automatically watches the process and restarts it on exit, minimizing downtime. Combined with health checks, a crash is an invisible blip, not an outage.

CLUSTER MODE FOR CONCURRENCY

A single Node.js process can only use one CPU core. Modern servers have 8, 16, or more cores sitting idle. PM2 cluster mode forks multiple worker processes, automatically distributing traffic. This solves the single-threaded bottleneck without code changes. The same application handles 8x more throughput.

KEY PROBLEM 1: MANUAL RESTARTS

Without PM2, a crash requires manual intervention. PM2 monitors the process in the background and restarts it automatically, keeping the application available. This is especially important for long-running servers where someone might not notice a crash immediately.

KEY PROBLEM 2: UNDERUTILIZED HARDWARE

A server with 8 cores but a single Node.js process wastes 7 cores. PM2 cluster mode forks 8 workers, each with its own event loop. Traffic is distributed via a round-robin load balancer within PM2, using all cores efficiently. This increases throughput without code changes.

GRACEFUL RESTARTS

PM2 can gracefully restart workers one by one, draining connections before termination. This enables zero-downtime deployments. The master process forks a new worker, drains the old one, and removes it, repeat for each worker.

MONITORING AND LOGGING

PM2 provides a dashboard (pm2 monit) showing CPU, memory, and restart counts. Logs are centralized. This visibility helps catch resource leaks or problems early. Without PM2, you rely on system tools like top, which is less integrated.

Read the original → pm2.keymetrics.io

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.