# Add Graceful Shutdown to a Node.js Server

Yes. An agent makes your Node.js server stop cleanly on SIGTERM: finish in-flight requests, close the database and exit, with tests and a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-graceful-shutdown/nodejs/). 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 is stopped today. In an Express app shaped like OWASP/NodeGoat, server.js connects with `MongoClient.connect(db, (err, db) => ...)` from the mongodb 2.x driver, builds the app inside the callback and ends with `http.createServer(app).listen(port, ...)`, discarding the server object. There is no signal handler anywhere, so a SIGTERM kills the process mid-request and leaves the Mongo connection to time out on the other side. The Dockerfile sets no `CMD` and no `STOPSIGNAL`; docker-compose.yml starts the web service with `command: sh -c "until nc -z ...; do sleep 2; done"` with `npm start` inside the loop, so `sh` is PID 1 and does not forward signals to Node, and `docker compose stop` waits out its grace period and kills. The Procfile runs `forever -m 5 server.js`, and the e2e workflow starts the server with `npm start -- --silent &` and relies on the job ending to stop it.

The change keeps the server object and gives it a stop. A `shutdown(signal)` function in a new app/shutdown.js, written in the CommonJS style and double-quoted strings `.jshintrc` enforces, is registered for `SIGTERM` and `SIGINT`. It logs the signal, calls `server.close()` so the listener stops accepting and the callback fires once the last open connection has finished, closes the Mongo client with `db.close()`, and exits 0. A timer, a few seconds by default and read from an environment variable, forces exit 1 if a request will not finish, so a stuck handler cannot hold a deploy. Idle keep-alive sockets are the catch: `server.close()` leaves them until `keepAliveTimeout` runs out, so the agent calls `server.closeIdleConnections()` where the runtime provides it and otherwise lets the timer end the process, and writes that reasoning into a comment next to the call.

The container is fixed so the signal arrives at all. The compose `command` is changed to let `sh` `exec` into Node after the wait loop, so Node becomes PID 1 and receives SIGTERM directly, and the Dockerfile gains `CMD ["node", "server.js"]` so an image run without compose behaves the same. `stop_grace_period` is set on the web service a little above the shutdown timer so compose waits for the drain. The Procfile's `forever -m 5 server.js` gets `--killSignal=SIGTERM`, because forever stops its child with SIGKILL unless told otherwise, and the README's Option 2 instructions are updated where they describe stopping the stack.

Tests are the gap the repository already has: `grunt test` runs `mochaTest:unit` on `test/unit/*.js`, and no test/unit directory exists, so `npm test` passes by running nothing. The agent adds test/unit/shutdown.js with mocha and should, which are devDependencies: it starts the server on an ephemeral port with a fake db object whose `close` records the call, opens a request that the handler holds open, sends the shutdown, and asserts the response completes, `close` was called once and no new connection is accepted. It runs `npx jshint .` as lint.yml does and `grunt test`, and starts the stack with `docker compose up`, stops it, and reads the timing and the log line in the output to show the drain happened.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add graceful shutdown to this Node.js server. Read package.json, server.js, config/config.js, config/env/all.js, Dockerfile, docker-compose.yml, Procfile, Gruntfile.js, .jshintrc and the workflows under .github/workflows first. Keep the http.Server object that listen returns and add a shutdown function, in a new app/shutdown.js following the repository's CommonJS style and jshint rules, registered for SIGTERM and SIGINT: log the signal, call server.close so in-flight requests finish, close the MongoDB client, exit 0, and force exit 1 after a timeout read from an environment variable with a default of a few seconds. Change the compose command so the shell execs into node after the wait loop, add a CMD to the Dockerfile, and set stop_grace_period on the web service above the timeout. Add --killSignal=SIGTERM to the forever command in the Procfile so forever stops the child with SIGTERM instead of its SIGKILL default. Add test/unit/shutdown.js with mocha and should, which the test task already expects to find under test/unit, covering an in-flight request completing, the database close being called once, and new connections being refused. Run npx jshint . and grunt test, then docker compose up and docker compose stop and record how long the stop takes. Open a pull request with the test output and the compose timings.",
  "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 on its own branch that adds app/shutdown.js and test/unit/shutdown.js, changes the last lines of server.js to keep the server object and register the handlers, adds a `CMD` to the Dockerfile, changes the `command` and adds `stop_grace_period` on the web service in docker-compose.yml, adds one flag to the Procfile, and edits the README's stop instructions. package.json is unchanged, because mocha and should are already devDependencies and the shutdown code uses only `http` and the existing driver.

The description quotes the `grunt test` run, which for the first time executes a unit test, the jshint result, and the compose stop before and after: the before with the grace period expiring and the container killed, the after with the shutdown log line and the container exiting on its own. It also says in one line that `sh -c` without `exec` was why the signal never arrived.

Before merging, a reviewer checks the timeout default against the longest request the app serves, decides whether SIGINT should behave the same as SIGTERM in development, and whether the e2e workflow should stop the server through the new path rather than by the job ending. A follow-up on the same session can make that workflow change.

## Run it on every deploy that drops requests

This is a fix that gets written after a deploy drops requests and forgotten before the next one: a `POST /o/{org}/sessions` with this prompt and the repository in `resources`, sent from the terminal while the incident is fresh, gets the branch ready without anyone staying late. The run continues in its own sandbox after the laptop closes. The sandbox parks with its disk when the turn ends, so a follow-up such as `also stop accepting new sessions during the drain and return 503 from the health route` wakes it with the branch and the containers still built.

With a webhook URL on the API key, Rush posts `run.completed` or `run.failed` with the `session_url` when the turn ends. A team with several Node services behind the same load balancer sends the same prompt to each repository, one run per repository, and each run reads that service's own startup file and container setup.

## Why run it on Rush?

Graceful shutdown is only proven by stopping a running process with a request in flight, which is exactly the experiment nobody runs on a laptop. The agent does it in its own sandbox: the unit test holds a request open and sends the signal, and the compose stop shows the container exiting on its own instead of being killed, with the timings in the run's record.

The record is also where the container finding lives. The transcript shows the agent reading the compose `command`, recognising that `sh` as PID 1 swallows the signal, and choosing `exec` over a process manager. A reviewer who wants a different timeout or a readiness flip during the drain can say so in a follow-up and the parked sandbox makes the change with the test already written.

## Frequently asked questions

### Why did SIGTERM never reach the app before?

Because docker-compose.yml runs the web service through sh -c with a wait loop and npm start inside it, so sh is PID 1, and sh does not forward signals to its children. Changing the command to exec into node after the loop makes Node PID 1 and the signal arrives directly.

### What happens to a request that is still running?

server.close stops the listener and waits for open connections to finish, so the response is sent. If a handler will not finish within the timeout, the forced exit returns 1 so the orchestrator sees a failure rather than a hang; the default is a few seconds and an environment variable changes it.

### Does it change how forever or Heroku run the app?

Only by one flag. The Procfile still runs forever -m 5 server.js, with --killSignal=SIGTERM added, because forever's default exit signal is SIGKILL and the shutdown handler would never run. With that flag the same drain path runs under forever as under Docker.

### Why add a unit test when the repo has Cypress?

Because the Gruntfile's test task already looks for test/unit/*.js and finds nothing, so npm test has been passing with zero tests. A mocha test with a held-open request is the direct proof, and it runs without a browser or a database.

### Will the health check or load balancer notice the drain?

Not in this change. The pull request suggests a follow-up that flips the health route to 503 when shutdown begins so a balancer stops routing new requests, and that can be done on the same session.

## More Node.js jobs

- [Add a Health Check Endpoint to a Node.js App](https://getrush.ai/run/add-health-checks/nodejs/)
- [Add Input Validation to a Node.js Express App](https://getrush.ai/run/add-input-validation/nodejs/)
- [Move Express Sessions from MemoryStore to MongoDB in a Node.js App](https://getrush.ai/run/add-mongo-session-store/nodejs/)

## The same job on other stacks

- [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/)
- [Add Graceful Shutdown to a React Router App](https://getrush.ai/run/add-graceful-shutdown/react-router/)

## 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/)
