# Add Graceful Shutdown to a Leptos Axum Server

Yes. An agent makes your Leptos server finish in-flight requests on SIGTERM and Ctrl-C with axum's graceful shutdown, proves it with a signal test, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-graceful-shutdown/leptos/). 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 server starts and stops today. In a project generated from leptos-rs/start-axum with `cargo leptos new`, `src/main.rs` is gated on the `ssr` feature: a `#[tokio::main]` `main` reads `get_configuration(None)`, calls `generate_route_list(App)`, builds an axum `Router` with `leptos_routes`, a `fallback` of `leptos_axum::file_and_error_handler(shell)` and `with_state(leptos_options)`, binds a `TcpListener` to the configured `site_addr` of `127.0.0.1:3000`, and ends with `axum::serve(listener, app.into_make_service()).await.unwrap()`. Nothing listens for a signal, so a `SIGTERM` from a container runtime or an orchestrator kills the process mid-response. `Cargo.toml` has `axum` and `leptos_axum` at 0.8.0 and `tokio` 1 with only the `rt-multi-thread` feature, all optional behind `ssr`; `signal` and `macros` are not enabled. `src/lib.rs` has the `hydrate` entry point and `src/app.rs` the `App` component. `end2end/` holds a Playwright test against `http://localhost:3000/`, `Cargo.lock` is ignored by `.gitignore`, and `rust-toolchain.toml` names nightly only when the template question was answered that way.

The change is confined to `main.rs` and `Cargo.toml`. `tokio` gains the `signal` feature so `tokio::signal::ctrl_c` and the Unix `signal(SignalKind::terminate())` stream are available, and `macros` so `tokio::select!` can wait on both. A `shutdown_signal` async function waits for either, with the terminate branch behind `#[cfg(unix)]` and a pending future on other platforms, and logs one line through `leptos::logging::log!` when it fires. The last line of `main` becomes `axum::serve(listener, app.into_make_service()).with_graceful_shutdown(shutdown_signal()).await`, which stops accepting connections, lets requests already in progress finish, and then returns so the process exits with status zero. The `hydrate` build is untouched because every new line sits inside the existing `ssr` gate.

Proving it needs a build and a signal. In its sandbox the agent installs `cargo-leptos` with `cargo install cargo-leptos --locked`, adds the `wasm32-unknown-unknown` target, and runs `cargo leptos build`. It then starts the server, opens a request to `/` that is still being served, sends `SIGTERM` to the process, and checks two things: the response completes with the full page, and the process exits with status zero within the time the test allows. The same script runs once more with `SIGINT` for the Ctrl-C path. `cargo clippy --features ssr` runs over the new code, and `cargo leptos end-to-end` runs the Playwright test to show the page still renders.

The agent also checks what will deliver the signal. If the repository has a `Dockerfile`, its `CMD` or `ENTRYPOINT` must exec the server binary directly, not through `sh -c`, or the shell receives the signal and the server never does; the agent fixes the form if needed and says so. The pull request description names the grace period the deployment grants after `SIGTERM` as the number to set beside this change, because the server now waits for in-flight requests and the orchestrator decides how long that wait may last.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add graceful shutdown to this Leptos application generated from the start-axum template. Read Cargo.toml, src/main.rs, src/lib.rs, src/app.rs, end2end/tests/example.spec.ts and any Dockerfile first. Enable the signal and macros features on tokio inside the existing ssr feature. Write an async shutdown_signal function in main.rs that completes on Ctrl-C or, on Unix, SIGTERM, logs one line through the leptos logging macro, and pass it to axum::serve through with_graceful_shutdown so the server finishes in-flight requests and exits with status zero. Keep every new line inside the ssr gate. Install cargo-leptos and the wasm32 target, run cargo leptos build, then start the server, hold a request to / open, send SIGTERM and confirm the response completes and the exit status is zero; repeat with SIGINT. Run cargo clippy --features ssr and cargo leptos end-to-end. If a Dockerfile runs the binary through a shell, change it to exec form and explain why. Open a pull request with the signal test output and a note on the deployment's grace period.",
  "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 `Cargo.toml` and `src/main.rs`, and a `Dockerfile` only if its entrypoint had to move to exec form. Its description pastes the output of the signal script for both `SIGTERM` and `SIGINT`: the full response arriving after the signal, the log line, and the exit status, followed by the `clippy` result and the Playwright run.

Before merging, a reviewer checks that the deployment's grace period is longer than the slowest request the server handles, decides whether a hard timeout should cap the wait so a stuck connection cannot hold a rollout, and looks at whether any background task the app may add later needs its own shutdown hook, which the description names as the next step.

## Run it on every Leptos service

A team with several Leptos services sends this body once per repository from its own server, each a `POST /o/{org}/sessions` with that 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 `main.rs`: one on `leptos_actix` gets the equivalent for Actix's server handle, and one that already passes a future to `with_graceful_shutdown` ends with a note and no change.

Once shutdown is handled, an automation on the Project with a `github` trigger on `pull_request.opened` and the prompt "if this pull request spawns a task with tokio::spawn in main.rs or adds a Dockerfile entrypoint in shell form, comment with the line and what it means for shutdown" starts one run per pull request. The trigger adds the pull request after the prompt, and only work by an owner, member or collaborator fires it.

## Why run it on Rush?

The change is a few lines, and the cost of getting it wrong is a request cut off during every deploy. What takes time is proving it: building a Leptos app needs `cargo-leptos`, the wasm target and a Sass compiler, and the test needs a real process, a real open request and a real signal. The agent does all of that in its own sandbox and keeps the output.

The script that sends the signal and reads the exit status is in the run's record, so a reviewer can see the response completing after `SIGTERM` rather than trusting a description. A team with many services runs the same request across all of them at once, each in its own sandbox.

## Frequently asked questions

### Which signals does it handle?

`SIGINT`, the Ctrl-C from a terminal, on every platform through `tokio::signal::ctrl_c`, and `SIGTERM` on Unix, which is what Docker, systemd and Kubernetes send first. On Windows the terminate branch compiles to a future that never completes, so only Ctrl-C applies there.

### Does it change the hydrate build or the client bundle?

No. The new code lives inside the `#[cfg(feature = "ssr")]` block in `main.rs`, and the `tokio` features change only the optional dependency the `ssr` feature enables. The wasm build in `cargo leptos build` is identical.

### What if a request never finishes?

axum's graceful shutdown waits for every in-flight connection, so a stuck one holds the process until the orchestrator's grace period ends and it sends `SIGKILL`. The description says this and offers a hard timeout around the serve future as a follow-up, rather than picking a number for the team.

### Why does the Dockerfile matter?

A `CMD` written as a string runs under `sh -c`, and the shell gets the `SIGTERM` while the server keeps running until it is killed. The exec form, a JSON array naming the binary, makes the server process 1 so the signal reaches the new handler.

## More Leptos jobs

- [Add Health Checks to a Leptos App](https://getrush.ai/run/add-health-checks/leptos/)
- [Add i18n to a Leptos App](https://getrush.ai/run/add-i18n/leptos/)
- [Add Open Graph Tags to a Leptos App](https://getrush.ai/run/add-open-graph-tags/leptos/)

## The same job on other stacks

- [Add Graceful Shutdown to a Litestar App](https://getrush.ai/run/add-graceful-shutdown/litestar/)
- [Add Graceful Shutdown to an Express and Mongoose API](https://getrush.ai/run/add-graceful-shutdown/mongoose/)
- [Add Graceful Shutdown to a Node.js Server](https://getrush.ai/run/add-graceful-shutdown/nodejs/)

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