Alpha ZealPHP is early-stage and under active development. APIs may change between minor versions until v1.0. Feedback and bug reports welcome on GitHub.
API Index — Namespaces, Packages, Reports, Indices

RateLimitMiddleware
in package
implements MiddlewareInterface

Rate-Limit Middleware (sliding window, per-IP, shared across workers)

Tracks request counts per client IP in a shared Store table. When a single IP exceeds $limit requests inside $window seconds, further requests receive a configurable HTTP error (default 429 Too Many Requests) with a Retry-After header.

nginx parity

limit_req_zone $binary_remote_addr zone=one:10m rate=60r/m; limit_req zone=one burst=5 nodelay;

ZealPHP equivalent:

$app->addMiddleware(new RateLimitMiddleware( limit: 60, window: 60, burst: 5, nodelay: true, tableName: 'rate_limit', ));

Algorithm note — fixed window vs leaky bucket

nginx's limit_req uses a leaky-bucket (token-drain) algorithm with millisecond precision. ZealPHP uses a fixed window that resets every $window seconds. The practical difference is the "thundering-herd at boundary" problem: a fixed window allows up to $limit requests at the tail of one window and another $limit at the head of the next window — a worst-case 2× burst. A leaky bucket smooths this out. For spam/abuse defence the fixed window is sufficient; for billing-grade fairness or tight concurrency control, consider implementing a leaky-bucket variant.

burst= / nodelay= / delay=

  • burst=N — allow up to N extra requests above the limit per window before rejecting. Requests within the burst quota are forwarded.
  • nodelay=true — burst requests are forwarded immediately (no artificial delay). This matches nginx limit_req ... nodelay.
  • Without burst (default burst=0), any request over the limit is rejected.

Trusted-proxy / X-Forwarded-For integration (B2 fix)

The zone key is now resolved via App::clientIp() which honours App::$trusted_proxies. Operators deploying behind Traefik/nginx must configure App::trustedProxies() so the rate-limit key is the real client IP rather than the proxy's IP.

Store-full failure policy (B10 fix)

When the OpenSwoole Table is full, Store::set() returns false. Rows are never removed by the Table itself, so the table used to fill with every client ever seen and from then on let every NEW client through unlimited (a botnet, or one IPv6 host cycling addresses, switched the limiter off). The middleware now evicts the rows whose window has ended (at most once a second per worker) and retries. Only when every row is still live does it log a warning via elog() and fail open (pass the request through) — rejecting an unknown client because the table is full would be overly aggressive. Size the table for the clients active within one window.

IPv6

A single IPv6 host is routinely given a whole /64, so a per-address key is free to evade. IPv6 clients are keyed by their /64 (IPv4-mapped addresses by the IPv4 address), see clientKey().

Dry-run mode

dryRun=true runs all accounting and logs what would have been blocked, but forwards every request regardless. Use this to calibrate rate-limit settings on production traffic without impacting availability.

Configurable reject status

rejectStatus defaults to 429. Pass 503 for nginx parity (nginx historically uses 503 for rate-limit rejections). Any 4xx/5xx code is accepted.

Loopback bypass

By default, requests from 127.0.0.1 / ::1 are not rate-limited so the integration test suite can run repeatedly without php app.php restart. Set ZEALPHP_RATE_LIMIT_LOOPBACK=1 to opt in (useful when testing the limiter).

Store table schema (create before $app->run())

Store::make('rate_limit', 16384, [ 'ip' => [\OpenSwoole\Table::TYPE_STRING, 64], 'count' => [\OpenSwoole\Table::TYPE_INT, 4], 'reset' => [\OpenSwoole\Table::TYPE_INT, 4], ]);

$app->addMiddleware(new \ZealPHP\Middleware\RateLimitMiddleware( limit: 60, window: 60, tableName: 'rate_limit', ));

If the table doesn't exist when the request arrives the middleware fails-open (passes the request through) and logs once via elog().

Table of Contents

Interfaces

MiddlewareInterface

Properties

$burst  : int
$dryRun  : bool
$lastEviction  : array<string, int>
$limit  : int
$nodelay  : bool
$rejectStatus  : int
$tableName  : string
$warnedMissingTable  : bool
$window  : int

Methods

__construct()  : mixed
clientKey()  : string
Limiter key for a client address: an IPv6 address by its /64 (one host typically holds the whole /64), an IPv4-mapped IPv6 address by its IPv4 address, anything else unchanged.
evictRows()  : int
Delete rows of $table that $isDead says are finished, at most once a second per worker per table. Collect-then-delete: deleting while iterating an OpenSwoole\Table skips rows.
process()  : ResponseInterface
windowEnded()  : bool
Has this rate-limit row's window ended at $now? A row without a usable reset counts as ended (it can't be limiting anyone).
isLoopback()  : bool
logDryRunBlock()  : void
tooMany()  : ResponseInterface

Properties

$lastEviction

private static array<string, int> $lastEviction = []

Per table: last expired-row eviction (unix time).

Methods

__construct()

public __construct([int $limit = 60 ][, int $window = 60 ][, string $tableName = 'rate_limit' ][, int $burst = 0 ][, bool $nodelay = false ][, int $rejectStatus = 429 ][, bool $dryRun = false ]) : mixed
Parameters
$limit : int = 60
$window : int = 60
$tableName : string = 'rate_limit'
$burst : int = 0
$nodelay : bool = false
$rejectStatus : int = 429
$dryRun : bool = false

clientKey()

Limiter key for a client address: an IPv6 address by its /64 (one host typically holds the whole /64), an IPv4-mapped IPv6 address by its IPv4 address, anything else unchanged.

public static clientKey(string $ip) : string
Parameters
$ip : string
Return values
string

evictRows()

Delete rows of $table that $isDead says are finished, at most once a second per worker per table. Collect-then-delete: deleting while iterating an OpenSwoole\Table skips rows.

public static evictRows(string $table, callable(array<string, scalar>): bool $isDead) : int
Parameters
$table : string
$isDead : callable(array<string, scalar>): bool
Return values
int —

Rows deleted.

process()

public process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
Parameters
$request : ServerRequestInterface
$handler : RequestHandlerInterface
Return values
ResponseInterface

windowEnded()

Has this rate-limit row's window ended at $now? A row without a usable reset counts as ended (it can't be limiting anyone).

public static windowEnded(array<string, mixed> $row, int $now) : bool
Parameters
$row : array<string, mixed>
$now : int
Return values
bool

isLoopback()

private isLoopback(string $ip) : bool
Parameters
$ip : string
Return values
bool

logDryRunBlock()

private logDryRunBlock(string $ip, int $count, int $retryAfterSeconds) : void
Parameters
$ip : string
$count : int
$retryAfterSeconds : int

tooMany()

private tooMany(int $retryAfterSeconds) : ResponseInterface
Parameters
$retryAfterSeconds : int
Return values
ResponseInterface
On this page