Node.js Course
Node.js
/
Advanced

Graceful Shutdown

Definition

The process of safely turning off a Node.js server. Instead of instantly killing the process, it stops accepting new requests, finishes processing existing active requests, closes database connections, and then exits.

Explain Like I'm New

Imagine a restaurant closing at 10 PM. A bad shutdown is turning off the lights and kicking everyone out mid-bite. A Graceful Shutdown is locking the front door so no NEW customers can enter, letting the people already inside finish their meals, washing the dishes, and then turning off the lights.

Real World Example

If you host on Kubernetes, K8s restarts your pods frequently. If you don't implement Graceful Shutdown, any user in the middle of uploading a file or paying a bill when the restart happens will experience a failed request and a crashed app.

Common Use Cases

  • •Kubernetes/Docker deployments
  • •Ensuring data integrity during deployments

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What system signal does Node.js receive when the server (like PM2 or Docker) wants it to shut down?

intermediate

  • What happens to pending HTTP requests if you call `process.exit(1)` immediately?

Flash Cards

Question

What system signal?

Click to reveal answer
Answer

`SIGTERM` or `SIGINT` (Ctrl+C).

Question

What happens if you process.exit?

Click to reveal answer
Answer

Every single pending HTTP request and database query is instantly severed, resulting in network errors for users and potentially corrupted database entries.