All jobs

Add Rate Limiting to a Slim 4 App

Yes. An agent adds a PSR-15 rate-limit middleware to your Slim 4 app with a configurable limit, 429 responses with Retry-After, a test, 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 how the skeleton is assembled, because Slim 4 middleware order and the container decide where a limiter fits. In an app built from slimphp/Slim-Skeleton, composer.json requires php ^7.4 || ^8.0, slim/slim ^4.12, slim/psr7 ^1.6, php-di/php-di ^6.4 and monolog/monolog ^2.9, with phpunit/phpunit ^9.6.17, phpstan/phpstan ^1.10 at level 4 on src/ and squizlabs/php_codesniffer on PSR-12 for development. app/middleware.php adds a single SessionMiddleware; app/routes.php has an OPTIONS catch-all for CORS preflight, GET / and a /users group with ListUsersAction and ViewUserAction; app/settings.php holds displayErrorDetails, the logger name, path and level; app/dependencies.php builds the Monolog logger; and public/index.php wires routing, body parsing and the HttpErrorHandler that renders every error as an ActionPayload with an ActionError type.

The agent chooses symfony/rate-limiter with symfony/cache for storage rather than writing a counter by hand, and pins both at ^5.4, because the CI matrix in .github/workflows/tests.yml runs PHP 7.4, 8.0, 8.1 and 8.2 and the 6.x line of those packages no longer installs on 7.4. A new rateLimiter block in app/settings.php holds policy sliding_window, limit 60 and interval 1 minute as starting values, and app/dependencies.php gains a definition for RateLimiterFactory built from those settings with a CacheStorage over a FilesystemAdapter pointed at var/cache/rate-limiter, a directory the skeleton already keeps with its own .gitignore.

src/Application/Middleware/RateLimitMiddleware.php implements PSR-15 like the existing SessionMiddleware. It skips OPTIONS requests so preflights never consume tokens, keys the limiter on REMOTE_ADDR from getServerParams(), calls consume(1), and on success passes the request on and adds X-RateLimit-Limit and X-RateLimit-Remaining to the response. When the limit is hit it returns a 429 directly, with Retry-After computed from the limit's retry time and a JSON body built from ActionPayload and a new ActionError::TOO_MANY_REQUESTS constant, so the shape matches every other error the app emits. It is registered in app/middleware.php after SessionMiddleware; Slim 4 runs the last-added middleware first, so adding it last puts it in front of the session code, and the agent writes that down in a comment because it is the opposite of what most people expect.

The test follows the existing pattern in tests/Application/Actions/User/ListUserActionTest.php: tests/Application/Middleware/RateLimitMiddlewareTest.php extends the project's TestCase, builds the app with getAppInstance(), replaces the factory in the container with one using InMemoryStorage and a limit of 3 so the test is fast, sends three requests to /users with a mocked UserRepository and asserts 200 with a decreasing X-RateLimit-Remaining, then asserts the fourth answers 429 with a Retry-After header and the TOO_MANY_REQUESTS type in the body, and that an OPTIONS request is never counted. The agent runs composer install, vendor/bin/phpcs, vendor/bin/phpstan and vendor/bin/phpunit, the three commands the workflow runs on PHP 8.1.

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 Slim 4 application. Read composer.json, app/middleware.php, app/routes.php, app/settings.php, app/dependencies.php, public/index.php, src/Application/Middleware/SessionMiddleware.php, src/Application/Actions/ActionError.php, src/Application/Handlers/HttpErrorHandler.php, tests/TestCase.php, tests/Application/Actions/User/ListUserActionTest.php, phpstan.neon.dist, phpcs.xml and .github/workflows/tests.yml first. Add symfony/rate-limiter and symfony/cache at versions that still install on PHP 7.4, the oldest version in the CI matrix. Put policy, limit and interval under a rateLimiter key in app/settings.php and define a RateLimiterFactory in app/dependencies.php with CacheStorage over a FilesystemAdapter in var/cache. Write src/Application/Middleware/RateLimitMiddleware.php as PSR-15: skip OPTIONS, key on REMOTE_ADDR, add X-RateLimit-Limit and X-RateLimit-Remaining on success, and return 429 with Retry-After and an ActionPayload body using a new ActionError TOO_MANY_REQUESTS type when the limit is exceeded. Register it in app/middleware.php and comment on Slim's last-added-runs-first order. Write a PHPUnit test using InMemoryStorage and a limit of 3 that covers success headers, the 429, and that OPTIONS is not counted. Run phpcs, phpstan and phpunit 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 adds RateLimitMiddleware.php and its test, changes composer.json and composer.lock, app/settings.php, app/dependencies.php, app/middleware.php and ActionError.php. The description shows the headers of a successful and a throttled response, explains the middleware order and why OPTIONS is exempt, and names the version constraint that keeps PHP 7.4 in the matrix green.

The run's record keeps the phpcs, phpstan and phpunit output, so a reviewer sees that the new class passes PSR-12 and level 4 analysis and that the five existing tests still pass beside the new ones.

Before merging, a reviewer sets the real limit and interval, decides whether to key on an authenticated user instead of the address once the app has one, and, if the app runs on more than one server, swaps the FilesystemAdapter for a shared cache adapter so the window is counted once.

Run it on every PHP service repository

A team with several Slim services starts one run per repository from its own server: a 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.

Afterwards, an automation on the Project with a github trigger on pull_request.opened and the prompt "if this pull request changes app/middleware.php, confirm RateLimitMiddleware is still added and still runs before SessionMiddleware, and comment if not" catches an accidental reorder. The trigger adds the pull request after the prompt; only work by an owner, member or collaborator fires it, never a fork's.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

The limiter itself is a small class; what makes the change safe is knowing it installs on every PHP version the project tests, that it runs before the middleware already there, and that the error body matches the rest of the API. The agent checks each of those by running the project's own phpcs, phpstan and phpunit in its own sandbox before the pull request exists.

Every command's output stays with the run, so the pull request can cite the passing analysis and the throttled response rather than describe them. Several services can get the same middleware at once, each on its own machine with its own record.

Frequently asked questions

Why symfony/rate-limiter rather than a Slim-specific package?

It is a framework-independent component with sliding window, fixed window and token bucket policies and pluggable storage, and its 5.4 line still supports PHP 7.4, which the skeleton's CI tests. The middleware is PSR-15, so nothing about it is Slim-specific beyond registration.

Why does the middleware go last in app/middleware.php?

Slim 4 executes middleware in reverse order of addition: the last one added wraps everything else and runs first. Adding RateLimitMiddleware after SessionMiddleware means a throttled request never starts a session. The agent leaves a comment at the call site because this order surprises people.

What if the app sits behind a proxy?

REMOTE_ADDR is then the proxy's address and every client shares one bucket. The pull request names the spot to read a forwarded header instead, and says not to trust that header unless the proxy is the only way in.

Does the file cache work with several servers?

Each server would count its own window. For a shared count, switch the storage to a Redis or Memcached adapter from symfony/cache; the middleware and the settings keys do not change.

More Slim jobs

The same job on other stacks

Keep reading