# Add Rate Limiting to an Echo API

Yes. An agent moves your Echo v4 module to a release with the rate limiter middleware, puts a per-IP limit on the login and signup routes, and opens a PR with tests.

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

## What the agent does

The agent reads the module before it adds a middleware, because the obvious one may not exist at the version in `go.mod`. In an API like xesina/golang-echo-realworld-example-app, `go.mod` is at Go 1.18 with `github.com/labstack/echo/v4` 4.1.16, `jinzhu/gorm` 1.9, `dgrijalva/jwt-go` 3.2, `testify` 1.4 and `swaggo/echo-swagger`. Echo's `middleware.RateLimiter` arrived in v4.2.0, so the first step is `go get github.com/labstack/echo/v4@latest` within v4, followed by `go mod tidy` and the existing suite, 25 `Test` functions across `handler/handler_test.go`, `user_test.go` and `article_test.go` that run against `db.TestDB()` with fixtures, to prove the bump broke nothing. `router/router.go` builds the app with `RemoveTrailingSlash`, `Logger`, a permissive `CORS` and a validator; `handler/routes.go` registers `/users` and `/users/login` as the unauthenticated group, `/user`, `/profiles` and most of `/articles` behind the repository's own JWT middleware in `router/middleware/jwt.go`, and `/tags` open. `main.go` serves on `127.0.0.1:8585`, and `Makefile` runs `go test -v -race ./...`.

The limit goes where abuse lands. Sign-up and login are the routes a credential stuffer hits, so the agent wraps the `guestUsers` group with `middleware.RateLimiterWithConfig` using `NewRateLimiterMemoryStoreWithConfig` and a `Rate`, `Burst` and `ExpiresIn` chosen for an unauthenticated endpoint: a few requests per second with a short burst, entries expiring after minutes. A second, looser limiter goes on the whole `/api` group so a single client cannot saturate reads either. The identifier is the default, `c.RealIP()`, and because that reads `X-Forwarded-For`, the agent sets `e.IPExtractor` in `router.go` to the extractor that matches how the API is deployed, direct or behind a proxy, and explains the choice in the pull request.

A denied request should look like every other error from this API. `utils/errors.go` wraps errors as `{"errors": {"body": ...}}`, so the agent sets `DenyHandler` to answer 429 with `utils.NewError` around the middleware's rate-limit error, and `ErrorHandler` to answer 403 the same way when the identifier cannot be read, instead of Echo's default `HTTPError` body. The limits live in two named variables at the top of `routes.go`, with a comment saying the memory store is per process.

Tests follow the suite's own style in `handler/handler_test.go`: a new `ratelimit_test.go` posts to `/api/users/login` past the burst in a loop and asserts the first responses are 200 or 422 as before and the overflow is 429 with the `errors.body` field, then shows a different `X-Real-IP` is not affected. The agent runs `make test`, `go vet ./...` and `go build ./...`, and regenerates nothing in `docs/` because the Swagger annotations did not change.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add rate limiting to this Echo v4 API. Read go.mod, main.go, router/router.go, router/middleware/jwt.go, handler/routes.go, handler/handler_test.go, utils/errors.go and Makefile first. If the echo/v4 version in go.mod predates the rate limiter middleware, upgrade it within v4 with go get and go mod tidy and run the existing tests before changing anything else. Apply middleware.RateLimiterWithConfig with an in-memory store, Rate, Burst and ExpiresIn, to the unauthenticated /users group with a strict limit and to the /api group with a looser one, keep the default RealIP identifier, set e.IPExtractor in router.go to match a direct deployment and explain the proxy alternative in the pull request. Make DenyHandler answer 429 and ErrorHandler answer 403 using utils.NewError so the body matches the API's error shape. Write handler/ratelimit_test.go in the style of handler_test.go that exceeds the login burst and asserts the 429 body, and that a different client IP is unaffected. Run make test, go vet ./... and go build ./..., and open a pull request that lists the limits, the version bump and the test results.",
  "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 `go.mod` and `go.sum` for the Echo bump and the `golang.org/x/time` dependency the limiter uses, `router/router.go` for the IP extractor, `handler/routes.go` for the two limiters and their handlers, and adds `handler/ratelimit_test.go`. The description lists each limit with its rate, burst and expiry, states the Echo version before and after, and shows the 429 body as the API now returns it.

The run's record keeps the `go get` and `go mod tidy` output, the suite's result before and after the bump, and the final `make test`, `go vet` and `go build` output, so a reviewer can see that the 25 existing tests passed on the new version before the limiter was added.

Before merging, a reviewer checks the numbers against real traffic, decides whether `IPExtractor` should trust a proxy header in production, and whether the memory store is enough for their deployment or a shared store belongs in a follow-up.

## Run it on every Linear issue labelled rate-limit

When a security review files an issue per service, an automation on the Project with a `linear` trigger on issues labelled `rate-limit` and this prompt starts one run per issue. The trigger puts the issue after the prompt, so the agent reads the routes the issue names and limits those; the pull request links back to it.

From your own server, for a list of Echo services, send one `POST /o/{org}/sessions` per repository with that repository in `resources` and a `request_id` that is a UUID v5 of its full name, so a retried call returns the run already started rather than a second pull request.

## Why run it on Rush?

The trap in this job is the version: the middleware is a one-liner on a current Echo and does not exist on the one in `go.mod`, and bumping a framework under a 2019-era ORM and JWT library is the part that needs a test suite run, not a guess. The agent does the bump first, in a sandbox with the module cache empty, and runs the 25 tests before and after, so the pull request separates what the upgrade changed from what the limiter added.

The sandbox keeps every command's output, including the loop that drives the login route past its burst, so the pull request shows the 429 and its body as produced by the branch rather than as written in a description.

## Frequently asked questions

### Why does it upgrade Echo first?

Because `middleware.RateLimiter` was added in Echo v4.2.0 and the module pins 4.1.16. The agent moves to a current v4 release with `go get` and `go mod tidy`, runs the existing tests on the new version before touching the routes, and reports both results so the two changes can be judged apart.

### Will the limit count every client as one IP behind a load balancer?

It would if the extractor read the socket address. The default identifier is `c.RealIP()`, which honours `X-Forwarded-For` and `X-Real-IP`, and the agent sets `e.IPExtractor` explicitly so the choice is visible: direct connection for a bare deployment, the forwarded-header extractor behind a proxy you trust.

### Does the limit survive a restart or scale across replicas?

No. The memory store is per process, which is what the pull request says in a comment next to the limits. For several replicas, implement the middleware's store interface over Redis in a follow-up; the config field is already there.

### Why 429 with the API's error shape?

Clients of this API parse `{"errors": {"body": ...}}` from `utils/errors.go` for every failure. A `DenyHandler` that returns the same shape means the front end shows the limit like any other error instead of crashing on an unexpected body.

## More Echo jobs

- [Add Request ID Logging to an Echo App](https://getrush.ai/run/add-request-id-logging/echo/)
- [Add Request Timeouts to an Echo App](https://getrush.ai/run/add-request-timeouts/echo/)
- [Add Security Headers to an Echo API](https://getrush.ai/run/add-security-headers/echo/)

## The same job on other stacks

- [Add Rate Limiting to an Express API from a Linear Issue](https://getrush.ai/run/add-rate-limiting/express/)
- [Add Rate Limiting to a FastAPI API](https://getrush.ai/run/add-rate-limiting/fastapi/)
- [Add Rate Limiting to a Fiber Login Endpoint](https://getrush.ai/run/add-rate-limiting/fiber/)

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