# Add Request Timeouts to an Axum API

Yes. An agent adds a tower timeout layer to your Axum router, maps the elapsed error onto the API's own error type as a 408, tests it and opens a PR.

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

## What the agent does

The agent starts from how the server is assembled. In an Axum service shaped like launchbadge/realworld-axum-sqlx, `Cargo.toml` pins `axum 0.3.4` with the `tower-log` feature, `tower 0.4.11` with no extra features, `tower-http 0.2.0` with `trace`, `sqlx 0.5` and `tokio 1.14`. `src/http/mod.rs` builds the whole stack in one `serve` function: `api_router()` merges the `users`, `profiles` and `articles` routers, then `.layer(ServiceBuilder::new().layer(AddExtensionLayer::new(ApiContext { config, db })).layer(TraceLayer::new_for_http()))`, and `axum::Server::bind` listens on `0.0.0.0:8080`. Nothing in that chain bounds how long a request may run, and `src/main.rs` builds the pool with `PgPoolOptions::new().max_connections(50)` and no timeout either, so a slow query or a stalled client holds a worker and a connection for as long as it likes.

Tower ships the layer, so the first change is one line in `Cargo.toml`: `tower = { version = "0.4.11", features = ["timeout"] }`. The `timeout` feature is not in tower's defaults, which is why the crate is already a dependency and still has no `TimeoutLayer`. In `serve`, the agent adds `.layer(HandleErrorLayer::new(handle_timeout))` followed by `.timeout(config.request_timeout)` to the `ServiceBuilder`, below `TraceLayer` so the trace span still records the status of a request that timed out. `HandleErrorLayer` is in `axum::error_handling` in this version and is what turns a `BoxError` from a middleware into a response, because tower's timeout service fails with `tower::timeout::error::Elapsed` rather than answering.

The timeout becomes an API error rather than a stray string. `src/http/error.rs` defines `Error` with `Unauthorized`, `Forbidden`, `NotFound`, `UnprocessableEntity`, `Sqlx` and `Anyhow` variants and an `IntoResponse` impl that maps each to a status; the agent adds a `Timeout` variant that maps to `408 Request Timeout` and uses it from the handler, so clients see the same error shape the rest of the API already returns. The duration comes from `Config` in `src/config.rs`, which already parses `database_url` and `hmac_key` with `clap` from flags or environment: a new `request_timeout_secs` field with a default keeps `.env.sample` optional and keeps the CI step in `.github/workflows/rust.yml` that starts the binary with `cargo run&` for the Realworld Postman collection working unchanged.

The repository has no handler tests, so the agent writes the layering as a small function that takes a `Router` and a `Duration` and returns the wrapped router, then tests it without a database: a test router with one route that sleeps past the limit and one that answers at once, driven through `tower::ServiceExt::oneshot`. The slow route must answer `408` with the error body; the fast one must be untouched; the real `api_router()` is built through the same function so the test covers the code path production uses. The agent runs `cargo build` and `cargo test` in the sandbox and pastes both outputs in the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add a request timeout to this Axum API and open a pull request. Read Cargo.toml, src/main.rs, src/config.rs, src/http/mod.rs and src/http/error.rs first. Enable the timeout feature of the tower crate that is already a dependency, and in serve() add HandleErrorLayer and a timeout to the existing ServiceBuilder, below TraceLayer, so traced requests record the timeout status. Add a Timeout variant to the Error enum in src/http/error.rs that maps to 408 Request Timeout and return it from the error handler. Read the duration from a new request_timeout_secs field on Config, parsed by clap from the environment like database_url, with a default of 30 seconds so .env.sample and the CI workflow need no change. Factor the layering into a function that takes a Router and a Duration, use it for the real router, and test it with a router that has one route sleeping past the limit and one answering at once, driven with tower::ServiceExt::oneshot, asserting 408 on the slow route and 200 on the fast one. Run cargo build and cargo test and paste the output in the pull request. Do not change the routes, the Realworld error body format or the Postman step in .github/workflows/rust.yml.",
  "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 touching five files: the feature flag in `Cargo.toml` and the matching `Cargo.lock` lines, the `request_timeout_secs` field in `src/config.rs`, the `Timeout` variant and its status mapping in `src/http/error.rs`, the layering function and the two new layers in `src/http/mod.rs`, and a test module. The description shows the `cargo test` output from the sandbox, with the timeout test listed by name, and the `cargo build` output with its warnings, if any.

The existing workflow in `.github/workflows/rust.yml` runs `cargo build --verbose` and `cargo test --verbose` against a Postgres service and then the Realworld Postman collection against the running binary, so the pull request gets both checks without any change to the workflow. Because the timeout has a default, the `cargo run&` step starts as before.

A reviewer checks the order of the layers in `serve`, that the `408` body uses the same JSON shape as the other errors, that the default is longer than the slowest legitimate request the API serves (the article listing with its `limit` and `offset` is the one to think about), and that the tests cover both the timed-out and the normal path. Then they set `REQUEST_TIMEOUT_SECS` per environment where the defaults are not right.

## Run it on every new backend service

A team that runs several Rust services sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own `Cargo.toml` and server setup, so a service already on a newer `axum` gets the `TimeoutLayer` wired the way that version expects, and a service that already has a timeout gets a pull request that only adds the missing test. Each run opens its own pull request.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request from. A sweep across many services can be sent in a single burst; the key runs `max_concurrent` of them, four by default and up to 100, and every other one answers `202` with `status: "queued"` and starts, oldest first, when a slot frees.

## Why run it on Rush?

A timeout is a few lines, but it is only trustworthy once something has actually hit it. In a Rush sandbox the agent compiles the crate, runs a test that really sleeps past the limit and checks the `408` that comes back, and every command and its output stays in the run's record, so the pull request shows the behaviour rather than describing it.

The fiddly part is version-specific: where `HandleErrorLayer` lives in `axum 0.3`, which tower feature exposes the timeout, how the error type must change so the response matches the Realworld error format. The agent reads the versions from `Cargo.toml` and `Cargo.lock` and writes against those, and the same request works on the next service without anyone re-deriving it on a laptop.

## Frequently asked questions

### Why 408 and not 504?

The timeout fires inside this service, not at a proxy in front of it, and `408 Request Timeout` is the status the Realworld API's error type can carry without inventing a new body shape. If your deployment sits behind a gateway that maps upstream timeouts to `504`, the prompt can say so and the agent maps the variant to that status instead.

### Does the test need Postgres?

No. The layering is factored into a function that takes any `Router`, so the test wraps a router with one sleeping route and one fast route and drives it with `tower::ServiceExt::oneshot`. The production `api_router()` goes through the same function, which is what makes the test meaningful without a database.

### Will long article listings start failing?

Only if they take longer than the configured limit. The listing in `src/http/articles/listing.rs` pages with `limit` and `offset`, so a 30-second default is far above a healthy query; a reviewer who knows their data sets `REQUEST_TIMEOUT_SECS` higher before merging if needed.

### What about the database pool?

The pull request leaves `PgPoolOptions` alone and says so. A request-level timeout bounds the whole handler, including its wait for a connection; a separate pool acquire timeout is a reasonable follow-up, and the description names the option for the `sqlx 0.5` line the crate pins.

### Does the CI workflow change?

No. `.github/workflows/rust.yml` already builds, tests and runs the Postman collection against `cargo run`. The new field has a default, so the binary starts without a new environment variable and the collection runs as before.

## More Axum jobs

- [Add Request Tracing to an Axum API from a Linear Issue](https://getrush.ai/run/add-request-tracing/axum/)
- [Add Security Headers to an Axum API](https://getrush.ai/run/add-security-headers/axum/)
- [Add Soft Delete to an Axum API](https://getrush.ai/run/add-soft-delete/axum/)

## The same job on other stacks

- [Add Request Timeouts to an Echo App](https://getrush.ai/run/add-request-timeouts/echo/)
- [Add Request Timeouts to a Fiber App](https://getrush.ai/run/add-request-timeouts/fiber/)
- [Add Request Timeouts to a Gin API](https://getrush.ai/run/add-request-timeouts/gin/)

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