# Add Request Timeouts to an Echo App

Yes. An agent sets read, write and idle timeouts on your Echo server, adds a per-request deadline middleware, tests both with a slow client, and opens a PR.

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

## What the agent does

The agent starts from what the server does today when a client is slow. In an Echo API like xesina/golang-echo-realworld-example-app, `go.mod` names `github.com/labstack/echo/v4` v4.1.16 and `github.com/jinzhu/gorm` v1.9.8 on a `go 1.18` directive, and `main.go` ends with `r.Logger.Fatal(r.Start("127.0.0.1:8585"))`. `Start` serves on the `*http.Server` Echo keeps in its `Server` field, and that server has every timeout at zero: a client that sends headers one byte a minute holds a connection forever, a response to a client that stops reading never finishes, and an idle keep-alive connection is never closed. `router/router.go` builds the `*echo.Echo` with `RemoveTrailingSlash` as a pre-middleware, the request logger and CORS, and `handler/routes.go` registers the `/api` routes under the JWT middleware in `router/middleware/jwt.go`.

Then it checks what the pinned Echo version offers, because the obvious answer does not exist here. The `middleware` package in v4.1.16 has `BodyLimit`, `Logger`, `Recover`, `RequestID` and the rest, but no `Timeout`; that middleware arrived in v4.2.0. The agent does not bump Echo, since a framework upgrade on a service with its own JWT middleware is a separate change, and says so in the pull request. It also notes that the handlers reach GORM v1 through `store/article.go` and `store/user.go`, and that library takes no `context.Context`, so a per-request deadline cannot cancel a running SQLite query; what it can do is stop the handler from writing after the deadline and return 503.

The change comes in two layers. In `main.go` the agent sets `r.Server.ReadHeaderTimeout`, `ReadTimeout`, `WriteTimeout` and `IdleTimeout` from four values in one place, with a comment that `Start` uses that server, so the settings take effect without a second `http.Server`. Then it adds `router/middleware/timeout.go`: a middleware that wraps `c.Request().Context()` with `context.WithTimeout`, stores it back with `c.SetRequest`, runs the handler, and if the deadline passed before the handler wrote a response answers `503` through `echo.NewHTTPError` so the existing error handling formats it like every other error. The JWT-protected `/api/articles` group and the public `/api/tags` route get the same deadline; the `/swagger/*` route mounted in `main.go` is left out, since it serves static files from the committed `docs` package.

Tests cover both layers. A test in `router/middleware` serves a handler that sleeps past a short deadline and asserts the 503 and that a fast handler is untouched. A test in package `main` starts the real server on a `net.Listen("tcp", "127.0.0.1:0")` listener assigned to `e.Listener`, opens a raw TCP connection, writes half a request line and asserts the server closes it after `ReadHeaderTimeout`. The agent runs `gofmt -l`, `go vet ./...` and `go test -v -race ./...` as `Makefile` does, which also runs the handler suite against its SQLite fixture in `./../realworld_test.db`, and `go build -v ./...` as `.github/workflows/go.yml` does on Go 1.18.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add request timeouts to this Echo application. Read go.mod, main.go, router/router.go, router/middleware/jwt.go, handler/routes.go, handler/handler_test.go, db/db.go, Makefile and .github/workflows/go.yml first. Echo is pinned to v4.1.16, which has no Timeout middleware; do not upgrade it. In main.go set ReadHeaderTimeout, ReadTimeout, WriteTimeout and IdleTimeout on the http.Server that Start uses, with the four values defined together. Add router/middleware/timeout.go: a middleware that puts a context.WithTimeout deadline on the request, runs the handler, and answers 503 through echo.NewHTTPError if the deadline passes before the handler responds; apply it to the /api group and leave /swagger/* alone. Note in the pull request that GORM v1 takes no context, so the deadline bounds the response and not a running query. Write a middleware test for the 503 and the fast path, and a main package test that starts the server on a 127.0.0.1:0 listener, sends a partial request over raw TCP and asserts the connection closes after ReadHeaderTimeout. Run gofmt -l, go vet ./..., go build -v ./... and go test -v -race ./..., and open a pull request that explains each timeout and its value.",
  "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 `main.go` and `handler/routes.go`, adds `router/middleware/timeout.go` and two test files. The description has a table of the four server timeouts with what each one bounds, says which routes carry the per-request deadline, and states plainly that a GORM v1 query keeps running past the deadline because the library takes no context.

The run's record keeps the `go test -race` output, including the raw TCP test closing after `ReadHeaderTimeout` and the middleware's 503 beside the existing handler tests, so a reviewer can see the behaviour rather than infer it from the diff.

Before merging, a reviewer sets the values to the service's real traffic: `WriteTimeout` has to exceed the slowest legitimate response, and `IdleTimeout` should sit below the idle timeout of whatever load balancer is in front. The agent chose conservative values and marked them in one block to change together.

## Run it on every alert on connections piling up

When a Grafana alert on open connections or request duration fires for this service, a contact point can call the Project automation's `webhook` trigger directly, since Grafana contact points can send a custom `Authorization: Bearer <secret>` header. The contact point also sends the trigger's URL an `Idempotency-Key` made from the alert's fingerprint, so a repeated notification starts no second run. The alert body becomes the event text, and the prompt tells the agent to read the alert, check which timeout is missing or too high, and open a pull request with the change and a test.

A monitor that cannot set a header is handled by a small handler on the team's own server that receives it and sends `POST /o/{org}/sessions` with this page's body, the repository in `resources` and a `request_id` that is a UUID v5 of the alert id, so a retried delivery returns the run already started.

## Why run it on Rush?

A missing timeout is invisible until a slow client finds it, and reproducing one by hand means a raw socket and a stopwatch. The agent does that in its own sandbox against a real listener, with the race detector on, and the tests stay in the repository so the values are checked on every change.

Every command the agent ran stays with the run, from `go vet` to the test output, so the pull request can cite a closed connection and a 503 rather than describe them. Doing this for every Go service behind one load balancer at once costs no more attention than one, because each run has its own machine and its own record.

## Frequently asked questions

### Why not use Echo's Timeout middleware?

The repository pins Echo v4.1.16, and its `middleware` package has no `Timeout`; it was added in v4.2.0. Upgrading Echo on a service with its own JWT middleware is its own change. The deadline middleware the agent writes uses only `context.WithTimeout` and `c.SetRequest`, both present in v4.1.16.

### Will the per-request deadline stop a slow database query?

No. The handlers call GORM v1 through `store/article.go` and `store/user.go`, and that library takes no `context.Context`, so a query runs to completion. The deadline stops the handler from writing a late response and returns 503 instead. Cancelling queries needs a database layer that accepts a context, which the agent names as follow-up work.

### Which of the four server timeouts matters most?

`ReadHeaderTimeout`, because without it a client can hold a connection open indefinitely by never finishing its headers. `ReadTimeout` bounds the whole request including the body, `WriteTimeout` bounds the response, and `IdleTimeout` closes keep-alive connections that go quiet. Each is set on `r.Server`, the `http.Server` that `Start` uses.

### Does this change the Dockerfile or CI?

No. The runtime image already runs the binary directly and `.github/workflows/go.yml` already runs `go build` and `go test` on Go 1.18, so the new tests run there with no workflow change. The agent does note that the Dockerfile's build stage pins `golang:1.12.1`, older than the `go 1.18` directive, as a separate problem.

## More Echo jobs

- [Add Security Headers to an Echo API](https://getrush.ai/run/add-security-headers/echo/)
- [Add Structured Logging to an Echo API](https://getrush.ai/run/add-structured-logging/echo/)
- [Fix Vulnerable Go Modules in an Echo API](https://getrush.ai/run/fix-vulnerable-dependencies/echo/)

## The same job on other stacks

- [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/)
- [Add Request Timeouts to a Hono App](https://getrush.ai/run/add-request-timeouts/hono/)

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