# Add Rate Limiting to an Actix Web API

Yes. An agent adds actix-governor to the login and invitation routes, following the repository's own rate-limit example, tests the 429 path and opens a PR.

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

## What the agent does

The agent reads the routes that need protecting and what the repository already knows about limits. In a service shaped like `auth/simple-auth-server` in actix/examples, the workspace `Cargo.toml` sets the 2024 edition and `actix-web` 4.11, `actix-session` 0.11 and `actix-identity` 0.9 as workspace dependencies, and the crate's own `Cargo.toml` adds Diesel 2 with Postgres and r2d2, `rust-argon2` and `sparklepost` for the invitation email. `src/main.rs` builds the app with `IdentityMiddleware`, a cookie `SessionMiddleware` named `auth-example` and the default `Logger`, then mounts `POST /api/invitation`, `POST /api/register/{invitation_id}` and `/api/auth` with `POST` for login, `DELETE` for logout and `GET` for the current user. `src/auth_handler.rs` verifies the Argon2 hash in `login`, and `src/invitation_handler.rs` sends an email through SparkPost for every call. Nothing limits either route, so a script can hammer logins or burn the email quota. The sibling `middleware/rate-limit` crate in the same workspace already uses `actix-governor` 0.10 with `GovernorConfigBuilder::default().seconds_per_request(10).burst_size(2)` and a hand-written `RateLimit` middleware, which is the pattern the agent follows.

It adds `actix-governor` to the crate's `Cargo.toml` at the same version the sibling uses and builds two `GovernorConfig` values in `main.rs`, one for login and one for invitations, keyed by peer IP with the default `PeerIpKeyExtractor` and with `use_headers()` so each answer carries `x-ratelimit-limit` and `x-ratelimit-remaining`. Since `/api/auth` serves three methods on one resource, the agent wraps only the `POST` route with `Route::wrap(Governor::new(&login_config))`, so logout and `GET /api/auth` stay unlimited, and wraps the invitation route the same way. The starting values are the sibling's ten seconds per request with a burst of two, as constants at the top of `main.rs` with a comment, since the pull request is the place to agree on the real numbers.

There is one unit test in the crate, `secret_key_default` in `src/utils.rs`, and the workspace CI builds every crate after installing `libpq-dev` and `diesel_cli`. The agent adds a `tests` module in `main.rs` using `actix_web::test::init_service` over a stub handler wrapped in the same login config: the first two requests from one peer return 200, the third returns 429 with the `x-ratelimit-remaining` header at zero, and after the window a request succeeds again. That tests the limit without a database. It runs `cargo test -p simple-auth-server`, `cargo clippy -p simple-auth-server --all-targets` and `cargo +nightly fmt --check` as the `justfile` does, and `taplo format --check` on the edited `Cargo.toml`.

With Postgres started in the sandbox and `diesel setup` run as the README says, the agent starts the server, posts three logins with `curl` and pastes the third response's status and headers in the pull request, so the 429 is shown from the real binary rather than only from the test.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add rate limiting to the login and invitation routes of this Actix Web service and open a pull request. Read the workspace Cargo.toml, auth/simple-auth-server/Cargo.toml, src/main.rs, src/auth_handler.rs, src/invitation_handler.rs, src/errors.rs, src/utils.rs, README.md, the middleware/rate-limit crate in this workspace, the justfile and .github/workflows/ci.yml first. Add actix-governor at the version middleware/rate-limit uses. In main.rs build two GovernorConfig values keyed by peer IP with use_headers enabled, one for POST /api/auth and one for POST /api/invitation, starting from the sibling example's seconds_per_request and burst_size as named constants, and wrap only those two routes with Route::wrap so GET and DELETE /api/auth are unaffected. Add a tests module in main.rs with actix_web::test::init_service over a stub handler under the login config asserting two requests pass, the third is 429 with x-ratelimit-remaining at zero, and a request after the window passes. Run cargo test -p simple-auth-server, cargo clippy -p simple-auth-server --all-targets, cargo +nightly fmt --check and taplo format --check. Start Postgres, run diesel setup and the server, send three logins with curl and paste the third response in the pull request with the test output. Do not change the handlers or the session settings.",
  "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 adds one dependency to `auth/simple-auth-server/Cargo.toml`, updates `Cargo.lock`, and changes `src/main.rs` for the two configs, the two `wrap` calls and the test module. The description shows the third `curl` login's 429 status with its `x-ratelimit-limit` and `x-ratelimit-remaining` headers, and the `cargo test` output with the new cases.

On a repository with the examples' `CI` workflow, the pull request builds and tests the workspace with `libpq-dev` installed, and the `clippy-fmt` workflow runs rustfmt and Clippy, so an unused import or a config that does not compile fails there.

A reviewer checks that logout and the current-user route are not wrapped, that the key extractor matches the deployment, since behind a reverse proxy every request shares one peer address, and that the constants are the numbers they want. Then they decide whether the registration route should get the same treatment.

## Run it on every public endpoint added

A team that wants every login, signup and email-sending route limited starts one `POST /o/{org}/sessions` per Actix service with this prompt and that repository in `resources`. Each run reads its own `main.rs` and picks the routes that verify a password or send mail, so a service with a `POST /api/password-reset` gets that wrapped too, and each opens its own pull request.

With a `webhook_url` on the key, `run.completed` arrives per run with its `session_url`, and a handler can collect the pull request links into one review.

## Why run it on Rush?

Rate limiting is a middleware change whose failure is silent: wrap the resource instead of the route and logout gets throttled, pick the peer address behind a proxy and every user shares one bucket. In a Rush sandbox the agent compiles the crate, runs the test that counts to 429, starts Postgres and the real server and sends real requests, and all of that stays in the run's record next to the pull request.

Building this crate needs `libpq` and a Postgres, which is why it tends to be skipped locally; the sandbox installs them as CI does. The turn parks when it finishes, so a follow-up that changes the constants or adds a `RealIp` key extractor wakes it where it stopped.

## Frequently asked questions

### Why actix-governor and not a hand-written middleware?

The workspace's own `middleware/rate-limit` example shows both, and the governor crate gives a tested token bucket with per-key state and standard headers. The hand-written one is fine for a demo but keeps no per-client state.

### What happens behind nginx or a load balancer?

The default `PeerIpKeyExtractor` sees the proxy's address, so every client shares one bucket. The pull request notes a custom `KeyExtractor` over `ConnectionInfo::realip_remote_addr`, which reads `Forwarded` and `X-Forwarded-For`, as the follow-up for that deployment.

### Does logout get limited?

No. Only the `POST` route on `/api/auth` is wrapped with `Route::wrap`; `DELETE` and `GET` on the same resource are untouched, and the reviewer can see that in the three lines of `main.rs` that change.

### Where do the numbers come from?

From the sibling example in the same repository: ten seconds per request with a burst of two. They are named constants so the pull request review is where the team sets the real values for login and for invitations.

## More Actix Web jobs

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

## The same job on other stacks

- [Add Rate Limiting to an AdonisJS API](https://getrush.ai/run/add-rate-limiting/adonisjs/)
- [Add Rate Limiting to an aiohttp App](https://getrush.ai/run/add-rate-limiting/aiohttp/)
- [Add Rate Limiting to an ASP.NET Core API](https://getrush.ai/run/add-rate-limiting/aspnet-core/)

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