# Add Rate Limiting to a Fiber Login Endpoint

Yes. An agent puts Fiber v3's limiter on your login route, counts only failed attempts per client, answers 429 in your JSON shape, tests it, and opens a PR.

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

## What the agent does

The agent reads how the login route is built before it limits anything. In a Fiber API like the `jwt` example in the Fiber project's cookbook repository on GitHub, `go.mod` names the module `api-fiber-gorm` on `go 1.26.0` with `github.com/gofiber/fiber/v3 v3.6.1`, `github.com/gofiber/contrib/v3/jwt v1.2.7`, `github.com/golang-jwt/jwt/v5 v5.3.1`, `godotenv` and `gorm` with the Postgres driver. `main.go` loads `.env` and panics without it, builds `fiber.New()`, mounts `cors.New()`, calls `database.ConnectDB()` and `router.SetupRoutes(app)`, then listens on `:3000`. `router/router.go` groups everything under `/api` behind `logger.New()`, registers `POST /api/auth/login` to `handler.Login`, and guards `POST` and `DELETE` on `/api/product` with `middleware.Protected()`. `handler/auth.go` binds a JSON body with `identity` and `password`, compares them to a hard-coded pair, signs an HS256 token with a 72-hour `exp` and answers `{"status": "success", "message": "Success login", "data": <token>}`; a wrong pair gets a bare `401` from `c.SendStatus`. Nothing counts attempts, so a password guess costs the attacker nothing but bandwidth.

The agent adds `github.com/gofiber/fiber/v3/middleware/limiter`, which ships with Fiber and needs no new module. The login route gets `limiter.New(limiter.Config{…})` with `SkipSuccessfulRequests: true`, so a correct login never counts against the client and only failed attempts fill the window; `Max` and `Expiration` come from the prompt and are read through the existing `config.Config` helper as `LOGIN_RATE_MAX` and `LOGIN_RATE_WINDOW` with those defaults, documented in `.env.sample`. The `KeyGenerator` combines `c.IP()` with the `identity` field of the body, so one office behind a NAT is not locked out by one person's typos, while a guess spread across many usernames from one address still hits the per-address part of the key. `LimiterMiddleware` is `limiter.SlidingWindow{}`, because a fixed window lets a client send twice the limit around the boundary.

`LimitReached` returns the same envelope the handlers use, `{"status": "error", "message": "Too many login attempts", "data": null}`, with status 429, so a client that already parses the login response needs no new case; the middleware's own `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` headers stay on, and a refused request carries `Retry-After` in seconds. The product routes are left alone: the prompt asks for the login endpoint, and the pull request names `app.Use(limiter.New())` on the `/api` group as the one-line follow-up if the reader wants a general limit. Because the default store is in memory, the description says plainly that each process keeps its own counts, and shows the `Storage` field that takes a shared store when the service runs more than one replica.

Tests go in `router/router_test.go` with `app.Test`: the login handler reads no database, so a test builds `fiber.New()`, calls `router.SetupRoutes(app)` and posts wrong credentials until the limit, asserting the 429, the envelope and `Retry-After`, then posts the correct pair from another address and sees it pass. The agent runs `go build ./...`, `go vet ./...` and `go test ./...` inside `jwt/` and the repository's `golangci-lint` at the `v2.14.0` the `Makefile` and `lint.yml` pin, and keeps the output. It also notes that `README.md` in that example still documents `/login` and `/restricted`, which `router.go` does not register, and corrects the table in the same pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add rate limiting to the login endpoint of this Fiber v3 API. Read go.mod, main.go, router/router.go, handler/auth.go, middleware/auth.go, config/config.go, .env.sample and the repository's Makefile and CI workflows first. Use github.com/gofiber/fiber/v3/middleware/limiter on POST /api/auth/login only, with a sliding window, SkipSuccessfulRequests so only failed logins count, a key made of the client IP and the identity field, and Max and Expiration read from LOGIN_RATE_MAX and LOGIN_RATE_WINDOW with defaults of 10 attempts per 15 minutes; document both in .env.sample. Make LimitReached answer 429 in the same status/message/data JSON envelope the handlers use and keep the X-RateLimit and Retry-After headers. Leave the product routes unchanged and say in the PR how to add a global limit and a shared Storage. Add tests with app.Test for the limit, the envelope, Retry-After and a successful login that does not count. Run go build, go vet, go test and golangci-lint at the version the Makefile pins, include the output, fix the README endpoint table if it disagrees with the router, 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

What comes back is a pull request that changes `router/router.go` and `.env.sample`, adds `router/router_test.go` and a small `middleware/ratelimit.go` holding the limiter config and the 429 handler, and corrects the endpoint table in the example's `README.md`. `go.mod` is unchanged because the limiter is part of the Fiber module already required.

The description explains the key choice, the sliding window, why successful logins are skipped, and quotes the `go test` and `golangci-lint` output. It also states the in-memory default and names the `Storage` field for a shared store. The commands and their full output are in the transcript at `GET /o/{org}/sessions/{id}/messages`.

Before merging, a reviewer sets the two environment variables for each deployment and decides whether the service sits behind a proxy: if it does, `c.IP()` is the proxy's address until `fiber.Config` is told to trust it with `TrustProxy`, `TrustProxyConfig` and `ProxyHeader`, which the pull request calls out but does not turn on. A follow-up message to the same session can add that configuration or wire a Redis-backed storage.

## Run it on every Fiber service with a login route and no attempt limit

A team with several Fiber services starts one run per repository with one `POST /o/{org}/sessions` each, this prompt as `input` and the repository in `resources`. Each run reads its own router and handler, so a service whose login lives at a different path or reads `username` instead of `identity` gets the key built from the field it actually binds.

Send a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run it already started. The key's `webhook_url` reports when each run the key starts finishes, with the run's final answer in `result` and `session_url` for the pull request link.

## Why run it on Rush?

Rate limiting a login route is mostly about the details: which key, which window, whether a success resets anything, and what the 429 body looks like to the client that already exists. The agent reads the handler's envelope and the router's groups and writes the middleware to fit them, then proves the limit with `app.Test` in a sandbox of its own, with the output kept.

The pull request carries the config, the tests and the lint output, so review is a diff rather than a session of `curl` in a loop. Several services can be done at once, each in its own sandbox with its own pull request.

## Frequently asked questions

### Does this need Redis?

No. The limiter's default store is in memory for the current process. That is right for a single instance; with several replicas each one counts separately, so the pull request shows the `Storage` field, which accepts any `fiber.Storage` implementation, and the agent can wire a shared store in a follow-up.

### Will one office behind a NAT lock everyone out?

The key is the client address plus the identity being tried, so one person's failed attempts limit only that address and that username. An attacker trying many usernames from one address still fills the address part of each key per username; say in the prompt if you want a second, address-only limit on top.

### Why count only failed attempts?

`SkipSuccessfulRequests: true` tells the limiter not to count responses under 400, so a correct login never gets closer to the limit and a user who signs in often is not punished. The window fills only with guesses.

### Does it work behind a load balancer?

Only once Fiber is told which proxy to trust; otherwise `c.IP()` is the balancer's address and every client shares one bucket. The pull request names `TrustProxy`, `TrustProxyConfig` and `ProxyHeader` in `fiber.Config` as the settings to turn on, and leaves them off because the repository does not show a proxy.

### What about the product routes?

They are unchanged, because the prompt asks for the login route. A general limit is `app.Use(limiter.New())` on the `/api` group with its own `Max` and window, and the description shows that line so a reviewer can add it knowingly.

## More Fiber jobs

- [Add Request ID Logging to a Fiber App](https://getrush.ai/run/add-request-id-logging/fiber/)
- [Add Request Timeouts to a Fiber App](https://getrush.ai/run/add-request-timeouts/fiber/)
- [Add Response Caching to a Fiber App](https://getrush.ai/run/add-response-caching/fiber/)

## The same job on other stacks

- [Add Rate Limiting to Firebase Callable Functions](https://getrush.ai/run/add-rate-limiting/firebase-functions/)
- [Add Rate Limiting to a Flask API](https://getrush.ai/run/add-rate-limiting/flask/)
- [Add Rate Limiting to a Gin API](https://getrush.ai/run/add-rate-limiting/gin/)

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