# Add Graceful Shutdown to an Express and Sequelize App

Yes. An agent makes your Express and Sequelize app stop cleanly on SIGTERM: the listener closes, in-flight requests finish, Sequelize closes, and it opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-graceful-shutdown/sequelize/). 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, because what it holds open is what a shutdown has to release. In an app laid out like the `express-main-example` in sequelize/express-example, `index.js` calls `sequelize.authenticate()` inside `assertDatabaseConnectionOk`, exits `1` with the error message if that fails, then calls `app.listen(PORT)` with `PORT` as a constant `8080` and drops the returned server, so nothing in the file can close it. There are no signal handlers at all: a `SIGTERM` from a container runtime kills the process mid-request. `sequelize/index.js` constructs one `Sequelize` with `dialect: 'sqlite'`, a `storage` path under `sqlite-example-database/`, `logQueryParameters` and `benchmark` on, defines the three models from `sequelize/models/` and applies the associations in `extra-setup.js`. `express/app.js` wraps every route handler in `makeHandlerAwareOfAsyncErrors` and mounts five REST routes per model. `package.json` asks for `sequelize` ^6.3.3, `express` ^4.17.1 and `sqlite3` ^5.0.0 with `node >=10`, and `.npmrc` sets `package-lock=false`, so there is no lockfile.

The agent keeps the server `app.listen` returns and adds one `shutdown(signal)` function registered for `SIGTERM` and `SIGINT`. It logs the signal with the `console.log` style the file uses, calls `server.close(callback)` so the listener stops accepting while requests already in a handler run to completion, then in the callback calls `sequelize.close()`, which ends the SQLite connection and lets the driver release the file handle, and exits `0`. A timer started with the signal forces `process.exit(1)` if the close has not finished within a deadline, read from a `SHUTDOWN_TIMEOUT_MS` environment variable with a default, and `unref()` keeps the timer from holding the process open itself. A flag ignores a second signal while the first is being handled.

Two details come from this repository rather than from a template. `sequelize.close()` is final: the instance cannot be reused after it, which is fine here because the process exits, but the agent says so in the description for anyone who later adds a restart path. And with SQLite, a process killed between a write and its commit leaves a journal file beside `example-db.sqlite` that the next start has to recover, which is the concrete thing the clean close prevents and what the pull request says the change is for.

There is no test runner in the repository, so the agent adds a script rather than a framework: `scripts/check-shutdown.js` spawns `node index.js` with a fresh example database from `npm run setup-example-db`, waits for the `Express server started` line, opens a request to `/api/orchestras?includeInstruments`, sends `SIGTERM`, and asserts the request answers `200`, the shutdown log lines appear in order, and the exit code is `0`; a second case sets the deadline to a few milliseconds against a route that waits and asserts exit code `1`. It is wired as `npm run check-shutdown` and the agent runs it, along with `npm install` and `npm start` to see the app still boots, quoting each.

## 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 Sequelize app. Read index.js, sequelize/index.js, express/app.js, package.json and sqlite-example-database/setup.js first. Keep the server app.listen returns. On SIGTERM and SIGINT: log the signal, call server.close so in-flight requests finish, then sequelize.close(), then exit 0. Read a SHUTDOWN_TIMEOUT_MS environment variable with a default and force exit 1 past it with an unref'd timer; ignore a repeated signal while a shutdown is running. Add scripts/check-shutdown.js, run as npm run check-shutdown, that spawns index.js against a fresh example database, holds a request open, sends SIGTERM and asserts the request completes and the exit code is 0, plus a case that proves the deadline. Run npm install, npm run setup-example-db, npm start once to see it boot, and npm run check-shutdown, 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 `index.js` and `package.json` and adds `scripts/check-shutdown.js`; no model, route or Sequelize setup file changes. The description shows the signal flow in a few lines, names the deadline variable and its default, and quotes the check script's output with the request's status, the log lines in order and the two exit codes.

The run's record keeps the spawned process's output from the check, so a reviewer can read the signal arriving, the request finishing and the connection closing without starting the app.

Before merging, a reviewer sets the deadline below the platform's own grace period, so the app exits on its own terms before the runtime kills it, and decides whether to replace `console.log` with a logger, which the agent left as it found it.

## Run it on every deploy

The check earns its keep after every deploy, when the old process receives the signal for real. A handler on the reader's server, the one that already rolls out the container, calls `POST /o/{org}/sessions` after each rollout with a prompt asking the agent to read the previous process's last log lines and its exit code from the platform and report whether the shutdown reached `sequelize.close()` within the deadline. The handler sends a `request_id` that is a UUID v5 of the deployment id, so a retried hook returns the run already started.

Each run reads logs through a connection the Project names and produces a short report: the signal seen, the time from signal to exit, 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, and a clean deploy produces a report and nothing else.

## Why run it on Rush?

The bug is a process that dies with a request half-answered and a database file half-written, and it only shows up under a real signal with a real request open. On a laptop that is two terminals and a guess about timing. In a Rush sandbox the agent writes the handler, spawns the app, sends the signal while a request is in flight and reads the exit code, with the whole sequence in the record.

The pull request carries the script that will catch a regression when someone adds a queue or a second connection, and it is small enough to read in a minute. Across every Node service a team keeps, the job runs in parallel, one sandbox and one pull request each, each written against that service's own start file.

## Frequently asked questions

### Why close the server before Sequelize?

Because a handler that is still running may need the database. `server.close` stops new connections and calls back when open ones end; only then is it safe to end the Sequelize connection and exit.

### Does this matter for SQLite?

Yes. A process killed between a write and its commit leaves a journal file beside the database that the next start has to roll back or recover. Closing the connection on the way out finishes the write and releases the file handle.

### What if a request never finishes?

The deadline timer exits `1` past `SHUTDOWN_TIMEOUT_MS`, whatever is still open, and the check script has a case for exactly that. The timer is unref'd so it cannot keep an otherwise finished process alive.

### Why a script instead of a test framework?

The repository has no test runner and `node >=10` in its engines, so adding one would be a bigger decision than the task. The script uses only `child_process` and `http` from Node, runs with `npm run check-shutdown`, and can move into whatever framework the project adopts later.

## More Sequelize jobs

- [Add Health Checks to an Express and Sequelize API](https://getrush.ai/run/add-health-checks/sequelize/)
- [Add Input Validation to a Sequelize and Express API](https://getrush.ai/run/add-input-validation/sequelize/)
- [Add Migrations to a Sequelize Express App](https://getrush.ai/run/add-migrations/sequelize/)

## The same job on other stacks

- [Add Graceful Shutdown to a Socket.IO Server](https://getrush.ai/run/add-graceful-shutdown/socket-io/)
- [Add Graceful Shutdown on SIGTERM to a Tokio Server](https://getrush.ai/run/add-graceful-shutdown/tokio/)
- [Add Graceful Shutdown to an Actix Web App](https://getrush.ai/run/add-graceful-shutdown/actix/)

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