# Add Rate Limiting to a CodeIgniter 4 App

Yes. An agent writes a Throttler-based filter for your CodeIgniter 4 app, registers it in Config\Filters, answers 429 with Retry-After, tests it, and opens a PR.

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

## What the agent does

The agent reads the filter configuration before writing a filter, because CodeIgniter 4 already ships the pieces and the work is in wiring them correctly. In an app started from codeigniter4/appstarter, `composer.json` requires `php` ^8.2 and `codeigniter4/framework` ^4.7, with `phpunit/phpunit` ^10.5.16, `fakerphp/faker` and `mikey179/vfsstream` for development. `app/Config/Filters.php` declares aliases for `csrf`, `toolbar`, `honeypot`, `invalidchars`, `secureheaders`, `cors`, `forcehttps`, `pagecache` and `performance`; every entry in `$globals['before']` is commented out, and `$methods` and `$filters` are empty arrays. `app/Config/Routes.php` has one route, `/` to `Home::index`, `app/Filters/` holds only a `.gitkeep`, and `app/Config/Cache.php` sets `$handler = 'file'` with a `dummy` backup and a 60-second default TTL.

The framework's `Throttler` service is a token bucket on top of that cache, so the agent uses it rather than adding a package. It generates `app/Filters/Throttle.php` with `php spark make:filter Throttle`, then fills in `before()`: it builds a key from the client address with `$request->getIPAddress()`, calls `service('throttler')->check($key, 60, MINUTE)`, and when the check fails returns a response with status 429, a `Retry-After` header taken from the throttler's `getTokenTime()`, and a JSON body. Returning a response from a `before` filter stops the request there, so the controller never runs. The limit of sixty requests a minute is a starting value the pull request names as such.

Registration is two lines in `app/Config/Filters.php`: `'throttle' => Throttle::class` in `$aliases`, and the alias in `$globals['before']` so every request is counted, with the agent's reasoning for global rather than per-route left in the pull request (the `$filters` array would scope it to `api/*` once there are API routes). Because `Throttler` stores buckets through the cache service, the file handler writes under `writable/cache/`; the agent checks that directory is writable in the sandbox and notes that a multi-server deployment needs the `redis` or `memcached` handler in `Cache.php`, otherwise each server counts on its own.

The test goes next to the one that already exists. `tests/unit/HealthTest.php` extends `CIUnitTestCase`; the agent adds `tests/unit/ThrottleFilterTest.php` using the framework's `FilterTestTrait`, which resolves the `throttle` alias and calls its `before` method with a mock request, so no HTTP server is involved. The test swaps the cache service for the framework's `MockCache`, calls the filter sixty times and asserts it returns nothing, then asserts the sixty-first call returns a response with status 429 and a `Retry-After` header, and finally resets the mock cache and asserts the bucket refills. The agent runs `composer install` and `vendor/bin/phpunit` as `.github/workflows/phpunit.yml` does, which `phpunit.dist.xml` points at the framework's `system/Test/bootstrap.php`.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add rate limiting to this CodeIgniter 4 application using the framework's Throttler service, with no new Composer package. Read composer.json, app/Config/Filters.php, app/Config/Routes.php, app/Config/Cache.php, app/Config/Services.php, tests/unit/HealthTest.php, phpunit.dist.xml and .github/workflows/phpunit.yml first. Create app/Filters/Throttle.php with php spark make:filter, implement before() so it keys the bucket on the client IP address, allows 60 requests per minute, and on a failed check returns a 429 response with a Retry-After header from getTokenTime() and a short JSON body. Register the alias in Config\\Filters and apply it in $globals before, and explain in the pull request how to scope it to api/* with $filters instead. Write tests/unit/ThrottleFilterTest.php with FilterTestTrait and the framework's MockCache: 60 calls pass, the 61st returns 429 with Retry-After, and the bucket refills after the cache is reset. Run vendor/bin/phpunit and open a pull request that also says which cache handler a multi-server deployment needs.",
  "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 `app/Filters/Throttle.php` and `tests/unit/ThrottleFilterTest.php` and changes `app/Config/Filters.php`. The description shows the headers of a throttled response, explains why the bucket is keyed on the client address and what that means behind a proxy (`getIPAddress()` honours the proxies listed in `Config\App::$proxyIPs`, which are empty in the starter), and gives the one-line change to move the filter from `$globals` to an `api/*` pattern in `$filters`.

The run's record keeps the `composer install` and `phpunit` output, with the existing `HealthTest`, session and database example tests still passing next to the new one, so a reviewer sees the suite rather than a summary.

Before merging, a reviewer sets the real limit and window, decides whether the health or static routes should be excluded through the `except` form in `$globals`, and, if the app runs on more than one server, switches `Config\Cache::$handler` from `file` to a shared store so the count is shared.

## Run it on every PHP application repository

A team with several CodeIgniter applications starts one run per repository from its own server: one `POST /o/{org}/sessions` each, with that repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started rather than opening a second pull request. Each run installs its own Composer dependencies in its own sandbox.

Once the filter is in, an automation on the Project with a `github` trigger on `pull_request.opened` and the prompt "if this pull request changes app/Config/Filters.php, confirm the throttle alias still applies and comment with what changed" watches for the filter being removed or narrowed. The trigger places the pull request after the prompt; only work by an owner, member or collaborator fires it, never a fork's.

## Why run it on Rush?

The framework documentation shows a throttle filter in a dozen lines, and the dozen lines are not the hard part: whether the cache handler the app actually uses persists buckets, whether `getIPAddress()` sees the client or the load balancer, and whether the filter test can run without a web server are what a reviewer wants to know. The agent answers them by running the app's own test suite and reading its config in its own sandbox.

Every command stays with the run, so the pull request can point at the passing `phpunit` output and the throttled response headers rather than describe them. Several applications can get the same filter at once, each run on its own machine with its own record.

## Frequently asked questions

### Does this need a package like a middleware library?

No. CodeIgniter 4 ships `Throttler` as a service and runs filters before controllers, so the whole feature is one filter class, an alias and a test. The only dependency is the cache service the app already configures in `app/Config/Cache.php`.

### Will the file cache work in production?

On one server, yes: buckets are written under `writable/cache/`. On several servers each one counts separately, so a client gets the limit times the server count. The pull request says to switch `$handler` to `redis` or `memcached` in that case; the filter code does not change.

### What does a throttled client receive?

A 429 status, a `Retry-After` header with the seconds until the next token, and a small JSON body. The controller does not run. The `before` filter returns the response itself, which is how CodeIgniter 4 short-circuits a request from a filter.

### Can it limit only the API routes?

Yes. Instead of `$globals['before']`, put `'throttle' => ['before' => ['api/*']]` in `$filters`. The starter has only the `/` route today, so the agent applies it globally and shows the scoped form in the pull request.

## More CodeIgniter jobs

- [Add Request ID Logging to a CodeIgniter 4 App](https://getrush.ai/run/add-request-id-logging/codeigniter/)
- [Add a REST API to a CodeIgniter 4 App](https://getrush.ai/run/add-rest-api/codeigniter/)
- [Add Security Headers to a CodeIgniter 4 App](https://getrush.ai/run/add-security-headers/codeigniter/)

## The same job on other stacks

- [Add Rate Limiting to a Django REST Framework API](https://getrush.ai/run/add-rate-limiting/django-rest-framework/)
- [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/)

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