rasuvaeff / concurrency-limits
Adaptive concurrency limiter (AIMD) for PHP: a drop-in bulkhead whose limit follows latency and overload
Requires
- php: 8.3 - 8.6
- rasuvaeff/bulkhead: ^1.4
- rasuvaeff/duration: ^1.1
Requires (Dev)
- ergebnis/composer-normalize: ^2.51
- friendsofphp/php-cs-fixer: ^3.95
- infection/infection: ^0.35
- maglnet/composer-require-checker: ^4.17
- nyholm/psr7: ^1.8
- predis/predis: ^2.2 || ^3.0
- psr/http-factory: ^1.0
- psr/http-server-middleware: ^1.0
- rasuvaeff/property-testing-testo: ^1.0
- rasuvaeff/rector-named-literals: ^1.0
- rasuvaeff/resilience: ^0.3
- rector/rector: ^2.9.2
- roave/backward-compatibility-check: ^8.0
- testo/bridge-infection: ^0.1.6
- testo/testo: ^0.10.25
- vimeo/psalm: ^7.11
Suggests
- ext-apcu: Required to use ApcuAdaptiveStore (one limit per host, shared by PHP-FPM workers)
- ext-redis: Required to use RedisAdaptiveStore via PhpRedisScriptRunner
- predis/predis: Required to use RedisAdaptiveStore via PredisScriptRunner (^2.2, pure-PHP alternative to ext-redis)
- psr/http-server-middleware: Required to use LoadSheddingMiddleware (with any PSR-17 response factory)
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-12-03 17:27:04 UTC
README
Adaptive concurrency limiter for PHP: a drop-in bulkhead whose limit follows latency and overload instead of being fixed. A port of the AIMD algorithm from Netflix concurrency-limits.
Using an AI coding assistant? llms.txt contains a compact API reference you can share with the model.
Status: 0.x, in development. AIMD, Vegas, Gradient2, in-memory, APCu and Redis stores and a PSR-15 load-shedding middleware are in. The API may change in minor releases until 1.0.
Requirements
- PHP 8.3+
rasuvaeff/bulkhead^1.4 — theBulkheadinterface andBulkheadFullException- optional:
ext-apcu(ApcuAdaptiveStore),ext-redisorpredis/predis(RedisAdaptiveStore),psr/http-server-middleware+ a PSR-17 factory (LoadSheddingMiddleware) rasuvaeff/duration^1.1
Installation
composer require rasuvaeff/concurrency-limits
Usage
use Rasuvaeff\ConcurrencyLimits\AdaptiveBulkhead; use Rasuvaeff\ConcurrencyLimits\AimdLimit; use Rasuvaeff\ConcurrencyLimits\ApcuAdaptiveStore; use Rasuvaeff\Duration\Duration; // PHP-FPM: one limit per host, shared by every worker through APCu. $bulkhead = new AdaptiveBulkhead( name: 'payments-api', algorithm: new AimdLimit(timeout: Duration::millis(300)), store: new ApcuAdaptiveStore(), lease: Duration::seconds(30), isDrop: static fn(\Throwable $e): bool => $e instanceof TimeoutException, ); $result = $bulkhead->call(static fn() => $client->charge($order));
Every call takes a slot under the current limit (fast-fail, no waiting) and releases it with a sample. The caller whose sample closes a window applies the algorithm and publishes the new limit:
| Window outcome | AIMD |
|---|---|
any call dropped, or average round trip above timeout |
limit = floor(limit × backoffRatio) |
| healthy, and at least half the limit was in use | limit + 1 |
| healthy, less than half in use | unchanged — an idle limiter does not drift up |
The result is always clamped to [minLimit, maxLimit].
What counts as a sample
| Call | Sample |
|---|---|
| returns | dropped = false |
throws, isDrop returns true (timeouts, 503 downstream) |
dropped = true |
| throws anything else (validation, 404) | none — it says nothing about load |
outlives its lease (returned or not) |
dropped = true, real round trip — its slot was already reclaimed |
rejected with BulkheadFullException |
none |
Choosing a store
| Store | Limit per | Round trips per call | Window time | Use for |
|---|---|---|---|---|
InMemoryAdaptiveStore |
process | none | hrtime() |
RoadRunner, Swoole, CLI workers, tests — under PHP-FPM every request starts over |
ApcuAdaptiveStore |
host | none (apcu_add spinlock) |
hrtime() |
PHP-FPM; a limit per node, as Netflix runs it |
RedisAdaptiveStore |
cluster | 2 (acquire, release) + 1 per closed window | Redis TIME |
one shared limit for all hosts |
All three keep slots, the open window and the estimate of a name together, so
one atomic step admits a call and another releases it with its sample. A
window is claimed by exactly one caller; its new estimate is published with a
version check and re-applied up to three times if another caller won the race.
Fail-closed: a busy APCu lock rejects the call; an unreachable Redis throws.
Redis keys are hash-tagged ({name}) for Redis Cluster.
use Rasuvaeff\ConcurrencyLimits\Redis\PhpRedisScriptRunner; use Rasuvaeff\ConcurrencyLimits\RedisAdaptiveStore; $store = new RedisAdaptiveStore(new PhpRedisScriptRunner($redis)); // or PredisScriptRunner
Choosing an algorithm
| Algorithm | Reacts to | Settles at (simulated server, capacity C, timeout 2× base latency) | Use when |
|---|---|---|---|
AimdLimit (default) |
drops and rtt > timeout |
≈ 2C: grows until calls hit the timeout | you have a latency budget; simplest to reason about |
VegasLimit |
estimated queue limit × (1 − baseline / rtt) |
≈ C … C + 26 | latency grows with load before anything fails |
Gradient2Limit |
short vs long-term average round trip | follows changes in latency, not capacity | latency drifts; it does not converge to C under steady queueing |
The ranges come from tests/SimulatedServerTest.php (servers with capacity
2–300 and base latency 0.5–50 ms, demand 10×C). AIMD and Vegas shed to the
new capacity when it halves and recover when it returns. Gradient2 does not
track capacity: it shrinks when latency jumps and grows back when latency
returns. Under stable latency its gradient is 1, so it adds queueSize every
window until inflight < limit / 2 — about twice the demand, capped by
maxLimit, whatever the capacity (Netflix behaves the same).
Configuration
| Class | Parameter | Default | Notes |
|---|---|---|---|
AimdLimit |
timeout |
required | latency budget; Netflix uses 5 s, which a PHP handler rarely reaches, so the limit would sit at maxLimit |
initialLimit |
20 | as Netflix | |
minLimit |
1 | Netflix: 20; 1 lets the limit shed below its start | |
maxLimit |
200 | as Netflix | |
backoffRatio |
0.9 | [0.5, 1), as Netflix |
|
VegasLimit |
initialLimit / minLimit / maxLimit |
20 / 1 / 1000 | as Netflix, except minLimit |
smoothing |
1.0 | (0, 1]; 1 = no smoothing |
|
probeMultiplier |
30 | the baseline round trip is re-measured every jitter × probeMultiplier × limit windows |
|
jitter |
Randomizer::getFloat(0.5, 1.0) |
inject a fixed value in tests | |
Gradient2Limit |
initialLimit / minLimit / maxLimit |
20 / 1 / 200 | as Netflix, except minLimit |
smoothing |
0.2 | (0, 1] |
|
queueSize |
4 | headroom added on top of the gradient | |
longWindow |
600 | windows in the long-term average (first 10 are a plain average) | |
rttTolerance |
1.5 | ≥ 1; how much slower than the long average still counts as healthy | |
WindowPolicy |
size |
10 | the window closes after size samples and minDuration |
minDuration |
1 s | ||
AdaptiveBulkhead |
name |
required | /^[A-Za-z0-9_.:-]+\z/ — becomes a store key |
lease |
required | TTL of a held slot | |
isDrop |
none | which exceptions signal overload | |
clock |
hrtime() |
monotonic microseconds for round trips; inject one in tests | |
observer |
none | LimitObserver::limitChanged(name, previous, current) on every change of the enforced limit |
|
InMemoryAdaptiveStore |
clock |
hrtime() |
window time and leases; pass the bulkhead's fake clock in tests |
ApcuAdaptiveStore |
keyPrefix |
concurrency-limits: |
|
lockMaxAttempts / lockRetryMicros |
100 / 1000 | ~100 ms spin budget, as ApcuBulkheadStore |
|
stateTtl |
1 day | ≥ 1 s; an idle name forgets its limit after it | |
RedisAdaptiveStore |
keyPrefix |
concurrency-limits: |
|
stateTtl |
1 day | ≥ 1 ms | |
LoadSheddingMiddleware |
retryAfterSeconds |
1 | ≥ 0 |
With rasuvaeff/resilience
AdaptiveBulkhead implements Rasuvaeff\Bulkhead\Bulkhead and throws
BulkheadFullException, so it plugs into a pipeline unchanged:
$pipeline = Pipeline::for('payments-api')->bulkhead($bulkhead)->build();
PSR-15 load shedding
use Rasuvaeff\ConcurrencyLimits\LoadSheddingMiddleware; $middleware = new LoadSheddingMiddleware($bulkhead, $responseFactory, retryAfterSeconds: 2);
Full → 503 Service Unavailable with Retry-After. Like Netflix's servlet
filter it looks at exceptions only: a handler that returns a 5xx response is a
successful call; exceptions propagate and the bulkhead's isDrop decides
whether they signal overload. Any Bulkhead works, not only the adaptive one.
Public API
| Class | Description |
|---|---|
AdaptiveBulkhead |
call(), availableSlots(), limit(), name() |
LimitAlgorithm |
interface: initial(): LimitEstimate, update(LimitEstimate, Sample): LimitEstimate |
LimitEstimate |
fractional limit plus the algorithm's own state (Vegas baseline, Gradient2 average); limit() is the enforced integer |
AimdLimit |
additive increase, multiplicative decrease |
VegasLimit |
queue estimate against the lowest observed round trip |
Gradient2Limit |
gradient of short vs long-term round trip |
Sample |
round trip (µs), inflight at start, dropped |
SampleWindow |
samples collected towards the next update; aggregate() = average round trip, peak inflight, any drop |
WindowPolicy |
when a window closes |
AdaptiveStore |
interface: acquire(), release() (claims a closed window), publish() (version check), limit(), activeCount() |
InMemoryAdaptiveStore |
per-process store |
ApcuAdaptiveStore |
per-host store; isAvailable() |
RedisAdaptiveStore |
cluster-wide store over a Redis\RedisScriptRunner |
Redis\PhpRedisScriptRunner, Redis\PredisScriptRunner |
Lua runners for ext-redis and predis |
Admission |
token (null = rejected), enforced limit, inflight including the call |
ClosedWindow |
aggregate sample + the EstimateSnapshot to apply it to |
EstimateSnapshot |
stored estimate (null until first publish) + version |
LimitObserver |
interface: limitChanged(name, previous, current) |
LoadSheddingMiddleware |
PSR-15: 503 + Retry-After when full |
Security
- The limit only learns from admitted calls. Rejected calls record
nothing, so if
minLimitis at or below the number of slots held by long-running calls, every new call is rejected and the limit cannot recover until those slots are released or their leases expire. KeepminLimitabove the slots you expect to stay held. InMemoryAdaptiveStoredoes not adapt under PHP-FPM: every request starts with an empty store. Under FPM useApcuAdaptiveStore(per host) orRedisAdaptiveStore(per cluster).- Stores fail closed. A busy APCu lock rejects the call (and a release under
a busy lock drops its sample; the slot expires with its lease). Redis errors
propagate from
call()— wrap the bulkhead if you prefer to fail open. - Redis window time is Redis
TIME(wall clock): a clock step on the Redis host can close a window early or late. Round trips are always measured in PHP withhrtime(). nameis validated before it reaches a Redis/APCu key.
Examples
See examples/ for runnable scripts. Examples are expected to execute without fatal errors and stay aligned with the documented public API.
| Script | Shows | Needs server? |
|---|---|---|
basic.php |
AIMD under a simulated clock: grows while healthy, shrinks when latency passes the timeout, grows back | no |
overload.php |
AIMD, Vegas and Gradient2 side by side through a capacity drop and recovery of a simulated downstream | no |
middleware.php |
LoadSheddingMiddleware: 200 with a free slot, 503 + Retry-After when full |
no |
apcu.php |
Two bulkheads sharing slots and the limit through APCu, as two FPM workers would | no (needs ext-apcu) |
redis.php |
Cluster-wide limit in Redis via predis; LimitObserver prints each change |
yes |
Development
No PHP/Composer on the host — run in Docker via the composer:2 image:
docker run --rm -v "$PWD":/app -w /app composer:2 composer install docker run --rm -v "$PWD":/app -w /app composer:2 composer build docker run --rm -v "$PWD":/app -w /app composer:2 composer cs:fix docker run --rm -v "$PWD":/app -w /app composer:2 composer test docker run --rm -v "$PWD":/app -w /app composer:2 composer release-check
Or with Make:
make install
make build
make cs-fix
make test
make test-coverage
make integration
make mutation
make release-check
make test-coverage and make mutation bootstrap pcov inside the
composer:2 container because the base image has no coverage driver.
make integration runs tests/Integration against a throwaway Redis and
ext-apcu/redis/pcntl. The suite fails, rather than skips, without them.
make mutation needs the same: Infection runs the Mutation suite (Unit +
Integration), because the APCu store and the Redis runners are only exercised
against the real backends.