All jobs

Add Rate Limiting to a Rocket API

Yes. An agent adds a per-client request guard on the login and registration routes of a Rocket API, answers 429 with Retry-After, tests it and opens a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads the server before it limits anything. In a Rocket API like TatriX/realworld-rust-rocket, Cargo.toml pins rocket = "0.5.0-rc.1" with only the json feature, rocket_cors and rocket_sync_db_pools with diesel_postgres_pool, diesel 1.4.8, jsonwebtoken and validator, and rust-toolchain says nightly. src/lib.rs mounts nineteen routes under /api with routes![...], attaches the Db fairing, the CORS fairing and AppState::manage(), and registers one catcher, not_found, that answers {"status": "error", "reason": "Resource was not found."}. src/config.rs builds the Figment from PORT and DATABASE_URL and reads SECRET_KEY in an AdHoc::on_ignite fairing; src/auth.rs is a FromRequest guard that decodes the Token header into Auth and fails with Status::Forbidden. The two routes that take a password, post_users and post_users_login in src/routes/users.rs, validate their JSON with FieldValidator and answer Errors, a responder that returns 422 with {"errors": {...}}. The tests under tests/ share one rocket::local::blocking::Client behind a OnceCell<Mutex<Client>> in tests/common.rs, and every test calls login() against /api/users/login, which registers the smoketest user on first use; .travis.yml shows they need Postgres seeded by init.sql and diesel migration run.

The limiter follows the shape the code already uses. The agent adds the governor crate and a RateLimit request guard in a new src/rate_limit.rs: a keyed RateLimiter over the client address, kept in managed state the way AppState is, with its quota read from two environment variables in config.rs, one for the number of attempts and one for the window, with defaults the pull request states. The guard keys on Request::client_ip(), which Rocket fills from the connection or the X-Real-IP header, and puts requests with no address in one shared bucket so a local client is still limited. When the quota is spent it returns Outcome::Failure((Status::TooManyRequests, ())), and a new #[catch(429)] catcher, registered beside not_found, answers the same JSON shape with a Retry-After header computed from the limiter's earliest-possible time. The guard is added as a parameter of post_users and post_users_login only: the credential endpoints are what password guessing and sign-up spam hit, and the token-guarded routes stay as they are.

The agent then makes the tests pass alongside the limit. Because every test file logs in through the shared client, a small quota would break unrelated tests, so the limit read from the environment is left high in tests/common.rs and a new tests/rate_limit.rs builds its own realworld::rocket() with a quota of a few attempts, posts /api/users/login past it and asserts the 429, the Retry-After header and that a request after the window succeeds. It installs Postgres in the sandbox, runs init.sql and the Diesel migrations as .travis.yml describes, and runs cargo test on the pinned nightly.

Last it adds the two variables to .env with their defaults and a short section to README.md, and writes a line in CHANGELOG.md under Unreleased, which the repository keeps in Keep a Changelog form.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add rate limiting to this Rocket API. Read Cargo.toml, rust-toolchain, src/lib.rs, src/config.rs, src/auth.rs, src/errors.rs, src/routes/users.rs, tests/common.rs and .travis.yml first. Add a request guard backed by the governor crate, keyed on the client address, with its quota read from environment variables in config.rs with sensible defaults, held in managed state like AppState. Apply it to the registration and login routes only. Answer 429 with the same JSON shape as the existing 404 catcher and a Retry-After header. Keep the existing tests passing: they share one client and log in on every test, so set a high limit for the suite and write a separate test that builds its own rocket with a small quota and asserts the 429, the header and recovery after the window. Install Postgres, seed it with init.sql and run the Diesel migrations as .travis.yml does, then run cargo test on the pinned nightly. Document the variables in .env and README.md, add a CHANGELOG line, and open a pull request.",
  "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

A pull request with src/rate_limit.rs, the guard on the two routes in src/routes/users.rs, the catcher and its registration in src/lib.rs, the two settings in src/config.rs, the new test file, the .env, README and changelog lines, and the governor entry in Cargo.toml and Cargo.lock. Its description quotes the cargo test output from the run and shows one 429 response body with its Retry-After header.

A reviewer checks that the quota defaults fit the frontend's retry behaviour, that the key is the right address when the API runs behind a proxy, and that no token-guarded route picked up the guard by accident. The limiter keeps its counts in process memory, so the pull request also says what changes if the API runs on more than one instance.

Run it on every Linear issue labelled rate-limit

In the console, add an automation on the Project with a linear trigger on linear.issue.labeled and the label rate-limit, with the prompt above. When a person on the team labels an issue that names a route or a quota, the run starts with the issue as its context, makes the change in the Project's repository and opens a pull request on its own branch linked to the issue. A label applied by an app integration never fires it.

From your own tooling, send this body to POST /o/{org}/sessions with the issue text appended to the prompt and a request_id that is a UUID v5 of the issue id, so a retried webhook from your side returns the run already started.

The use case this job follows, with its automation and trigger: Turn a Linear label into a PR.

Why run it on Rush?

A rate limit is only real once it has refused a request, and proving that here means a nightly toolchain, a seeded Postgres, the Diesel migrations and a test that spends the quota. The agent sets all of that up in its own sandbox, runs the whole suite, and keeps every command and the 429 it provoked in the run's record, so the pull request carries evidence rather than a description.

The same run fits any Rocket service with a sign-in route: a 0.5 release with rocket_db_pools, a service that keys on an API token instead of an address, or one that wants the limit on a password-reset route too. Each gets a guard shaped like its own request guards and a test that fits its own suite.

Frequently asked questions

Why only the registration and login routes?

They take a password and no token, so they are what credential stuffing and sign-up bots hit. Every other route already requires a valid Token header through the Auth guard. Adding the limit elsewhere is one more guard parameter per route, and the pull request lists where it would go.

What happens behind a load balancer?

The guard keys on client_ip(), which uses X-Real-IP when a proxy sets it. If every request arrives from the proxy's address with no such header, all clients share one bucket; the pull request names the header to forward. The counts live in memory, so several API instances each keep their own.

Will the existing tests still pass?

Yes. Every test file logs in through the shared client, so the suite runs with a high quota from the environment and only the new tests/rate_limit.rs builds a rocket with a small one. The run's record shows the full cargo test output on the pinned nightly.

Does it change the error format?

The 429 uses the same {"status": "error", "reason": "..."} shape as the existing 404 catcher, plus a Retry-After header in seconds. Validation errors keep their 422 body with errors.

More Rocket jobs

The same job on other stacks

Keep reading