Shared\Pool
OxPHP\Shared\Pool is a bounded pool of per-thread resources. It is the primitive for managing objects that are expensive to create, cannot be recreated cheaply, and should not exist in unlimited numbers: typically database connections, prepared-statement caches, reusable JSON decoders, or HTTP client sessions.
A Pool gives each PHP worker thread its own lane of ready-to-use resources, enforces a strict maximum across the whole pool, and recycles idle slots automatically so you do not pay for capacity you do not use.
Overview
- The budget is strict.
maxSizeis a hard cap across the whole pool, and when the pool is saturated, an acquire waits, returnsnull, or throws, depending on which acquire method you call. - Slots have per-thread affinity. Each worker thread has its own idle queue, and an acquire pulls from the local queue first. It never hands a slot minted on thread A to thread B.
- The factory runs on the acquiring thread. Resources are minted lazily on first demand per thread, not at pool construction. In worker mode that thread can be another worker's or a task's, where your script's functions and classes may not exist; see Callbacks on other threads for the rules a callback must follow there.
- An optional
destroy($resource)closure runs on the thread holding a slot whenever the pool drops that slot (idle timeout, manual eviction, the pool going away there). It does not run at server stop unless you ask for it. See When the destroy callback is skipped. - In worker mode, slots sitting idle longer than
idleTimeoutMsare destroyed by the worker thread holding them, which a background scheduler wakes for the purpose. SetidleTimeoutMs: 0to disable idle eviction entirely. Slots held elsewhere are not evicted this way. See Idle-timeout eviction. - Handles are RAII.
acquire()returns aHandle, and the slot returns to the pool automatically when the handle goes out of scope (including on exception), or earlier via$handle->release(). - Pools are Shareable. In worker mode a pool survives request boundaries and is shared by handle (
use ($pool)in closures), but its factory and destroy callback still end with the worker that created the pool. See When the worker that created a pool exits. Outside worker mode a pool lasts only as long as the request that creates it. See Outside worker mode.
API Reference
namespace OxPHP\Shared;
final class Pool implements Shareable
{
public function __construct(
callable $factory, // fn(): object — create a resource
?callable $destroy = null, // fn(object): void — tear down a resource
int $maxSize = 32, // hard cap on live slots; > 0
int $idleTimeoutMs = 300_000, // idle ms before eviction; 0 disables it
);
// acquire family — millisecond timeout trichotomy
public function acquire(): Pool\Handle; // wait forever
public function tryAcquire(): ?Pool\Handle; // non-blocking; null if saturated
public function acquireTimeout(int $ms): Pool\Handle; // bounded; $ms > 0
// with family — scope-guard around the raw resource
public function with(callable $body): mixed; // wait forever
public function withTimeout(callable $body, int $ms): mixed; // bounded; $ms > 0
public function stats(): Pool\Stats; // point-in-time snapshot of counters
public function evict(): int; // force-evict the idle slots of the calling thread now; returns count
public function id(): int;
}
namespace OxPHP\Shared\Pool;
class Handle
{
public function get(): mixed; // the underlying resource (throws after release)
public function release(): void; // return the slot now; idempotent; also runs on destruct
}
final class Stats
{
public function inUse(): int; // slots currently checked out
public function idle(): int; // free slots on every thread; acquire() takes only its own thread's
public function waiting(): int; // callers waiting in acquire
public function size(): int; // inUse() + idle() (live slots)
public function maxSize(): int; // configured cap
public function utilization(): float; // inUse() / maxSize(), 0.0 if maxSize() == 0
}| Method | Returns | Use case |
|---|---|---|
acquire |
Handle |
Check out a resource, waiting forever for a free slot. |
tryAcquire |
?Handle |
Non-blocking check-out. Returns null immediately if the pool is saturated. |
acquireTimeout |
Handle |
Check out within a bounded budget of $ms (> 0); throws OperationTimeoutException on expiry. |
with |
mixed | Scope-guard: acquire (forever), run $body($resource) with the raw resource, release even on exception. The closure's return value passes through. |
withTimeout |
mixed | Like with, but the acquire is bounded by $ms. |
stats |
Pool\Stats |
Point-in-time snapshot of pool counters. |
evict |
int | Force-evict all idle slots of the calling thread now (regardless of idleTimeoutMs); returns the count dropped. |
id |
int | Registry identifier; useful for logging / observability. |
Handle::get |
mixed | The underlying resource. Throws StaleHandleException after release. |
Handle::release |
void | Return the slot to the pool now. Idempotent; also runs automatically on destruct (RAII). |
Timeouts follow the same trichotomy as Shared\Mutex and Shared\Channel: a bare method waits forever, a try* method is non-blocking, and a *Timeout(int $ms) method waits a bounded number of milliseconds. There is no float-seconds timeout.
Examples
Database connection pool
<?php
$db = new OxPHP\Shared\Pool(
factory: function () {
return new PDO(
getenv('DB_DSN'),
getenv('DB_USER'),
getenv('DB_PASS'),
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION],
);
},
destroy: function (PDO $conn) {
// Nothing to do — PDO closes on destruct. The callback exists
// for resources that need explicit teardown (sockets, handles).
},
maxSize: 16,
idleTimeoutMs: 60_000, // free idle connections after 1 min
);
// In a request handler
$users = $db->with(function (PDO $conn) use ($userId) {
$stmt = $conn->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$userId]);
return $stmt->fetch();
});with() is the shortest-lifetime pattern: acquire happens on entry, release happens on return or on exception, and you cannot leak a handle. It also hands your closure the raw resource directly, which skips the Handle::get() step.
Manual acquire / release
<?php
$h = $pool->acquire(); // waits forever for a free slot
$conn = $h->get();
$conn->beginTransaction();
doWork($conn);
$conn->commit();
$h->release(); // or just let $h fall out of scope (RAII)The handle returns its slot automatically when it is destroyed, including when an exception unwinds the stack, so an explicit release() is optional. Prefer a manual handle over with() only when the resource must survive multiple calls in a handler sequence.
Reusable parser pool
<?php
$parsers = new OxPHP\Shared\Pool(
factory: fn () => new JsonMachine\Parser(),
maxSize: 8,
);
$doc = $parsers->with(fn ($p) => $p->parse($body));Non-blocking acquire with fallback
<?php
$h = $pool->tryAcquire();
if ($h === null) {
// Pool saturated — degrade gracefully without waiting.
http_response_code(503);
header('Retry-After: 1');
return;
}
// ... use $h->get(); slot returns on scope exit.Bounded acquire with a timeout
<?php
try {
$h = $pool->acquireTimeout(100); // wait up to 100 ms
} catch (OxPHP\Shared\OperationTimeoutException $e) {
http_response_code(503);
header('Retry-After: 1');
return;
}
// ... use $h->get();Factory and destroy semantics
The factory runs lazily on the acquiring thread. A pool with maxSize: 32 does not pre-allocate 32 resources; it mints them as demand arrives, bounded by maxSize across all threads combined.
- The factory must return an object. Returning anything else makes the acquire throw
TypeException, and the slot is not counted against the budget. - An exception the factory throws reaches the acquire caller unchanged. A fatal error in the factory ends the request. In neither case is the slot counted against the budget.
- The destroy callback (if supplied) runs when the pool drops a slot: on idle timeout, on
evict(), or when the pool's last reference goes away on the thread holding the slot. It runs on that thread, while PHP code is running there. It does not run at server stop, nor for a slot another thread holds (see When the destroy callback is skipped). - An exception the destroy callback throws is swallowed: neither the caller nor the server log sees it, and the pool is not poisoned. A destructor that runs as that exception is freed (its own
__destruct(), or that of an object it holds) throws at the point in your code that dropped the slot: theunset(), theevict()call, or the call of a function that returned holding the pool. Idle-timeout eviction drops that exception as well. - The pool calls its own copy of a closure you pass, with the same code,
$thisand captured variables. Astaticvariable in the closure's body is shared with the copy only if a call had already set it when the pool was created; otherwise each keeps its own. A closure made from a function or method (make(...)) uses that function'sstaticvariables.
On a thread other than the one that created the pool, both callbacks follow stricter rules. See Callbacks on other threads.
Fatal errors in the destroy callback
What a fatal error in $destroy does depends on what called it.
evict(). The error ends the request or the task, as it would anywhere else. The slot being destroyed counts as dropped, and the idle slotsevict()had not reached yet stay in the pool. The object in the dropped slot is not freed: in worker mode, and in a pool created inside anoxphp_async()task, it stays alive until its thread exits, so a connection in it stays open without counting againstmaxSize.- Idle-timeout eviction. There is no request to end, so the error retires the worker, which logs a warning saying so, and the pool starts a replacement. The slot being destroyed counts as dropped, and the eviction calls no destroy callback after the one that failed. The idle slots it had not reached on that worker, in this pool and in any other, are released when the worker exits.
- The pool's last reference going away (an
unset()of the last variable holding the pool, or aShared\Mapletting go of it). The error ends the request or the task. The slot being destroyed counts as dropped, and the pool's other idle slots on that thread go without$destroy, as do those of any other pool the same call lets go of (two pools a map'sclear()removes, say). None of these objects is freed, and neither are the pool's callbacks: outside worker mode PHP frees them with the rest of the request, while in worker mode and in anoxphp_async()task they stay alive until the thread exits, connections included.
Callbacks on other threads
In worker mode the factory runs on whichever PHP thread acquires, and the destroy callback on whichever thread holds the slot. That can be a thread other than the one that created the pool:
- another worker thread, for a pool shared between workers (bound to a name with
Registry::pool(), or held in aShared\Map); - a task's thread of the
ASYNC_WORKERSpool, for an acquire inside anoxphp_async()task, or anevict()there; - for a pool created inside a task, any thread other than that task's.
A task's thread never ran your script: only built-in functions and classes and those loaded by opcache.preload exist there. Another worker thread has what its own requests have loaded. Outside worker mode a pool serves only the request that created it (see Outside worker mode), so none of this section applies.
What a refusal looks like
Before a callback's first statement runs on such a thread, OxPHP checks that it can run there, even if it already ran on another thread. When the check fails:
- the factory is not run: the acquire throws
Error, and the slot is not counted against the budget; - the destroy callback is skipped as if it had thrown: the slot is dropped all the same, and
evict()counts it.
On a task's thread, a function of your script is also checked as the thread enters it, however it was reached. One that calls a function of its own file the thread has not loaded, or declares a class, does not start, and its caller gets the Error; a generator function's body is refused on its first resume. The function is checked whole, so such a call in a branch it does not take refuses it as well.
The Error message names the code (The closure at file:line, Method C::m() or Function f()), says why, and ends with so the code was not run:
| Message | Fix |
|---|---|
Call to undefined function f() at file:line: it belongs to a script this PHP thread has not loaded; only built-in functions and classes and those loaded by opcache.preload exist on every PHP thread, so the code was not run. The same tail follows Cannot declare class C at file:line and Cannot declare anonymous class at file:line. |
Call only code that exists on that thread |
… is not in OPcache's shared memory: on a thread other than the one that created the pool, a Shared\Pool callback runs only when its code is there, so the code was not run |
Keep OPcache's shared memory on |
Variable $x of the closure at file:line holds …: on a thread other than the one that created the pool, a Shared\Pool callback runs with copies of its closure's variables, and only null, booleans, numbers, strings, arrays of these and OxPHP\Shared objects are copied, so the code was not run. A variant starts A variable of the closure at file:line holds a value that is not copied. |
Pass a static method or a self-contained closure |
The closure at file:line uses $this: on a thread other than the one that created the pool, a Shared\Pool callback cannot use an object of the request that created it, so the code was not run. The same tail follows … is called on an object and Built-in method C::m() is called on an object. |
Pass a static method or a self-contained closure |
Enum E was not loaded by opcache.preload: every request that loads such an enum has a copy of its own, cases included, and on a thread other than the one that created the pool a Shared\Pool callback would reach the copy of the request that created it, so the code was not run |
Preload enums and classes linked in request memory |
Class C was linked in the memory of the request that loaded it, not in OPcache's shared memory: every request that loads such a class has a copy of its own, and on a thread other than the one that created the pool a Shared\Pool callback would reach the copy of the request that created it, so the code was not run |
Preload enums and classes linked in request memory |
… keeps its static variables in the memory of the request that created the pool: on a thread other than that one, a Shared\Pool callback cannot use them, so the code was not run |
Preload enums and classes linked in request memory |
Rules for callbacks
A callback that follows these rules runs on every thread. The short version: write the factory and destroy callback as static methods of a preloaded class, or as closures that capture only plain values and call only built-in or preloaded code, and keep OPcache on.
Pass a static method or a self-contained closure
These run on another thread:
- a static method:
[Maker::class, 'make'],Maker::make(...), or[$maker, 'make']whenmake()is static; - a function name, or a closure made from a function (
make(...),Closure::fromCallable('make')); - a closure that captures, and keeps in
staticvariables, only null, booleans, numbers, strings, arrays of these, andOxPHP\Sharedobjects.
These are refused there:
- a closure that captured, or keeps in a
staticvariable, any other object (an enum case included), a closure, a resource, or an array that holds itself, at any depth; - a closure bound to an object when its body, or a closure declared in it, uses
$this; - a callable that calls a method on an object other than an
OxPHP\Sharedone, whatever the method does (__call()and__invoke()included):[$object, 'make'],$object->make(...), an invokable object,[$object->make(...), '__invoke'], or a method of a built-in class such as[$queue, 'dequeue'],$queue->dequeue(...),[$closure, 'call']or[$reflection, 'invoke']; [self::class, 'make']naming a non-static method, when the pool is created in a non-static method of that class or of a subclass, since PHP calls it on that method's$this.
A closure that calls a non-static method through parent::, self::, static:: or a class name has no $this there, and PHP throws Error: Non-static method … cannot be called statically.
Keep shared state in OxPHP\Shared objects
On another thread, a closure runs with copies of the captured and static variables it had when the pool was created. Every call there starts from those values:
- A change a call makes lasts until the call returns: a
static $n = 0; $n++;counter in a destroy callback counts to1on every such call. - A call does not see what the creating request changes later, even in a variable captured by reference.
- The copies are made on every call, so a large captured array costs that much each time.
An OxPHP\Shared object is shared, not copied: it is the same counter or map the creating request holds. Keep the state the calls should share in one.
A closure made from a function or a static method runs as that function, with the static variables the function has on that thread. They start from their initial values on the thread's first call and keep what every call leaves: on another worker thread until that worker exits, on a task's thread for as long as it runs, and in a request served without worker mode until it ends. On the thread that created the pool the closure shares them with the function.
Keep OPcache's shared memory on
On another thread a callback runs only when its code is in OPcache's shared memory. The code that counts is the closure's, the function or method the callable names, or the __invoke(), __call() or __callStatic() the call runs. This code is not there:
- every script with
opcache.enable=0oropcache.file_cache_only=1; - code passed to
eval(); - a script OPcache compiles without caching it: a blacklisted one, one changed too recently (under
opcache.file_update_protection), or one compiled while OPcache's shared memory is full.
A callback in such code runs only on the thread that created the pool, so without OPcache's shared memory a pool whose factory is written in PHP makes slots only there. A parent-class or trait method outside that memory, reached through parent::, self:: or static:: from cached code, is refused too, because its class is linked in request memory.
Call only code that exists on that thread
A callback is refused when it calls a function declared in its own file, or declares a class (named or anonymous), and that thread has not loaded the file. On a task's thread that is every file of your script, so load what the callback needs with opcache.preload. On another worker thread it is a file that only some requests include: include it from the worker script, or preload it.
The check also follows the callback into what it carries:
- the closures it declares, and
$thisif it uses$this; - the classes
selfandstaticstand for (both, whichever the callback writes), when the callback:- calls or creates through
self::,static::orparent::(self::make(),new static(), a parameter default$maker = new self()); - names
forward_static_call()orforward_static_call_array(); - runs
eval(),includeorrequire, whose code takes those classes (eval('return self::make();')); - holds a callable string or array that names a class that way (
'static::make',['self', 'make'],'static::' . $method): in its code, captured, as astaticvariable's initial value or a parameter default, or in a constant or property default of those classes that it reads throughself::,static::orparent::(call_user_func(static::CALLBACK));
- calls or creates through
- the class a built-in static method is called on, such as
[MyDate::class, 'createFromInterface']withMyDateextendingDateTime, since the object it creates runs that class's__destruct(); - the class whose
__call()or__callStatic()answers a method the callback names; - the closure behind a
[$closure, '__invoke']callback; - on PHP 8.5, the closures in the constant expressions (constant values and property defaults) of those classes, their parents and the interfaces they inherit a constant from, when the callback reads a constant or static property through
self::,static::orparent::.
A class is checked whole: every method and property hook of it and of its parent classes, __destruct() included. A string that is self, static or parent for another reason (the property name in $node->parent, the value in ['rel' => 'self'], a captured $mode = 'static') gets those classes checked as well.
Preload enums and classes linked in request memory
An enum the callback reaches through self:: in the enum's own method (self::Primary) or through a callable ([Suit::class, 'cases']) is refused unless opcache.preload loads it, even on a thread that has loaded the same enum. Each request that loads such an enum has a copy of its own, cases included, and PHP crashes creating a case on a thread that does not have the enum.
Any other class that each request links in its own memory is refused the same way when the callback reaches it through self::, static::, parent::, new static or forward_static_call(), through eval(), include or require while self or static stands for it, or through its __call() or __callStatic(). Such a class is one:
- whose parent class, interface or trait is outside OPcache's shared memory (one declared in
eval(), say); - with a method whose type PHP checks, as it links the class, against such a class or an enum
opcache.preloaddoes not load (a method returning that enum where the interface declares\UnitEnum, say); - linked while OPcache's shared memory is full.
A method that such a class declares or takes from a trait, passed by name or as a closure ([Suit::class, 'make'], Suit::make(...)), is refused when it declares static variables. Without them, each call runs it on its own, with a run-time cache that lasts for that call, unless what it reaches of its class is refused. A method such a class only inherits from a parent in OPcache's shared memory is the parent's, and runs as its name would. Preloading the class and what it depends on avoids all of this.
Callables built at run time
The check before the first statement cannot see a callable your code builds at run time. That covers a string or array with self, static or parent as its class ('static::make', ['self', 'make']), and an array that names a class and then self:: or parent:: as its method ([Base::class, 'self::make']). Built from a property, a function's result, a value an OxPHP\Shared object holds or a global constant (call_user_func(MAKE_CB)), or held by a static variable or static property a call has set, such a callable is checked when PHP resolves it. That is when the code calls it, or earlier, when is_callable() or a callable parameter looks at it.
- If the class it runs with is one this thread has not loaded itself, that class is checked whole. When something is missing the method does not start and
Erroris thrown there, after whatever the callback did up to that point. The callback can catch it and go on. Closure::fromCallable(), andcall_user_func()orcall_user_func_array()where PHP compiles them to an opcode of their own (\call_user_func(), or any call in the global namespace), report it as aTypeErrorwithmust be a valid callback, (null), and theErroras itsgetPrevious().- An error handler set for the deprecation PHP raises for these callables is not called for such a call. With no handler set, the deprecation is reported as
error_reportingallows, next to the exception. - On PHP 8.4 and 8.5,
filter_var()withFILTER_CALLBACK, and a stream notifier on PHP 8.4, resolve the callable only as they call it. A refused[Class, 'self::m']method there leaves before its first statement, and none of its owncatchorfinallyblocks run. - On PHP 8.6,
filter_var(),filter_var_array(),filter_input()andfilter_input_array()check aFILTER_CALLBACKas they are called, before any filter runs. A failed check throws theErrorand calls nothing, even when the input is absent, and a callable PHP would reject (parent::in a class without a parent, a missing method) gets thisErrorin place of PHP'sTypeError. A callback or filter id held through a reference is checked whatever it holds, since code run during the call can rewrite it.
What the check does not cover
These are not checked before the callback starts. Keep them to built-in or preloaded code:
- An object held in a property, a static property, a class constant or a
staticvariable, or inside a built-in object such asArrayObject,SplObjectStorageor aGenerator. - A pool created inside a task from code the task was handed. On that task's thread its callbacks run from the memory of the request that dispatched the task, which can end before the pool does.
- Code that OPcache's file cache keeps in a request's memory (
opcache.file_cache_only=1, say) is not always recognised, and a callback in it then runs on other threads. That happens when another thread loaded the code, or while PHP's allocator is switched off withUSE_ZEND_ALLOC=0or replaced by an extension. - For code outside OPcache's shared memory that still runs on another thread, a closure it declares has one run-time cache for every thread. A class it names throws when missing until the closure has run, and after that PHP reuses the class it found, on every thread. The same cache records whether a function of that code is checked as a task's thread enters it, decided by the first thread that runs the function.
On another worker thread, the calls below get through, and a call from there to a function of your script that the thread lacks can crash the server. On a task's thread the entry check (see What a refusal looks like) still stops the first two.
- On PHP 8.5 and 8.6, a run-time callable is not checked while OPcache compiles a file. A stream wrapper can run one then, as it serves an included file (
stream_read()of a wrapper registered in place offileorphar, or of one aninclude_pathentry leads to). The code doing theincludecan get theErroronce the compile ends. ob_start(), and other built-in functions that keep a callable to call later, keep a refused[Class, 'self::m']array, and later call its method without the check.- An extension that runs PHP code as a function is entered gets past the entry check too: one loaded after OxPHP that does so from the engine's interrupt hook (
pcntlwithpcntl_async_signals()), or one whose function-call observer runs after OxPHP's.
Per-thread affinity
Pools are strict per-thread: a slot minted on worker thread A cannot be acquired on worker thread B. In practice, stats()->idle() can be non-zero on worker A while worker B is waiting in acquire(). This keeps slots hot in the thread that uses them (DB connections, OPcache-primed objects) and avoids shuffling resources across cores.
Slots do not move between threads, so size maxSize against the number of worker threads × expected per-thread concurrency, not just aggregate demand.
Once maxSize slots exist, a thread that holds none of them gets one only after a slot is destroyed. A slot given back stays with the thread it was made on, however long it sits idle there. In worker mode with maxSize: 1 and two workers, for instance, a request on the second worker waits while the first worker's slot sits idle, with stats() reporting idle() 1 and inUse() 0.
The wait ends when idle-timeout eviction destroys that slot on the first worker (idleTimeoutMs after it was last given back at the earliest, and only once that worker has no request in flight), when evict() is called there, or when that worker exits. If the worker that exits is the one that created the pool, the waiting call throws ClosedException instead of getting a slot. See When the worker that created a pool exits.
With idleTimeoutMs: 0, or for slots idle on a thread of the ASYNC_WORKERS pool, which idle-timeout eviction does not reach (see Idle-timeout eviction), acquire() and with() can wait until the server shuts down. Where the pool can run short, use acquireTimeout() or withTimeout().
Outside worker mode
With traditional, Framework or SPA routing, every HTTP request is a PHP request of its own. When it ends, PHP frees every object it created, including the pool's factory and destroy closures and every object the factory returned. A pool that a request creates there is tied to that request:
- Only that request can acquire from it.
acquire(),tryAcquire(),acquireTimeout(),with()andwithTimeout()throwClosedException(outside worker mode a Shared\Pool can only be used by the request that created it, and only until that request ends) when called from any other request (one that reached the pool through aShared\Map, say) or from a task started withoxphp_async(). - When the request ends, the pool closes. PHP frees the objects still idle in it along with the rest of the request, like any other object the request created, and
$destroyis not called for them. Any later acquire throwsClosedException. - If the pool's last reference goes away in another request or in a task while the creating request still runs, the pool closes then.
$destroyis not called for its idle objects either: PHP frees them when the creating request ends. Registry::pool()called from a request throwsSharedExceptionwithout calling its factory:Shared\Registry::pool() cannot be called from a request served without worker mode: a pool a request creates there lasts only until that request ends, and a registry name lasts as long as the server.Registry::global()throws it when its factory returns a pool, with a message startingShared\Registry::global() cannot bind a Shared\Pool to a name in a request served without worker mode. In a task that the request hands its pool to, both throw it (Shared\Registry cannot bind a Shared\Pool to a name: …) when their factory returns that pool.idleTimeoutMshas no effect, since no slot outlives the request.
A pool created inside a task started with oxphp_async() is not tied to a request. The task's thread runs a single PHP request for as long as it lives, and a task can bind the pool to a name with Registry::pool(). Its idle slots are not evicted by idleTimeoutMs, though (see Idle-timeout eviction). A request that calls Registry::pool() with that name still gets SharedException. Handing such a pool to HTTP requests served without worker mode gains them nothing. Each object such a request gets from it was created by that request's own call to the factory and is reused only within that request. When the request ends, PHP frees it along with the rest of the request, without $destroy. Without worker mode, use such a pool from tasks only.
oxphp run executes the whole script as one request. There, a pool the script creates (Registry::pool() included) serves it from start to finish and closes when it ends, without $destroy for the objects still idle at that point, and idleTimeoutMs has no effect on it. A task started with oxphp_async() cannot acquire from it or bind it to a name there either.
To keep database connections open across requests without worker mode, use the driver's persistent connections instead of a pool. For PDO that is PDO::ATTR_PERSISTENT => true, which keeps a connection open in each PHP worker thread for the next request on that thread that connects with the same DSN and credentials. To share one pool across requests, run the application in worker mode.
When the worker that created a pool exits
A pool's factory and destroy callback belong to the PHP request that created the pool, like every closure that request makes, and PHP frees them when that request ends. In worker mode that request is the worker's script, which runs for as long as the worker does. It ends when the worker is recycled, when a dynamic pool retires it, and when the server stops. In a task started with oxphp_async(), it is the request of the task's thread, which lasts as long as that thread. The pool itself lives on wherever another worker still holds it (under a name, in a Shared\Map, or in a variable of its own), so the callbacks end before the pool does:
- Once the script of the request that created the pool has run to its end (
oxphp_worker()has returned and the code after it has run), that request waits for the calls other threads are making into the factory or the destroy callback to return. Only then do its shutdown functions and destructors run and PHP free its memory. The wait has no limit. A callback that in turn waits for something the exiting worker gives up only as it shuts down, such as a lock it releases in a destructor, keeps that worker from exiting at all. After 5 seconds of waiting, the server logs a warning. - From then on, no other thread calls them. The slots that already exist are still handed out and given back as before. An acquire that has to make a new slot throws
ClosedException:Shared\Pool cannot make a new slot: its factory belonged to a PHP request that has ended. A pool bound to a name takes the factory and destroy callbacks of the next Shared\Registry::pool() or Shared\Registry::global() call for that name. A slot that another thread destroys, withevict()or by idle eviction, goes without$destroyand is counted inoxphp_shared_pool_destroy_skipped_total{reason="request_ended"}. - The request that created the pool can still call them itself while it shuts down, in its shutdown functions and its destructors.
A pool bound to a name gets new callbacks from the next call to Registry::pool() or Registry::global() for that name that is made in a request that is not shutting down. That call runs its factory. If the factory returns a pool that the request making the call created, the bound pool takes that pool's factory and destroy callback, but not its maxSize or its idleTimeoutMs. A pool the factory got from elsewhere, such as another name, gives it none. The call returns the bound pool, as on any other hit. From then on, new slots come from the new factory, and the new destroy callback is called for every slot of the pool, including the slots the old factory made. If the factory returns anything but a pool, the call throws TypeException, and if the factory throws, the exception propagates. Either way, the bound pool keeps the callbacks it had.
When the workers call Registry::pool() for the name as they boot, the replacement of the worker that created the pool gives it new callbacks as soon as it boots. Until then, the other workers can only use the slots that exist. A worker that calls Registry::pool() again, inside the request handler for instance, gives the pool its own callbacks first:
<?php
oxphp_worker(function () {
$db = Registry::pool('db', fn () => new Pool(
factory: fn () => new PDO(getenv('DB_DSN')),
maxSize: 16,
));
// ...
});A pool not bound to a name never gets new callbacks. Once the request that created it has ended, it hands out the slots it has, and an acquire that needs a new one throws ClosedException.
Idle-timeout eviction
Idle-timeout eviction works in worker mode. A background scheduler looks at every pool twice a second. When a worker holds a slot that has been idle longer than idleTimeoutMs, the scheduler wakes that worker. As soon as the worker has no request in flight, it destroys every slot of its own that has been idle that long, in every pool, and calls $destroy for each. The budget is released at the same point. A worker waiting for its next request does this at once, without serving a request for it. One that always has a request in flight (one carrying long-lived streams, say) does it the next time it has none.
Once the server has begun its graceful shutdown, the eviction no longer runs, so that a fatal error in $destroy cannot retire a worker and have the pool boot a replacement in the middle of the drain. A slot that goes stale during the drain stays in the pool like every other idle slot, and the server's stop does not call $destroy for it. See When the destroy callback is skipped.
$destroy runs there between requests, on the worker's own PHP engine. What it outputs there, buffered or not, belongs to no response and is discarded, and a shutdown function it registers there is dropped without running. max_execution_time does not apply to it, so a callback that never returns stops that worker from serving. A fatal error in it retires the worker (see Fatal errors in the destroy callback).
Slots held anywhere else are not evicted by idleTimeoutMs. They stay until evict() is called on the thread holding them, or until that thread or the pool goes away. That covers the slots that a task started with oxphp_async() acquires and releases, which park on the task's thread, and every pool under oxphp run. Without worker mode, a pool that a request creates closes with that request anyway (see Outside worker mode).
Tune idleTimeoutMs to the cost of recreation:
- For resources that are cheap to re-mint (JSON decoder, string pool), set 10_000 to 60_000 ms to free memory fast when traffic dies down.
- For resources that are expensive to re-mint (DB connection, TLS session), set 300_000 ms (the default) to 900_000 ms so you pay the recreation cost less often.
- To never evict, pass
0. Idle slots then live until the pool is dropped.
$pool->evict() force-evicts all idle slots of the calling thread right now, regardless of idleTimeoutMs, and returns how many were dropped. Use it as the operational "flush idle now" escape hatch (e.g. when a downstream service restarted and you want the next acquire to mint fresh resources). In-use slots are untouched. evict() holds no lock of the pool while it runs the destroy callback, so the callback can call tryAcquire() and release() on that same pool.
When the destroy callback is skipped
$destroy is called only on the thread that holds the slot, and only while PHP code is running there. Otherwise the slot is let go without the callback, and PHP frees the object in it when the request of the thread holding it ends. That happens in these cases:
- The server stops. The shutdown closes every pool but destroys no slot, because it runs on a thread that holds none. The workaround for worker mode is below this list.
- The request that created the pool has ended. In worker mode and in tasks started with
oxphp_async(), once the request that created the pool has begun to shut down, no other thread calls its destroy callback, and the slots other threads destroy go without it. See When the worker that created a pool exits. - A request is ending. A pool whose last reference goes away while its request is ending (once a worker's script has run to its end, say) goes away with no PHP code running, so
$destroyis not called for the slots of its own thread either. Outside worker mode this is how a pool that a request creates ends, unless the request lets go of it earlier. See Outside worker mode. - Another thread holds the slots. When the pool's last reference goes away on one thread, the idle slots another thread holds (another worker's, or those of a task started with
oxphp_async()) are let go there and then. Their objects stay alive until that thread's request ends, which for a worker or a task's thread is when the thread exits. Until then a connection in one stays open without counting againstmaxSize. - A fatal error hits while a pool goes away. Once
$destroyhas failed with a fatal error in the teardown of a pool whose last reference went away, no PHP code runs until the error has ended the request. The slots that teardown had not reached yet, and those of any other pool the same call lets go of, go without the callback. See Fatal errors in the destroy callback.
Each slot let go in one of these ways is counted in oxphp_shared_pool_destroy_skipped_total, when its pool was given a destroy callback. See Observability.
In worker mode, to have $destroy called at server stop for the slots a worker holds, call evict() after oxphp_worker() returns. The code after it runs on that worker once its loop has ended, for whatever reason, the server's stop included:
<?php
$pool = new Pool(factory: ..., destroy: ...);
oxphp_worker(function () use ($pool) {
// ... handle the request
});
// The loop has ended: hand the slots this worker holds to $destroy.
$pool->evict();On a pool bound to a name with Registry::pool(), the destroy callback belongs to the worker that created the pool, or to the one that last gave it new callbacks. A worker whose loop ends after that worker's script has ended (at a stop, one that was still finishing a request) lets its slots go without it, as in the second case above.
Budget & acquire semantics
Every acquire variant first tries to satisfy the request immediately, by reusing an idle slot of the calling thread or, if the pool is below maxSize, minting a new one via the factory. The variants behave differently only when the pool is saturated, with no idle slot on the calling thread and at maxSize:
| State at call time | acquire() |
tryAcquire() |
acquireTimeout($ms) |
|---|---|---|---|
| Idle slot in the local thread's queue | reused immediately | reused immediately | reused immediately |
No idle slot, but below maxSize |
factory mints a slot | factory mints a slot | factory mints a slot |
Saturated (at maxSize, none idle on this thread) |
waits forever | returns null |
waits up to $ms, then OperationTimeoutException |
Once the request that created the pool has ended, the factory is no longer called, and the second row throws ClosedException instead. See When the worker that created a pool exits.
$ms must be > 0; 0 or negative raises TypeException. There is deliberately no float-seconds form and no "infinite" sentinel argument. Use the bare acquire() for an unbounded wait.
What a wait holds
In worker mode, and in a task started with oxphp_async(), a wait on a saturated pool suspends the fiber running the request or the task, and the thread goes on running the others. When the slot being waited for is held on the same thread, its holder is among them. A suspended wait looks for a free slot again after 1 ms, then after 2 ms, then every 4 ms, so a slot given back on its thread reaches it within a few milliseconds of the thread being free to resume it. Waiters are not served in the order they arrived: the next free slot goes to whichever looks first.
Where a fiber switch is not possible, the wait holds the thread instead, as it does in a request served without worker mode. That is the case inside a fiber your code starts itself, with new Fiber or through a scheduler such as Revolt or AMPHP, and in the other places where oxphp_sleep() waits on the thread, which are listed in the warning under Suspension points. There, a slot held by anything else suspended on the same thread (another request, or another fiber of that scheduler) cannot come back while the wait lasts. Unless a slot is destroyed meanwhile and leaves room for a new one (by evict() or idle eviction on another thread, for instance), acquireTimeout() throws OperationTimeoutException once its $ms are up, and acquire() can wait until the server shuts down. Use the bounded form in such code.
A task cancelled while its wait is suspended (because the side awaiting it gave up, or the request that started it ended, for instance) is resumed, and its acquire throws OxPHP\Async\AsyncException.
Exceptions
| Exception | Raised by |
|---|---|
OperationTimeoutException |
acquireTimeout / withTimeout exceeded $ms without a free slot. Extends Async\AsyncException, not SharedException. |
TypeException |
Non-positive maxSize, negative idleTimeoutMs, $ms <= 0, or a factory that returned a non-object. |
CapacityException |
new Pool() past SHARED_MAX_ENTRIES or SHARED_MAX_BYTES. |
StaleHandleException |
Handle::get() after the handle was released. |
ClosedException |
An acquire on a closed pool, or on one that can no longer serve the call (see below). |
SharedException |
Registry::pool() or Registry::global() without worker mode (see below). |
UninitializedException |
A method call on a pool wrapper that has not finished __construct. |
Error |
An acquire whose factory cannot run on the calling thread. See Callbacks on other threads. |
Async\AsyncException |
An acquire in an oxphp_async() task that was cancelled while its wait was suspended. See What a wait holds. |
ClosedException comes from any acquire on a closed pool, and the server's shutdown closes every pool. It also comes from an acquire that has to make a new slot once the request that created the pool has ended (see When the worker that created a pool exits). Outside worker mode, any acquire on a pool a request created throws it unless that request makes it while it runs (see Outside worker mode). SharedException comes from Registry::pool() called from an HTTP request served without worker mode, and from Registry::global() there when its factory returns a pool. In a task, either of them throws it when the factory returns a pool such a request created.
tryAcquire() does not throw on saturation. It returns null. Because OperationTimeoutException extends OxPHP\Async\AsyncException (not SharedException), a catch (SharedException) will not catch an acquire timeout; use catch (OxPHP\Async\AsyncException) or catch OperationTimeoutException directly.
Both are non-blocking try* calls, but Pool returns null on contention while Mutex throws ContentionException. A pool hands back a Handle, so null is free to mean "no slot". A mutex hands back only your closure's result, which may itself be null, so contention needs an exception. Test tryAcquire for null, and wrap tryWithLock in catch (ContentionException).
Exceptions thrown inside the factory propagate to the acquire caller unchanged and do not consume budget. Exceptions inside the with() / withTimeout() body propagate to the caller after the slot is released. A fatal error inside the body ends the request, and the slot goes back to the pool all the same, in whatever state the body left it. That is the same as after a throw, except that no finally block in the body has run. If a body can be ended halfway through an exchange (a reply not yet read, a transaction still open), start each body by putting the resource back into a known state.
Observability
See Shared Observability for the full reference. The pool-specific parts:
GET /__ox_shared/entry?id=Nexposestype: "Pool"and, undertype_specific,{ count, in_use, idle, waiting, max_size, idle_by_thread, rebalance_strategy }.GET /__ox_shared/summaryincludes aPoolbucket withcount,bytes, andops. Per-pool gauges likewaitingand theevicted_totalcounter are exposed on/metrics(below), not aggregated in the summary.- Prometheus metrics per pool:
oxphp_shared_pool_count{pool_id="…"}: gauge, total slots (in-use + idle).oxphp_shared_pool_in_use{pool_id="…"}: gauge.oxphp_shared_pool_idle{pool_id="…"}: gauge.oxphp_shared_pool_waiting{pool_id="…"}: gauge, queued acquires.oxphp_shared_pool_acquire_total{pool_id="…",result="ok|timeout|closed|saturated"}: counter.saturatedcounts non-blockingtryAcquirecalls that found the pool full (distinct fromtimeout, which means a wait elapsed).oxphp_shared_pool_evicted_total{pool_id="…",reason="idle_timeout|evict|shutdown"}: counter.oxphp_shared_pool_wait_seconds_*{pool_id="…"}: acquire-wait histogram (bucket / sum / count).
- Prometheus metric for all pools together:
oxphp_shared_pool_destroy_skipped_total{reason="no_frame|other_thread|request_ended"}, a counter of the slots let go without the destroy callback their pool was given, in the cases listed under When the destroy callback is skipped.
Alert-worthy combinations: rising waiting with flat count means the pool is saturated and should be resized; rising acquire_total{result="timeout"} with normal in_use means the factory is slow (or blocking); rising acquire_total{result="saturated"} means callers keep hitting tryAcquire on a full pool (backpressure firing).
When not to use
- Cheap or immutable resources do not need one. A pool's overhead is larger than re-creating a simple object, so use it for resources where creation costs milliseconds or kilobytes.
- Some objects cannot be reused safely. If the resource accumulates per-request state (open transactions, pending reads) and you cannot reliably reset it, pooling leaks state between requests. Return slots to a known state in your request-finishing code, or do not pool.
- A pool is in-process, so it does not cover cross-host resources. For multi-host connection pooling, prefer a connection-bucket service or a sidecar (pgbouncer, proxy-sql).
- Unbounded fan-out is a different problem. If you need one connection per in-flight HTTP call, you have an N-per-request problem, which a pool does not solve. Use a
Shared\Channelto serialise work behind a bounded pool instead. - Many client libraries already pool internally (e.g. Guzzle's connection pool). Stacking a
Shared\Poolon top of a resource with its own pool semantics is double bookkeeping, so prefer the library's own pooling.
Prompts for your agent
These prompts assume an agent with the OxPHP documentation MCP server connected. The agent reads the pages it needs itself.
Use an OxPHP Shared Pool in my code instead of constructing a database connection, HTTP client, or parser fresh on every request. Read the `shared-state/shared-pool` page through the OxPHP documentation MCP server.
Find that per-request construction in this repository and show me the Pool plus `with()` replacement, sized against the worker count this deployment actually runs.
If this deployment does not run in worker mode, a pool closes with each request, so say so and, for database connections, use the driver's persistent connections instead.My OxPHP pool is saturated and requests are timing out on acquire. Read the `shared-state/shared-pool` page through the OxPHP documentation MCP server.
Pull this pool's `/__ox_shared/entry` and `/metrics` from my running deployment and tell me, from `waiting`, `idle_by_thread`, and the acquire-result counters, whether I need a bigger `maxSize` or the factory itself is slow.Related
- Shared State: overview and mental model.
- Shared\Once: for when you need exactly one resource (not a pool of N).
- Shared\Channel: pair it with a pool for producer/consumer pipelines.
- Shared\Map: one
Poolper tenant, keyed by name. - Worker Mode: pool handles across requests within one worker thread.