# Add Rate Limiting to a Go chi API

Yes. An agent adds rate limiting to a Go chi API with httprate: strict per-IP limits on login routes, per-account limits elsewhere, JSON 429s and tests, in a PR.

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

## What the agent does

The agent starts with which routes can be abused and how. In an API laid out like dhax/go-base, `api/api.go` mounts `/auth` in front of the JWT middleware and `/admin` and `/api` behind it. Inside `auth/pwdless/api.go`, `POST /auth/login` takes an email and, for any active account, sends a login-token email from a goroutine, and `POST /auth/token` exchanges that token for a JWT pair. Nothing limits either. Anyone who knows a user's address can make the API mail them without end, and `.env.example` sets the token to 8 characters with an 11-minute expiry, so the only bound on guessing one is how fast a client can post. The router's middleware is `Recoverer`, `RequestID`, a 15-second `Timeout`, the structured logger and a JSON content type; `go.mod` has chi v5 with `cors`, `jwtauth`, `render` and `docgen`, and no limiter.

It adds `github.com/go-chi/httprate`, which is built for chi's middleware chain, and applies three limits where each belongs. The `/auth` router gets a strict per-IP limit on `login` and `token`. The authenticated group gets a looser limit keyed by account, with a key function that reads the id from `jwt.ClaimsFromCtx`, placed after `jwt.Authenticator` so the claims exist; an office behind one address then does not share a single budget. A wide per-IP limit on the whole router bounds everything else, including the static files `SPAHandler` serves. Each limit and window is read through Viper with a default set in `cmd/serve.go` beside the existing ones, and listed in `.env.example`.

Three details in this codebase decide whether the limiter is correct. First, the client address: `r.Use(middleware.RealIP)` is commented out in `api/api.go`, so `r.RemoteAddr` is the proxy's address when the API runs behind one, and every user would share a bucket. Trusting forwarded headers from anyone is the opposite mistake, so the agent adds a `trust_proxy` setting, off by default, that enables `RealIP`, and says in the pull request which deployments should turn it on. Second, the response: handlers here answer errors as an `ErrResponse` rendered through `render.Render`, so the agent gives the limiter a handler that renders a 429 in that same JSON shape, with the `Retry-After` header the middleware computes. Third, the email flood is per address and not per IP, so `login` also gets a small per-email limit after the request body has been bound and validated, reusing the lowered and trimmed address the handler already produces.

Tests follow the existing file. `auth/pwdless/api_test.go` posts to `/login` several times from one address in its table tests, so the agent sets generous limits in `TestMain` for those and adds a separate server with a limit of two for the new cases: the third request answers 429 with the JSON body and a `Retry-After` header, a different email from the same address is still limited by IP, the same email from different forwarded addresses is limited by email, and the store is not called at all once the limit is hit, which the mock's `Invoked` flag shows. A test in `api` covers the per-account key with two signed tokens. The agent runs `go vet ./...` and `go test -race ./...`, starts the server against a Postgres it installs in its sandbox, and loops `curl` against `/auth/login` to record the status codes turning from 200 to 429 and back after the window.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "A Linear issue labelled rate-limit says the login endpoint of this Go chi API can be used to flood a user with emails and to guess login tokens. Read go.mod, api/api.go, api/server.go, cmd/serve.go, .env.example, auth/pwdless/api.go, auth/pwdless/logintoken.go, auth/pwdless/errors.go, auth/pwdless/api_test.go, auth/jwt/authenticator.go and logging/logger.go first. Add github.com/go-chi/httprate. Put a strict per-IP limit on POST /auth/login and POST /auth/token, a per-account limit keyed by the id in the JWT claims on the authenticated group after the Authenticator, and a wide per-IP limit on the whole router. Add a per-email limit inside login after the body is bound. Read every limit and window through Viper with defaults in cmd/serve.go and entries in .env.example. Add a trust_proxy setting, off by default, that enables middleware.RealIP, and explain it in the pull request. Answer 429 with the same ErrResponse JSON shape the other errors use and a Retry-After header. Keep the existing table tests passing by setting generous limits in TestMain, and add tests on a separate test server for the third request being refused, the IP and email keys, the store not being called once limited, and the per-account key. Run go vet ./... and go test -race ./..., start the server against PostgreSQL in the sandbox, loop curl against /auth/login and paste the status codes. Open a pull request that links the issue and says the counters are in memory per process.",
  "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 `go.mod` and `go.sum`, `api/api.go`, `auth/pwdless/api.go`, `cmd/serve.go` and `.env.example`, extends `auth/pwdless/api_test.go` and adds a test in `api`. The description links the Linear issue and shows `go vet` and `go test -race` output and the `curl` loop from the sandbox: the sequence of status codes for `/auth/login`, the 429 body and its `Retry-After` value, and the first 200 after the window passed.

It states the limits it chose as a table of route group, key, count and window, each with the environment variable that overrides it, and it names what the limiter does not do. The counters live in the process's memory, so two replicas each allow the full count and a restart resets them; a shared store is the follow-up for a deployment with more than one instance. `routes.md`, which `cmd/gendoc.go` generates, is left alone and mentioned, since regenerating it needs a database connection and the file already lists middleware the router no longer uses.

A reviewer decides the numbers and the proxy setting, because both depend on the deployment. Behind a load balancer with `trust_proxy` off, every client shares one address and the per-IP limits would lock users out together; directly on the internet with it on, a client could forge the header and dodge them. The tests prove the mechanism in both modes, and the description says which mode suits which setup.

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

In the console, connect Linear under Settings → Connections and add an automation to the Project with a `linear` trigger on `linear.issue.labeled` and the label `rate-limit`. The prompt is the general form of this one: read the issue, find the routes it names, add limits with the keys that fit them, test, and open a pull request linking the issue. The trigger puts the issue after the prompt, so each labelled issue becomes one run with its own requirements. It fires only for a change made by a person in your Rush org, never for one made by an app integration.

From your own server the same run is one `POST /o/{org}/sessions` per issue, with the repository and the issue's `https://linear.app/<workspace>/issue/<ID>` URL in `resources`, which Rush reads into the prompt through your Linear connection. Send a `request_id` that is a UUID v5 of the issue id so a retried call starts nothing new.

## Why run it on Rush?

A rate limiter that has never refused a request is untested. In its own sandbox the agent starts the API against a real Postgres, sends requests until the limiter answers 429, waits out the window and sends one more, and repeats that with forwarded headers on and off. Those status codes, with the commands that produced them, are kept with the run and quoted in the pull request, so a reviewer sees the limiter working on the real router and not just in a unit test.

The sandbox also makes it safe to try what the issue is about. Flooding a login endpoint to see what happens is not something to do against staging from a laptop; here the mailer is the repository's own mock, which prints messages when no SMTP host is configured, and the database is thrown away with the sandbox. Each issue gets its own run, so the security backlog moves in parallel with feature work.

## Frequently asked questions

### Does it work when the API runs on several instances?

The limits hold per instance. The default counter is in memory, so three replicas allow three times the configured count, and the pull request says so. For a shared limit, ask for a Redis-backed counter in a follow-up; the keys, limits and tests stay the same and only the store changes.

### Will real users behind one office IP get locked out?

Authenticated routes are keyed by account id from the JWT, not by address, so colleagues do not share a budget there. Only `login` and `token`, which run before anyone is signed in, are limited per IP, and their windows are short. All of the numbers are environment variables.

### Why is trust_proxy off by default?

`middleware.RealIP` takes the client address from forwarded headers. If the API is reachable directly, any client can set those headers and pick a new address for every request, which defeats a per-IP limit. Turn the setting on only when a proxy you control sets the header.

## More chi jobs

- [Add Request ID Logging to a chi App](https://getrush.ai/run/add-request-id-logging/chi/)
- [Add Security Headers to a chi API](https://getrush.ai/run/add-security-headers/chi/)
- [Migrate a chi API from Logrus to log/slog](https://getrush.ai/run/migrate-logrus-to-slog/chi/)

## The same job on other stacks

- [Add Rate Limiting to a Cloudflare Worker](https://getrush.ai/run/add-rate-limiting/cloudflare-workers/)
- [Add Rate Limiting to a CodeIgniter 4 App](https://getrush.ai/run/add-rate-limiting/codeigniter/)
- [Add Rate Limiting to a Django REST Framework API](https://getrush.ai/run/add-rate-limiting/django-rest-framework/)

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