Writing PHP Middleware for API Rate Limiting

An API can be perfectly designed and still become unreliable when one client sends too many requests. A burst from a mobile app, a badly behaved integration, or a retry loop can exhaust PHP workers, database connections, and upstream service quotas. Rate limiting creates a controlled boundary before that traffic becomes an outage.

For PHP applications, middleware is a useful place to enforce this boundary. It runs around the request handler, so authentication, route matching, logging, and response formatting can remain separate from the limiting algorithm. A well-designed component can be reused across a Laravel application, a Slim service, or a custom PSR-15 stack.

Australian deployments add practical complications. Customers may connect through mobile networks, carrier-grade NAT, or variable NBN links, while users in Perth can experience a very different latency profile from users in Sydney or Melbourne. A limit based solely on IP address can therefore punish a whole household, office, or shared hotspot.

The implementation also needs to communicate clearly with clients. A 429 Too Many Requests response, a useful Retry-After value, and predictable rate-limit headers allow callers to back off rather than hammering the endpoint through the next arvo.

Choose The Limiting Model

A fixed-window counter is the simplest approach. The middleware increments a key such as rate:user:4821:2025-03-08T10:15, then rejects requests after the configured threshold. It is easy to explain and inexpensive to run, but requests clustered around a window boundary can create a short burst that is twice the intended average.

A sliding window gives a more accurate view of recent traffic by tracking timestamps or smaller sub-windows. A token bucket is often a better compromise for APIs: tokens accumulate at a steady rate up to a maximum capacity, and each request consumes one. This permits small bursts while preserving a long-term request rate.

The right policy depends on the operation. A public search endpoint might allow 60 requests per minute, whereas password reset, invoice export, and expensive reporting routes need much tighter controls. Store the policy beside route metadata rather than scattering numeric values through middleware code.

Identify Clients Without Trusting The Wrong Header

The client key should usually be based on an authenticated subject, API key, tenant, or a combination of tenant and endpoint. This prevents one customer from consuming another customer’s quota. Before authentication, an IP address may be the only available identity, but it should be treated as a coarse fallback.

Never blindly trust X-Forwarded-For. Configure the trusted proxy addresses in the web server or framework, then extract the original address only through that trusted chain. A request that can supply its own forwarding header can otherwise evade the limiter by presenting a new identity on every call.

Australian carriers and corporate networks make IP-only controls particularly blunt. Several people in a Brisbane office may share one public address, and a family using a mobile hotspot near Newcastle may appear as one client. Combining IP with an API credential, where available, reduces accidental blocking while retaining a useful defence against anonymous abuse.

Build PSR-15 Middleware Around A Small Store

A PSR-15 middleware class should receive a request handler and return a response. Its responsibilities can stay narrow: derive the identity, select a policy, ask a rate-limit store whether the request is allowed, attach headers, and either call the next handler or return a 429 response.

Redis is a common store because its atomic operations and expiry support suit counters and token buckets. A Lua script can check the current token balance and update it as one operation, avoiding race conditions when several PHP-FPM workers process requests simultaneously. A database counter can work at low volume, but row locks and cleanup jobs often become an unnecessary bottleneck.

For a small development installation, an in-memory store may be enough to validate behaviour. Production workers must share state, however; a local PHP array would give every process its own limit and reset whenever that process ended. The same concern applies when scaling across containers or multiple availability zones.

Return Useful Responses And Headers

When a request is accepted, the middleware can add RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset headers. These names are widely recognisable, although the exact contract should be documented for consumers. The reset value should describe when capacity becomes available, not merely expose an internal Redis expiry that clients cannot interpret.

A rejected response should use status 429 and a JSON body with a stable error code. Retry-After may contain a number of seconds or an HTTP date; seconds are usually simpler for API clients. Avoid returning a long HTML error page from a JSON service, and make sure the response is generated before expensive application work begins.

A reverse proxy or API gateway can enforce a broad edge limit, while PHP middleware applies user- or route-specific rules. This layered model protects the application from floods and still lets the application understand business identity. It is especially useful when a service runs across several nodes, such as a home lab Kubernetes experiment documented in bare-metal cluster notes.

Keep Configuration Explicit And Observable

A policy should describe its window, capacity, refill rate, identity source, and any trusted proxy settings. Put those values in deployment configuration rather than hard-coding them. Separate anonymous, authenticated, partner, and administrator policies so an urgent operational task does not require editing application logic.

The limiter should emit structured events when a request is denied, including route, policy, tenant identifier, and a privacy-conscious client fingerprint. Metrics such as allowed requests, rejected requests, remaining capacity, Redis errors, and store latency reveal whether a policy is too strict or an infrastructure dependency is failing.

Do not log raw access tokens or complete personal data. Australian organisations may need to consider the Privacy Act, contractual data handling obligations, and where Redis or managed observability services store information. A service used across Sydney, Adelaide, and Perth may also benefit from regional monitoring so a local network issue is not mistaken for application abuse.

Useful operational signals include:

  • Rejection rate by route and customer
  • Redis command latency and connection failures
  • Percentage of requests using anonymous fallback identity
  • Retry-After values returned during busy periods
  • Requests accepted after a policy change
  • Differences between edge and application-level counts

Test Bursts Failures And Deployment Changes

Unit tests should cover an empty bucket, a partially consumed bucket, an exhausted bucket, expiry, malformed configuration, and clock movement. Test that the next handler is never called after a rejection and that response headers match the body’s retry information. Inject a clock into the limiter instead of relying directly on time(); deterministic time makes token calculations much easier to verify.

Integration tests should exercise concurrent requests against the real store. Two PHP workers must not both observe the same final token and accept requests beyond capacity. Test Redis failover as well. Depending on the risk profile, a store outage may fail closed for sensitive endpoints or fail open for low-risk reads, but that choice should be deliberate.

Before deploying in Australia, test traffic from different networks and regions. A Sydney office, a Perth user, and a mobile connection outside Hobart can produce different latency and retry patterns. Test through the actual load balancer, CDN, and trusted proxy chain rather than sending requests directly to PHP-FPM.

A practical verification checklist includes:

  • Confirming 429 responses under controlled bursts
  • Verifying authenticated and anonymous keys separately
  • Checking behaviour across multiple application instances
  • Testing proxy address extraction with forged headers
  • Measuring clock and expiry behaviour during daylight-saving changes
  • Confirming dashboards contain no secrets or unnecessary personal data

A safe rollout can begin in observation mode, where the middleware calculates decisions and records would-be rejections without blocking clients. Compare the results with normal traffic, adjust route policies, then enforce limits gradually. Document exceptions for trusted integrations and provide a contact path for customers whose legitimate batch jobs need a higher quota.

Middleware is most effective when it is treated as a small infrastructure component rather than a single conditional statement. Define identities carefully, use atomic shared state, return standards-friendly responses, and monitor the decisions in production. Add the limiter to a staging environment first, generate realistic bursts, and then release a measured policy that protects the API without making ordinary Australian users fight their own network.

Experience

Information Technology Consulting

Independent Practice

Provides IT consulting services focused on infrastructure planning, cloud migration strategy, and systems architecture. Engagements draw on years of hands-on sysadmin and development experience across Linux, Windows, and hybrid environments.

K9 Search & Rescue Volunteer

Ongoing

Active participant in K9 Search & Rescue operations, combining technical logistics skills with field support for canine search teams.

Karl Katzke's Blog

October 2006 – May 2014

Published a long-running personal technology blog covering cloud vs. in-house infrastructure, F# and Mono on OSX, hardware vendor critiques, RAID card performance analysis, and sysadmin storytelling. Notable posts include "When Sysadmins Ruled the Earth" (May 15, 2014) and "Getting Started with F# and Mono on OSX" (December 22, 2012).

Credentials

A small badge icon with a shield shape in muted blue tones on a light background

Systems Administration

Deep experience with Linux (RHEL, SLES, CentOS), high-availability clusters, and STONITH configurations.

A small badge icon with a gear shape in muted blue tones on a light background

Cloud Infrastructure

Practical knowledge of AWS EC2, reserved instances, and cost analysis for cloud vs. on-premises deployments.

A small badge icon with a code symbol in muted blue tones on a light background

Development

Proficient in F#, PHP (Symfony), and cross-platform tooling including Mono and MonoDevelop on OSX.

Studies

F# & Functional Programming

Self-directed, 2012

Explored strongly typed functional programming with F# on OSX using the Mono runtime. Published a detailed getting-started guide covering toolchain setup and cross-platform game development research.

High-Availability & Cluster Management

Professional Development, 2009

Configured and documented crm_mon email alerting for STONITH events on SLES11-HAE clusters, integrating with Nagios monitoring for production environments.

Hardware & Storage Performance

Ongoing

Conducted hands-on benchmarking of SATA/SAS RAID controllers including HighPoint RocketRaid 2740 and LSI/SuperMicro AOC-USASLP2-H8iR, comparing against software RAID configurations.

Skills

A small icon representing a server with clean geometric lines in slate blue

Linux Administration

RHEL, SLES, CentOS — package management, kernel tuning, HA clustering, and monitoring integration.

A small icon representing a cloud shape with clean geometric lines in slate blue

Cloud Architecture

AWS EC2, reserved-instance planning, cost modeling, and hybrid infrastructure strategy.

A small icon representing code brackets with clean geometric lines in slate blue

F# & .NET/Mono

Functional programming on OSX, MonoDevelop toolchain, and cross-platform game-dev exploration.

A small icon representing a database cylinder with clean geometric lines in slate blue

PHP & Symfony

Web application development with the Symfony framework and the broader PHP ecosystem.

A small icon representing a storage drive with clean geometric lines in slate blue

Storage & RAID

SATA/SAS controller evaluation, md RAID configuration, and performance benchmarking.

A small icon representing a shield with clean geometric lines in slate blue

High Availability

Pacemaker, STONITH, crm_mon alerting, and Nagios integration for production cluster monitoring.