# Add Rate Limiting to a Django REST Framework API

Yes. An agent turns on DRF's own throttling, scopes the writes that run Pygments, sets NUM_PROXIES for your proxy, adds the first tests and opens a PR.

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

## What the agent does

The agent reads the settings before it picks a throttle, because Django REST Framework already ships the rate limiting and the work is choosing the right classes for this API. In an API laid out like encode/rest-framework-tutorial, `tutorial/settings.py` has a `REST_FRAMEWORK` dict with `PAGE_SIZE` 10, `PageNumberPagination` and drf-spectacular's `AutoSchema`, and nothing about throttling; there is no `CACHES` setting either, so the throttles would count in Django's default `LocMemCache`. `snippets/views.py` registers two viewsets through a `DefaultRouter` in `snippets/urls.py`: `SnippetViewSet`, a `ModelViewSet` with `IsAuthenticatedOrReadOnly` and the repository's own `IsOwnerOrReadOnly`, plus a `highlight` action that returns the stored HTML, and a read-only `UserViewSet`. `snippets/models.py` is where the cost is: `Snippet.save` runs Pygments over the code on every create and update, so a write is many times a read. `pyproject.toml` pins Python 3.13 with Django 6.1.3 and djangorestframework 3.18.3 under `uv.lock`, the `Procfile` runs `gunicorn tutorial.wsgi`, `app.json` deploys it to Heroku behind that platform's router, and `.github/workflows/ci.yml` runs `uv sync --locked` and `manage.py check` and no tests, because `snippets/` has no `tests.py`.

From that the agent writes three settings and one override. `DEFAULT_THROTTLE_CLASSES` gets `rest_framework.throttling.AnonRateThrottle` and `rest_framework.throttling.UserRateThrottle`, so an anonymous caller is counted by IP address and a signed-in one by user id, and `DEFAULT_THROTTLE_RATES` gets the `anon` and `user` rates the prompt names, in DRF's `number/period` form. For the writes, `SnippetViewSet` gets a `get_throttles` override that returns a `ScopedRateThrottle` with a `snippet-write` scope on `POST`, `PUT`, `PATCH` and `DELETE`, with its own entry in `DEFAULT_THROTTLE_RATES`, so a client can read freely and still only create or re-highlight a few snippets a minute; `UserViewSet` and the `highlight` action keep the defaults. `NUM_PROXIES` is set to 1, because the Heroku router in `app.json` sets `X-Forwarded-For` and, with the setting absent, DRF trusts the first address in that header, which means any client can reset its own bucket by sending the header. The agent keeps `LocMemCache` and says in the pull request what it implies: each gunicorn worker counts on its own, so a deploy that raises the worker count multiplies the effective limit by that number until a shared cache backend is configured.

Then it writes the tests the repository never had, in `snippets/tests.py` on `APITestCase`, and the detail that makes them work is one it would otherwise learn the hard way: `APIView.throttle_classes` is read from `api_settings` when the view module is imported, so `override_settings` applied after import changes nothing. The tests therefore run with the project's real settings, clear the cache in `setUp`, send one request more than the anonymous rate allows and assert the last answer is `429` with a `Retry-After` header and the body `{"detail": "Request was throttled. Expected available in N seconds."}`, then show that `/users/` is refused too, since both viewsets share the `anon` bucket, and that a `POST` from a signed-in user is counted under `snippet-write` while that user's reads still answer `200`. One more test sends a forged `X-Forwarded-For` and asserts it does not get a fresh bucket, which is what `NUM_PROXIES` buys.

The agent runs `uv run manage.py check`, `uv run manage.py test` and `uv run manage.py spectacular --file /tmp/schema.yml` in its sandbox, to show the OpenAPI schema at `/schema/` is unchanged (throttling is not part of it), and adds the test command to `ci.yml` after the existing check step, because a suite nobody runs is not a suite. It does not add a package: `django-ratelimit` and a Redis cache are each one line in the pull request's description as follow-ups, not in the diff.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add rate limiting to this Django REST Framework API. Read pyproject.toml, tutorial/settings.py, tutorial/urls.py, snippets/urls.py, snippets/views.py, snippets/permissions.py, snippets/serializers.py, snippets/models.py, Procfile, app.json and .github/workflows/ci.yml first. Use DRF's own throttling, no new dependency: set DEFAULT_THROTTLE_CLASSES to AnonRateThrottle and UserRateThrottle with DEFAULT_THROTTLE_RATES of 100/hour for anon and 1000/hour for user; give SnippetViewSet a get_throttles override that applies a ScopedRateThrottle with scope snippet-write at 20/hour to POST, PUT, PATCH and DELETE, since Snippet.save runs Pygments; set NUM_PROXIES to 1 for the Heroku router. Keep LocMemCache and explain in the pull request what changes with several gunicorn workers. Write snippets/tests.py on APITestCase, with the real settings and cache.clear() in setUp, covering the 429 with Retry-After after the anon limit, the shared anon bucket across /snippets/ and /users/, the write scope for a signed-in user, and a forged X-Forwarded-For not resetting the bucket. Add uv run manage.py test to ci.yml. Run manage.py check, the tests and a spectacular schema export in the sandbox and open a pull request quoting the output.",
  "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 `tutorial/settings.py` (the three throttle keys and `NUM_PROXIES` inside `REST_FRAMEWORK`), `snippets/views.py` (the `get_throttles` override on `SnippetViewSet`), adds `snippets/tests.py`, and adds one step to `.github/workflows/ci.yml`. The description lists each rate and which requests it counts, quotes the `manage.py check` and `manage.py test` output from the sandbox, and shows that the exported schema did not change.

The description also carries the two operational notes a reviewer needs: that `LocMemCache` counts per gunicorn worker, with the one-line `CACHES` change for a shared backend written out but not applied, and that `NUM_PROXIES` is right for one router in front of the app and must be 0 when the app is reached directly.

Before merging, a reviewer checks the three rates against what the API's real clients send, decides whether `highlight` should join the write scope, and confirms the proxy count for the environment the app actually runs in. Then CI runs the new test step on the pull request itself.

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

Create an automation in the Project with a `linear` trigger on `linear.issue.labeled` with `rate-limit` in its `labels`, and this prompt. The trigger adds the issue after the prompt as untrusted event text, so an issue that says which endpoint is being hammered and by whom reaches the agent, which picks the rate and the scope from that rather than from the prompt's defaults.

Each labelled issue starts one run in its own sandbox and opens one pull request on its own branch. Changes made by an app integration never fire the trigger, so a bot that labels issues in bulk cannot start a run per issue; a person adding the label can, and the automation's `max_runs_per_hour` caps how many start in an hour.

## Why run it on Rush?

The throttle settings are four lines, and every one of them is easy to get wrong in a way that only shows in production: a header-trusting IP lookup that any client can spoof, a per-process cache that silently multiplies the limit under more workers, a write endpoint that costs a Pygments run but is counted like a read, and view classes that read their throttle list at import so the obvious test setup proves nothing. On Rush the agent reads the settings, the views and the deploy files first, writes the tests against the real settings, and runs them in its own sandbox on the project's pinned Python before anyone opens the diff.

The run keeps every command and its output, so the reviewer reads the `429` body and the `Retry-After` value from the test log without checking out the branch. Several APIs can get the same treatment at once, each in its own sandbox, each pull request shaped by that project's own views and deploy target.

## Frequently asked questions

### What does a throttled client receive?

A `429` with a `Retry-After` header holding the seconds until the bucket has room, and a JSON body of the form `{"detail": "Request was throttled. Expected available in 60 seconds."}`. `SimpleRateThrottle` implements `wait()`, which is where the header comes from; the test asserts both.

### Why is NUM_PROXIES needed?

When it is unset, DRF identifies an anonymous client by the first address in `X-Forwarded-For` if the header is present, and a client can send that header itself. With `NUM_PROXIES` at 1 the address is taken from the position the one trusted proxy writes, which is what the Heroku router in `app.json` is. An app served directly sets it to 0 and uses `REMOTE_ADDR`.

### Does the limit hold across gunicorn workers?

Not with `LocMemCache`, which is a dictionary inside each process. The `Procfile` runs gunicorn with its default single worker, so today the count is exact; the moment `--workers` goes up, each worker keeps its own count. The pull request shows the `CACHES` entry for a shared backend and leaves the choice to the reviewer, since it adds infrastructure.

### Why not throttle the highlight action too?

`highlight` returns `snippet.highlighted`, which is already stored; the Pygments work happens in `Snippet.save`, on create and update. So the expensive requests are the writes, and those get the `snippet-write` scope. Adding `highlight` to it is a one-line change in `get_throttles` if its traffic turns out to matter.

### Can the tests use override_settings for a smaller rate?

Not on their own. `APIView.throttle_classes` and the rate lookup are evaluated when `snippets/views.py` is imported, so a setting changed later in a test is not seen by the view classes. The tests use the real rates and loop one request past the limit, which with `100/hour` and the in-memory cache runs in well under a second.

## More Django REST Framework jobs

- [Add Role-Based Permissions to a Django REST Framework API](https://getrush.ai/run/add-role-based-permissions/django-rest-framework/)
- [Add Security Headers to a Django REST Framework API](https://getrush.ai/run/add-security-headers/django-rest-framework/)
- [Add Soft Delete to a Django REST Framework API](https://getrush.ai/run/add-soft-delete/django-rest-framework/)

## The same job on other stacks

- [Add Rate Limiting to a .NET Minimal API](https://getrush.ai/run/add-rate-limiting/dotnet/)
- [Add Rate Limiting to an Echo API](https://getrush.ai/run/add-rate-limiting/echo/)
- [Add Rate Limiting to an Express API from a Linear Issue](https://getrush.ai/run/add-rate-limiting/express/)

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