# Graceful Shutdown and Health Checks

A host stops your API with SIGTERM on every deploy, so a graceful shutdown stops taking new requests, lets the ones in progress finish with server.close, then closes MongoDB, and a /health route answers 200 or 503 so the host knows whether to send the API riders.

Freelancer · Node.js · Web Development · Updated November 19, 2026

By Gregor Dzierzon

## After this lesson you can

- Shut a server down gracefully on SIGTERM and SIGINT, with server.close, then close the MongoDB client
- Add a /health route that answers 200 when the API can work and 503 when it can't, and explain why a host needs it

## Key takeaways

- A host stops a program by sending it SIGTERM, on every deploy and restart. Ctrl+C sends SIGINT. One handler can serve both.
- Ending at once with process.exit cuts off every request in progress, so a rider's request gets no answer.
- server.close stops taking new requests and calls its function once every request in progress has its answer. Then close the MongoDB client.
- A timer that ends the program after a few seconds, with unref so it doesn't keep Node running, stops a stuck request from holding up the shutdown.
- A /health route answers 200 when the API can do its work and 503 Service Unavailable when it can't, such as when MongoDB doesn't answer a ping.

Once your API is online, it gets stopped and started far more than you'd think: every time you push a change, every time the host moves it to another computer, every time it restarts after a crash. Each stop is a chance to cut off a rider halfway through a request, and each start is a moment when it isn't ready yet. Every host and every team expects an API to handle both well.

*Wiring MongoDB into Express* closed the database on Ctrl+C. Here's a first try at stopping the Campus Shuttle API for a host, where the arrivals route takes about a second to look things up:

```javascript
process.on("SIGTERM", () => {
  logger.info("SIGTERM: stopping now");
  process.exit(0);
});
```

A rider asks for the next buses at the library, and while the API is still looking, the host stops it. The server's log:

```text
{"level":30,"time":1794939281916,"pid":209420,"hostname":"sams-laptop","msg":"Listening on http://localhost:3100"}
{"level":30,"time":1794939282627,"pid":209420,"hostname":"sams-laptop","msg":"SIGTERM: stopping now"}
```

And the rider? No answer at all. Node's `fetch` reported `fetch failed`, caused by `read ECONNRESET`: the connection was cut. `process.exit` ends the program at once, in the middle of whatever it was doing.

## Signals: the host asks politely

A **signal** is a short message from the operating system to a running program. Two matter here:

- **SIGINT** (read "sig-int", interrupt): what Ctrl+C sends in your terminal.
- **SIGTERM** (read "sig-term", terminate): what a host sends when it wants your program to stop. It means "please finish up and stop". A host waits a short while after it, then stops the program for good.

Windows has no real SIGTERM to send from a terminal, so on your computer you test with Ctrl+C. Hosts run Linux, where SIGTERM is what arrives. One function can handle both: `process.once("SIGTERM", stop)` and `process.once("SIGINT", stop)`. `once` runs it at most one time each, even if a second signal arrives while it's working.

## Finishing what's in progress: a graceful shutdown

Think of a café at closing time. The staff lock the door so nobody new comes in, serve the people already inside, and only then turn off the coffee machine. A **graceful shutdown** does the same:

1. **Lock the door.** `server.close()` stops taking new connections.
2. **Serve who's inside.** It waits for every request in progress to get its answer, then calls the function you hand it.
3. **Turn off the machine.** Close the MongoDB client, last, because those requests may still need it.

![A café at closing time, in three steps from left to right: the door is locked so no new customers come in, the customers already inside get their orders, and only then is the coffee machine switched off. Under each step, its match in a Node server: server.close() stops new requests, the requests in progress get their answers, client.close() closes MongoDB](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/cec2b8440be84bd49dffc11358d146b7.webp)

```javascript
async function shutdown(signal) {
  logger.info({ signal }, "Shutting down: finishing the requests in progress");
  setTimeout(() => {
    logger.error("Still busy after 10 seconds, so stopping anyway");
    process.exit(1);
  }, 10_000).unref();

  await new Promise((resolve) => server.close(resolve));
  await client.close();
  logger.info("Closed the server and the database connection");
}

process.once("SIGTERM", shutdown);
process.once("SIGINT", shutdown);
```

`server` is what `app.listen` gave back, and `client` is the `MongoClient`. The `setTimeout` is a safety net: a request that never finishes would hold the shutdown up forever, so after 10 seconds the program stops anyway. `.unref()` tells Node not to stay running only for that timer.

The same rider, the same moment:

```text
{"level":30,"time":1794939292560,"pid":232960,"hostname":"sams-laptop","msg":"Listening on http://localhost:3100"}
{"level":30,"time":1794939293275,"pid":232960,"hostname":"sams-laptop","signal":"SIGTERM","msg":"Shutting down: finishing the requests in progress"}
{"level":30,"time":1794939294014,"pid":232960,"hostname":"sams-laptop","msg":"Closed the server and the database connection"}
```

The rider got `200` and `{"stop":"library","next":["8:10","8:20"]}`, and the program ended by itself, with nothing left to do. With Ctrl+C, the second line says `"signal":"SIGINT"`.

## A health route the host can ask

A host also needs to know whether your API can do its work: after a deploy, before it sends riders to the new copy, and every so often after that. It asks a **health check** route, by habit `GET /health`. The answer is a status code: 200 means "send me riders", and **503 Service Unavailable** reads "I can't take requests right now".

An API that can't reach its database can't do its work, so the shuttle's health route asks MongoDB to answer a `ping`:

```javascript
app.get("/health", async (req, res) => {
  try {
    await db.command({ ping: 1 });
    res.json({ status: "ok" });
  } catch (error) {
    req.log.warn({ err: error }, "Health check: the database didn't answer");
    res.status(503).json({ status: "unavailable" });
  }
});
```

With MongoDB running, then after stopping it:

```text
GET /health
HTTP/1.1 200 OK
{"status":"ok"}

GET /health
HTTP/1.1 503 Service Unavailable
{"status":"unavailable"}
```

The second request also logged a warning with the error, `MongoNetworkError: connect ECONNREFUSED`, for whoever reads the logs later. The answer itself says only "unavailable": callers don't need the details, and attackers shouldn't get them.

One setting makes that 503 quick. By default, the driver keeps trying to find a database for 30 seconds before the ping fails, and in this run the 503 took 30.5 seconds; a host gives up on a health check long before that. Making the client with `new MongoClient(uri, { serverSelectionTimeoutMS: 3000 })` makes it give up after 3 seconds, and the 503 above came back in under one.

## Why a host needs both

On a deploy, a host starts the new copy and asks its `/health` until it answers 200; only then does it send riders there. It sends the old copy SIGTERM, and the graceful shutdown lets that copy finish its last requests. If `/health` starts answering 503 later, the host knows to restart the API, or to stop sending it riders. *Put Your API Online with Render* fills in the health check path on a real host.

## Check yourself

2 questions to try on the lesson page.

## So what

A graceful shutdown and a health route are how an API gets restarted many times a week without a rider ever noticing, and they're the first things a host asks you to set up.

## Key terms

- [Graceful Shutdown](https://www.ask-codey.com/glossary/graceful-shutdown-nodejs)
- [SIGTERM](https://www.ask-codey.com/glossary/sigterm)
- [Signal](https://www.ask-codey.com/glossary/signal-unix)
- [Health Check](https://www.ask-codey.com/glossary/health-check-rest-api)
- [503 Service Unavailable](https://www.ask-codey.com/glossary/503-service-unavailable)

## Related

- [Wiring MongoDB into Express](https://www.ask-codey.com/lessons/node-mongodb-in-express)
- [Logging with pino](https://www.ask-codey.com/lessons/node-pro-logging-with-pino)
- [Put Your API Online with Render](https://www.ask-codey.com/lessons/node-deploy-render)

Source: https://www.ask-codey.com/lessons/node-pro-graceful-shutdown-and-health
