# Add Graceful Shutdown to an Actix Web App

Yes. An agent makes your Actix Web app drain on SIGTERM with a readiness flip, an explicit shutdown timeout and a closed SQLx pool, proves it with a test, in a PR.

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

## What the agent does

The agent reads what the server does on a signal today, because Actix already does part of this job. In an app like `basics/todo` in actix/examples, `Cargo.toml` takes `actix-web` 4.11, `actix-files` and `actix-session` with its cookie store from a workspace on edition 2024 with a minimum Rust of 1.98, plus `sqlx` 0.9 on the Tokio runtime with SQLite, `tera` 2 for templates, `dotenvor`, `env_logger` and `log`. `src/main.rs` loads `.env`, builds a `SqlitePool` through `db::init_pool` with a one-second `acquire_timeout`, and runs `HttpServer::new(...)` with the pool, the Tera instance, a cookie session and three error handlers, bound to `127.0.0.1:8080` with two workers. `HttpServer` installs its own handlers for `SIGINT`, `SIGTERM` and `SIGQUIT`, stops accepting connections, and waits up to its default 30 seconds for in-flight requests. So the process does not die mid-request today, and the pull request says so. What is missing is around that: nothing tells a load balancer the instance is leaving before the listener closes, the 30-second default is unrelated to any deployment's grace period, and the pool is dropped with the process rather than closed, so SQLite never gets its orderly close.

The agent restructures `main` so the shutdown is explicit and observable. `HttpServer` gets `.disable_signals()` and `.shutdown_timeout(10)`, the number chosen to sit inside a typical 30-second termination grace period with room for the drain delay. `run()` returns a `Server` whose `handle()` is cloned into a task that waits on `tokio::signal::unix` for `SIGTERM` and `SIGINT`, sets a shared `AtomicBool` named `draining`, sleeps for a short `PRE_STOP_DELAY` so the balancer sees the readiness change, and then calls `handle.stop(true).await`. The main task awaits the server, and when it returns calls `pool.close().await`, which lets SQLx finish checkpointing the SQLite file before the process exits. `/healthz` is added in `src/api.rs` and answers 200 until `draining` is set and 503 after, with the flag in `web::Data`, and the route is registered before the static files service so it is never shadowed.

The proof is an experiment staged in the sandbox, then written down as a test. The agent builds the binary, runs the migration with `sqlx migrate run` against a scratch `todo.db`, starts the server, opens a `POST /todo` whose body arrives at one byte per second with `curl --limit-rate`, sends `SIGTERM` to the process, and records that `/healthz` answers 503 at once, that the slow request still gets its redirect, and that the process exits after the request and before the timeout. `tests/shutdown.rs` repeats that in-process: it builds the same `App` on a random port with `actix_web::test` and a real pool, spawns a request that holds a connection, calls `stop(true)`, and asserts the response arrived and `pool.is_closed()` is true afterwards. `cargo test` and `cargo clippy --all-targets`, which the workspace's `justfile` runs, are the commands the pull request quotes.

Two things in the file are noted and left. The server binds `127.0.0.1`, so inside a container nothing outside can reach it; the pull request says so without changing it, since binding is a deployment decision. The `SESSION_SIGNING_KEY` is 64 zero bytes with a comment that says it is not suitable for production, and the agent repeats that note rather than generating a key in a change about shutdown.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add graceful shutdown to this Actix Web app. Read Cargo.toml, .env, README.md, src/main.rs, src/api.rs, src/db.rs, src/model.rs, src/session.rs and the migrations first, and say in the pull request what HttpServer already does on SIGTERM. Call disable_signals and shutdown_timeout(10) on the server; take its handle; spawn a task that waits for SIGTERM or SIGINT, sets a shared draining flag, waits a short pre-stop delay and calls stop(true); after the server future returns, close the SQLx pool. Add GET /healthz in api.rs that answers 200 until the flag is set and 503 after, registered before the static files service. In the sandbox, build the binary, run the migration on a scratch database, start the server, hold a POST /todo open with curl --limit-rate, send SIGTERM, and record that /healthz flips, the request completes and the process exits inside the timeout. Write tests/shutdown.rs that does the same in-process with actix_web::test, a real pool and stop(true), asserting the response arrived and the pool is closed. Do not change the bind address or the session key; note both. Run cargo test and cargo clippy --all-targets and open a pull request with the experiment transcript and the test output.",
  "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

The pull request changes `src/main.rs` and `src/api.rs`, adds `tests/shutdown.rs`, and adds `tokio` with its `signal` feature to `Cargo.toml` if the workspace does not already supply it. Its description opens with what `HttpServer` already did, then the experiment: the timestamps at which `SIGTERM` was sent, `/healthz` first answered 503, the slow request's redirect arrived and the process exited, followed by the `cargo test` and `clippy` output.

A rolling deploy now has a window in which the instance says it is leaving before it stops listening, a drain bounded by a number the team chose rather than a library default, and a database file that is closed by the pool instead of by the operating system.

Before merging, a reviewer sets the pre-stop delay and the timeout against the orchestrator's grace period, points the readiness probe at `/healthz`, and decides separately about the loopback bind and the placeholder session key the description calls out.

## Run it on every service that gets SIGTERM on every deploy

A team with several Rust services sends this body once per repository to `POST /o/{org}/sessions` from the terminal or a script, each with its own repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started. Each run reads its own entry point: a service on Postgres through `deadpool` closes that pool, one that already calls `disable_signals` gets its handler checked against the same experiment, and one with a background task gets that task told to stop before the drain.

Each run opens its own pull request on its own branch, and the experiment transcript for each is on its session, so the person who started the batch compares the drain timings from `GET /o/{org}/sessions`.

## Why run it on Rush?

Whether a server drains can only be seen at the moment a signal lands on a request in flight, and that moment is awkward to stage on a laptop with a real database file and a real slow client. The agent stages it in its own sandbox, with the binary it built, a migrated SQLite file and `curl` throttled to one byte a second, and writes the timestamps into the pull request.

The run keeps the build, the migration, the experiment and the test output, so review is about the delay and the timeout values rather than about whether the mechanism works. A service that already drains correctly gets a pull request that says so and adds only the readiness flip and the pool close.

## Frequently asked questions

### Actix already handles SIGTERM. What is the change for?

Three things it does not do: tell a load balancer the instance is leaving before the listener closes, use a drain timeout the deployment chose, and close the database pool. The pull request says plainly that in-flight requests were already safe and that the change is about the window around them.

### Why disable_signals and handle them by hand?

Because the readiness flip and the pre-stop delay have to happen before the listener stops, and the built-in handler stops the listener as soon as the signal arrives. Taking the handler over lets the app set `draining`, wait for the balancer to notice, and then call `stop(true)`, which runs the same drain the built-in path runs.

### Why 10 seconds?

It is a starting value, chosen to fit inside a 30-second grace period with the pre-stop delay before it and a margin after. The pull request names both numbers in one place in `main.rs` and asks the reviewer to set them from the real deployment's termination settings.

### Does closing the SQLite pool matter?

SQLx closes connections and finishes any write-ahead-log checkpoint when `close()` runs. Dropping the pool with the process usually leaves the file consistent, since SQLite recovers on the next open, but the recovery is work the next start does. An explicit close makes the shutdown clean and the test can assert it with `pool.is_closed()`.

### What about the loopback bind address?

`bind(("127.0.0.1", 8080))` makes the server unreachable from outside a container, which matters for any deployment that sends it `SIGTERM`. The agent points it out in the description and leaves it, because the address belongs to the deployment configuration and not to this change.

## More Actix Web jobs

- [Add Health Checks to an Actix Web Server](https://getrush.ai/run/add-health-checks/actix/)
- [Add Input Validation to an Actix Web App from a Linear Issue](https://getrush.ai/run/add-input-validation/actix/)
- [Add JWT Authentication to an Actix Web API](https://getrush.ai/run/add-jwt-auth/actix/)

## The same job on other stacks

- [Add Graceful Shutdown to an Axum API](https://getrush.ai/run/add-graceful-shutdown/axum/)
- [Add Graceful Shutdown to a Go chi API](https://getrush.ai/run/add-graceful-shutdown/chi/)
- [Add Graceful Shutdown to an Echo App](https://getrush.ai/run/add-graceful-shutdown/echo/)

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