# Add Rate Limiting to a NestJS API

Yes. An agent adds @nestjs/throttler to your NestJS API with tighter limits on login, registration and password reset, proves the 429 end to end, and opens a PR.

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

## What the agent does

The agent reads how requests enter the app before it picks where a limit belongs. In a NestJS API shaped like brocoders/nestjs-boilerplate, `package.json` pins `@nestjs/core`, `@nestjs/common` and `@nestjs/platform-express` at 11.1.18, `@nestjs/config` 4.0.3, `@nestjs/swagger` 11.2.6 and `typeorm` 0.3.28, with Jest 30.3.0, `supertest` 7.2.2 and TypeScript 5.9.3, and `.nvmrc` says Node 24.14.1. There is no `@nestjs/throttler` and no limiter of any kind. `src/main.ts` adds `helmet`, enables CORS from `app.corsOrigins`, sets the global prefix from `app.apiPrefix` with `/` excluded, turns on URI versioning and the global `ValidationPipe`, and serves Swagger at `/docs`. `src/app.module.ts` loads every config namespace through `ConfigModule.forRoot({ isGlobal: true })` and picks TypeORM or Mongoose from `databaseConfig().isDocumentDatabase`.

The routes that need protecting are in `src/auth/auth.controller.ts`, declared with `@Controller({ path: 'auth', version: '1' })`: `POST email/login`, `POST email/register`, `POST email/confirm`, `POST email/confirm/new` and `POST forgot/password`. The agent installs `@nestjs/throttler`, whose current release lists `@nestjs/core` 11 among its peers, and registers `ThrottlerModule.forRootAsync` in `app.module.ts` with a default limit read from configuration, then binds `ThrottlerGuard` as an `APP_GUARD` provider so the default applies to every route. On the login, register and forgot-password handlers it adds `@Throttle` with a smaller limit, and on `HomeController`, the unprefixed `GET /` that reports app info, it adds `@SkipThrottle`.

Configuration follows the repository's pattern rather than a hard-coded number. `src/config/app.config.ts` validates `process.env` with a class-validator class and returns an `AppConfig`; the agent adds optional `THROTTLE_TTL` and `THROTTLE_LIMIT` fields with `@IsInt` and `@IsOptional`, extends `src/config/app-config.type.ts`, and adds both keys to `env-example-relational` and `env-example-document`, which the Docker test setups load with `--env-file`. The Swagger document gets a `429` response on the throttled routes through `@ApiTooManyRequestsResponse`, so `/docs` tells API consumers about the limit.

The proof is an e2e test in the shape of `test/user/auth.e2e-spec.ts`, which drives the running app at `APP_URL` with `supertest`. A new `test/user/throttle.e2e-spec.ts` posts wrong credentials to `/api/v1/auth/email/login` one more time than `THROTTLE_LIMIT` allows and asserts `429` with a `Retry-After` header on the last response, then confirms that `GET /` still answers `200`. It runs the way `.github/workflows/docker-e2e.yml` runs it: `docker compose -f docker-compose.relational.ci.yaml` builds the `api` container, and `startup.relational.ci.sh` waits for Postgres, migrates, seeds, starts the app, runs `npm run lint` and then `npm run test:e2e -- --runInBand`. The agent runs the same compose file in its sandbox, and `npm run lint` and `npm run build` on the host, before it pushes.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add rate limiting to this NestJS API and open a pull request. Read package.json, .nvmrc, src/main.ts, src/app.module.ts, src/auth/auth.controller.ts, src/home/home.controller.ts, src/config/app.config.ts, src/config/app-config.type.ts, env-example-relational, env-example-document, test/user/auth.e2e-spec.ts, test/utils/constants.ts, startup.relational.ci.sh, docker-compose.relational.ci.yaml and .github/workflows/docker-e2e.yml first. Install @nestjs/throttler at a release whose peer range includes the installed @nestjs/core. Register ThrottlerModule.forRootAsync in app.module.ts reading THROTTLE_TTL and THROTTLE_LIMIT from the app config namespace, add those two optional fields to the validator in app.config.ts and to app-config.type.ts, and add them to both env-example files. Bind ThrottlerGuard as APP_GUARD. Put a tighter @Throttle on email/login, email/register and forgot/password in auth.controller.ts, add @SkipThrottle to HomeController, and add @ApiTooManyRequestsResponse to the throttled handlers. Add test/user/throttle.e2e-spec.ts in the style of auth.e2e-spec.ts: post wrong credentials to /api/v1/auth/email/login past the configured limit and assert a 429 with a Retry-After header, then assert GET / still answers 200. Run npm run lint and npm run build, run the relational Docker e2e setup the CI workflow uses, paste the output in the pull request description, and mention the two new variables in docs/installing-and-running.md. Do not change any other route, entity or migration.",
  "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 `@nestjs/throttler` to `package.json` and `package-lock.json`, registers the module and the guard in `src/app.module.ts`, decorates three handlers in `src/auth/auth.controller.ts` and one in `src/home/home.controller.ts`, extends the app config and both env example files, and adds `test/user/throttle.e2e-spec.ts`. The description shows the lint and build output and the e2e output from the compose run, including the new spec's `429`.

The repository's `NestJS API CI` workflow runs the relational and document compose suites on the pull request with `--exit-code-from api`, so the new spec runs in the same container the maintainers use and a failure uploads `prod.log` as an artifact. The agent pushes one commit for the module, guard and config, one for the controller decorators, and one for the test and documentation.

A reviewer checks that the default limit is high enough for the frontend's normal traffic at `FRONTEND_DOMAIN`, that the login limit counts per client rather than globally, that the Swagger document shows the `429`, and that nothing in the `users` or `files` modules changed. Then they set `THROTTLE_TTL` and `THROTTLE_LIMIT` in their deployment's environment.

## Run it on every new public endpoint

Teams that add endpoints often start one run per repository with `POST /o/{org}/sessions`, this prompt and the repository in `resources`, so every NestJS service gets the same guard with limits read from its own config. The agent reads each service's controllers to find the anonymous routes, so a service without email login gets its tighter limit on whatever route takes a password.

The key's `webhook_url` receives `run.completed` for each run with a `session_url`, so a small handler can collect the pull request links and open them for review together.

## Why run it on Rush?

The decorator is one line; what takes time is proving that the `429` arrives and that the home route and the frontend's normal traffic are untouched, which in this repository means building the Docker compose test setup, migrating, seeding and running the suite in band. In a Rush sandbox the agent does that with real commands and their output is kept in the transcript, so the pull request shows the throttled request and the unthrottled one side by side.

The result follows the repository's own conventions, a config namespace with class-validator, env example files, Swagger annotations, an e2e spec against the running app, and passes its lint and CI before a reviewer opens it. The same request works unchanged across every NestJS service the team owns.

## Frequently asked questions

### Why a global guard instead of decorating each controller?

Because the boilerplate adds new resources through generators, and a module that nobody remembers to decorate should still be covered. `ThrottlerGuard` as an `APP_GUARD` applies the default everywhere; `@Throttle` tightens it where a password is involved and `@SkipThrottle` lifts it from the unprefixed app-info route.

### Where does the limit come from?

From `THROTTLE_TTL` and `THROTTLE_LIMIT`, read in `src/config/app.config.ts` the way `APP_PORT` and `API_PREFIX` are, validated with class-validator and typed in `app-config.type.ts`. The env example files carry values for the Docker test setups, and a deployment sets its own.

### Does it work with the Mongoose setup too?

Yes. The throttler keeps its counters in memory and does not touch the database module, so both `docker-compose.relational.ci.yaml` and `docker-compose.document.ci.yaml` run the same spec. A shared store such as Redis is a follow-up for multi-instance deployments and is noted in the pull request, not added.

### Will it slow down the e2e suite?

The new spec sends a handful of requests more than the configured limit and the suite runs `--runInBand`, so the added time is the time of those requests. The limit in the env example files is low enough to reach in the test and high enough that the existing auth specs, which log in a few times per file, do not trip it.

## More NestJS jobs

- [Add Request ID Logging to a NestJS API](https://getrush.ai/run/add-request-id-logging/nestjs/)
- [Add an Audit Log to a NestJS API from a Linear Issue](https://getrush.ai/run/add-soft-delete-audit/nestjs/)
- [Dockerize a NestJS App](https://getrush.ai/run/dockerize-app/nestjs/)

## The same job on other stacks

- [Add Rate Limiting to a Node.js Login Route](https://getrush.ai/run/add-rate-limiting/nodejs/)
- [Add Rate Limiting to a Quarkus REST API](https://getrush.ai/run/add-rate-limiting/quarkus/)
- [Add Rate Limiting to a React Router App](https://getrush.ai/run/add-rate-limiting/react-router/)

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