# Add Graceful Shutdown to an Express and Mongoose API

Yes. An agent makes your Express and Mongoose API finish in-flight requests on SIGTERM, close the MongoDB connection, exit cleanly with a deadline, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-graceful-shutdown/mongoose/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how the process starts and how it stops today, because a shutdown is only graceful relative to what the app holds open. In an API built from hagopj13/node-express-boilerplate, `src/index.js` calls `mongoose.connect` with the URL and options from `src/config/config.js`, and only inside its `then` starts `app.listen(config.port)`, keeping the server in a module-level `server` variable. An `exitHandler` closes that server and then calls `process.exit(1)`, and `uncaughtException` and `unhandledRejection` both route to it. `SIGTERM` gets its own handler that logs `SIGTERM received` and calls `server.close()` with no callback: the MongoDB connection stays open, nothing exits, and nothing handles `SIGINT`. `package.json` runs production through `pm2 start ecosystem.config.json --no-daemon` with `autorestart: true`, the `Dockerfile` runs on `node:alpine`, and `docker-compose.yml` starts the app beside a `mongo:4.2.1-bionic` service. `mongoose` resolves to 5.13.20 in `yarn.lock`.

It then writes one `shutdown` function and routes every exit through it. On `SIGTERM` and `SIGINT` the function logs the signal through the winston logger in `src/config/logger.js`, calls `server.close(callback)` so the listener stops accepting while open requests finish, then in the callback calls `mongoose.disconnect()`, the 5.x API that closes every connection, logs `MongoDB connection closed`, and exits `0`. A timer started with the signal forces `process.exit(1)` if the close has not finished within a deadline, with `unref()` so the timer itself never keeps the process alive; the deadline comes from a new `SHUTDOWN_TIMEOUT_MS` key in the Joi schema in `config.js`, with a default and a line in `.env.example`. The existing `exitHandler` keeps exit code `1` for the crash paths, since a restart after an uncaught exception is pm2's job, but now closes Mongoose too.

Two details come from reading rather than from a template. The `then` on `mongoose.connect` has no `catch`, so a connection failure at boot is an unhandled rejection that `unexpectedErrorHandler` logs and exits on; the agent adds the `catch` so the boot error is logged as a connection error with the host, not as a generic rejection. And a second signal during a shutdown already in progress should not start a second close: the function keeps a flag and ignores repeats, which matters under pm2, which sends `SIGINT` and then kills.

In its sandbox the agent starts a MongoDB with `docker compose up mongodb`, runs `yarn lint` (ESLint with the airbnb base config forbids `console`, so every new line goes through the logger) and `yarn test`, then adds `tests/integration/shutdown.test.js`: it spawns `node src/index.js` as a child process with the test database URL, waits for the `Listening to port` log line, holds a request open against a route, sends `SIGTERM`, and asserts the request completes, the `MongoDB connection closed` line appears, and the exit code is `0`. A second test sends the signal with the deadline set to a few milliseconds and a route that never answers, and asserts exit code `1`. Both run under the suite's `jest -i` so they never share a port.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add graceful shutdown to this Express and Mongoose API. Read src/index.js, src/config/config.js, src/config/logger.js, ecosystem.config.json, Dockerfile and docker-compose.yml first. On SIGTERM and SIGINT: stop accepting connections with server.close, wait for in-flight requests, call mongoose.disconnect(), log through the winston logger and exit 0. Add a SHUTDOWN_TIMEOUT_MS setting to the Joi schema in config.js with a default and an .env.example line, and force exit 1 past it with an unref'd timer. Ignore a repeated signal while a shutdown is running. Add a catch to the mongoose.connect promise. Keep exit code 1 for uncaughtException and unhandledRejection but close Mongoose there too. Write an integration test that spawns src/index.js, holds a request open, sends SIGTERM and checks the request completes and the exit code is 0, and one that proves the deadline. Run yarn lint and yarn test against a MongoDB started from docker-compose.yml and quote the results. Open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that changes `src/index.js` and `src/config/config.js`, adds a line to `.env.example`, and adds one test file under `tests/integration/`. The description shows the signal flow in a few lines, the new setting with its default, and quotes `yarn lint` and `yarn test` passing with the two shutdown tests named in the Jest output.

The run's record keeps the child process's log lines from the test, so a reviewer can read `SIGTERM received`, the request finishing, and `MongoDB connection closed` in order, with the exit code, rather than taking the sequence on faith.

Before merging, a reviewer sets the deadline to match the platform: a Kubernetes `terminationGracePeriodSeconds`, a Compose `stop_grace_period` or pm2's `kill_timeout`, each of which should be longer than `SHUTDOWN_TIMEOUT_MS` so the app gets to exit on its own.

## Run it on every container restart

Shutdown bugs show up on restarts, not in review, so the follow-on is a run per deploy. A handler on the reader's server, the one that already deploys the container, calls `POST /o/{org}/sessions` after each rollout with a prompt asking the agent to read the previous replica's last log lines and the orchestrator's exit code for it, and to report whether the shutdown sequence ran to the end within the deadline. The handler sends a `request_id` that is a UUID v5 of the deployment id, so a retried deploy hook returns the run already started.

Each run reads logs from a connection the Project names, never from the production database, and produces a short report: the signal seen, the time to `MongoDB connection closed`, and any request that was cut off. A deploy where the deadline fired becomes a pull request that raises the timeout or fixes the route that held the process open.

## Why run it on Rush?

Graceful shutdown is small code that is hard to test by hand: the proof is a process receiving a real signal while a real request is open, with a real database connection to close. On a laptop that is a terminal, a second terminal and a stopwatch. In a Rush sandbox the agent starts the database from the repository's own Compose file, spawns the app, sends the signal and reads the exit code, and all of it is in the record.

The pull request carries the test that will catch a regression when someone later adds a queue or a second connection, and the lint run shows no `console` slipped past the airbnb config. Across every Node service a team keeps, the same prompt produces one pull request per repository, each written against that repository's own start file.

## Frequently asked questions

### Why exit 0 on SIGTERM but 1 on an uncaught exception?

Because they mean different things to the supervisor. A clean stop after `SIGTERM` is what a deploy asked for, and pm2 or an orchestrator should not count it as a crash. An uncaught exception is a crash, and exit code `1` is what makes `autorestart` in `ecosystem.config.json` bring the app back.

### Does server.close wait for in-flight requests?

It stops the listener from accepting new connections and calls back once existing connections end. A keep-alive connection with no request in flight can hold it open, which is why the deadline exists; past `SHUTDOWN_TIMEOUT_MS` the process exits `1` whatever is still open.

### Why mongoose.disconnect and not connection.close?

On the 5.13 release the repository pins, `mongoose.disconnect()` closes every connection Mongoose holds, which is what a process exit wants. `mongoose.connection.close()` closes only the default connection; the two are the same here, and `disconnect` stays right if a second connection is added later.

### Will the integration test be flaky in CI?

It waits for the app's own `Listening to port` line before sending the signal, and reads the exit event rather than sleeping, so it does not depend on timing. It needs a MongoDB like the rest of the integration suite, which `.travis.yml` already provides with the `mongodb` service.

## More Mongoose jobs

- [Add Health Checks to an Express and Mongoose API](https://getrush.ai/run/add-health-checks/mongoose/)
- [Add OpenTelemetry Tracing to an Express and Mongoose API](https://getrush.ai/run/add-opentelemetry/mongoose/)
- [Add Optimistic Locking to a Mongoose API](https://getrush.ai/run/add-optimistic-locking/mongoose/)

## The same job on other stacks

- [Add Graceful Shutdown to a Node.js Server](https://getrush.ai/run/add-graceful-shutdown/nodejs/)
- [Add Graceful Shutdown and Zero-Downtime Reloads with PM2](https://getrush.ai/run/add-graceful-shutdown/pm2/)
- [Add Graceful Shutdown to a Quarkus Service](https://getrush.ai/run/add-graceful-shutdown/quarkus/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
