Worker Mode
Worker mode runs persistent PHP workers that bootstrap once and then handle many requests, so the cost of starting PHP is paid a single time instead of on every request. Your application loads its autoloader, configuration and database connections once and reuses them for the lifetime of the worker.
How it works
- Enable worker mode. Set
WORKER_MODE_ENABLED=trueand pointENTRY_FILEat your bootstrap script. This enables worker mode for all PHP workers in the pool. - Bootstrap once. PHP runs the script's outer scope one time: autoloader registration, configuration loading, database connections and any other initialization.
- Enter the request loop. Call
oxphp_worker(callback). OxPHP begins dispatching incoming HTTP requests to your callback. - Reset between requests. Superglobals,
php://input, output buffers, response headers, the session a request opened, the ini directives it changed and the environment variables it set withputenv()are reset automatically (see Worker State Between Requests).$_ENVis a deliberate exception: with PHP's defaultauto_globals_jit=1it is not reset (see Superglobals). - Outer scope persists. Variables defined before
oxphp_worker(), static properties, database connections and autoloaders stay available to every request the worker handles.
A worker also carries several requests at once. With fiber multiplexing it switches to another request whenever the one it is running waits at a suspension point, so state a request leaves in a static or global can be read by a request that overlaps it.
Worker mode changes routing behavior. All requests that do not match a static file on disk are dispatched to the worker instead of returning 404. See Routing for details.
Configuration
| Variable | Default | Description |
|---|---|---|
WORKER_MODE_ENABLED |
false |
Enable persistent worker mode. Accepts true, 1, yes. Requires ENTRY_FILE to point at a .php script |
ENTRY_FILE |
(unset) | Path to the worker bootstrap script. A relative path resolves against DOCUMENT_ROOT; .. segments and absolute paths are allowed |
WORKER_MAX_MEMORY_MIB |
0 |
PHP memory per worker, in MiB, above which the worker is recycled. 0 = unlimited |
A bootstrap living outside the public document root is a supported layout. A worker that serves no static files can run with DOCUMENT_ROOT=false and an absolute ENTRY_FILE (see No Document Root).
For application-driven recycling, call OxPHP\Server\Worker::scheduleExit() from inside a request handler. The worker exits cleanly after the current request completes.
To make blocking calls such as sleep(), socket reads and cURL transfers suspend the request instead of holding the worker, see Runtime Hooks.
Writing a worker script
A worker script has two parts: the outer scope that runs once at startup, and the callback passed to oxphp_worker() that runs on every request.
<?php
// Outer scope: runs once at startup
require __DIR__ . '/../vendor/autoload.php';
$config = parse_ini_file(__DIR__ . '/../config/app.ini');
$db = new PDO($config['dsn'], $config['user'], $config['pass'], [
PDO::ATTR_PERSISTENT => true,
]);
$app = new MyApp\Application($config, $db);
// Request loop: runs for every request
oxphp_worker(function () use ($app) {
$app->handle();
});
// Teardown: runs when this worker's loop ends, which is not
// only at server shutdown (see Worker Recycling)
$app->terminate();Build shared services in the outer scope, and per-request objects inside the callback. A Request from oxphp_http_request() belongs to the request it was created in: kept past its handler and called while the worker serves a later request, it throws OxPHP\Http\Exception\NoActiveRequestException. See Request API → Worker Mode.
What resets and what persists
OxPHP performs a soft reset between requests. Per-request state is cleaned automatically, while anything bootstrapped in the outer scope survives for the life of the worker.
- Superglobals and
php://input - Output buffers, the status code and response headers
- The last error and the connection status
- The session the request opened
- Ini directives the request changed
- Environment variables the request set with
putenv()
- Outer-scope variables captured with
use - Static properties
- Persistent database connections
- Autoloaders and loaded classes and functions
- Ini directives and environment variables set during bootstrap
$_ENV, error handlers and exception handlers
The reset has limits. Some of that state stays with the worker while other requests on it are in flight, and a few settings are not put back. Worker State Between Requests lists each item with its boundaries, including sessions, ini rollback and putenv().
Recycling
A worker is recycled when its memory passes WORKER_MAX_MEMORY_MIB, when the handler calls Worker::scheduleExit(), on an OPcache restart, after three consecutive requests that came apart, and in a few cases where a request that ended abnormally leaves the worker unfit to keep serving. Its loop ends, its PHP state is torn down, and the pool decides whether a fresh worker takes its place. Other requests in flight on it are answered 503 with a Retry-After.
Worker Recycling lists the conditions, which failures count, and the log lines and metrics each recycle leaves.
Request deadlines
Every request a worker serves is bounded by its own max_execution_time, whether the worker took it alone or while carrying others. With fiber multiplexing a worker runs several requests on one thread, and each still gets the whole of its limit and no more:
- A request's limit counts from the moment the worker takes it. It starts at the
max_execution_timethe worker's bootstrap left (thephp.inivalue, or whatever the worker script's outer scope set). It counts wall-clock time, time spent suspended included (see Timeouts). set_time_limit()applies to the request that calls it. It restarts that request's limit from the call, as under PHP-FPM, and leaves every other request on the worker as it was. The directive the call writes stays with the worker (see Ini rollback).- When a limit runs out, it ends the request it belongs to. That request gets a
504, the timeout bit in its ownconnection_status()for its shutdown functions, and is neutral for the recycle count. The requests running beside it carry on. - A suspended request is ended when it resumes, not when its deadline passes. A request waiting in
oxphp_async_await(),oxphp_sleep()/oxphp_usleep(), or a wait thatRUNTIME_HOOKStook over runs no PHP code, and a time limit can only end code that runs. Once the call it waited in returns, the request ends there as at any other timeout, its shutdown functions included. - What a worker runs between requests is under no limit. The destructors run by the worker's periodic garbage collection are outside any request.
A suspended request resumes when what it waits for arrives (the promise settles, the sleep elapses, the socket becomes readable, writable or connected), when the wait reaches its timeout, or when the server cancels it. For a read or a write that timeout is the stream's own (default_socket_timeout unless stream_set_timeout() set another); for a connect it is the timeout passed to stream_socket_client() or fsockopen().
A call that waits once (a sleep, a single read) returns when it is resumed. One that waits again and again inside, such as stream_get_contents() reading a stream to its end, returns only when it is done as a whole. Two waits are exceptions:
session_start()waiting for another request's session to close (see Worker State) is resumed every quarter of a second. It returns without opening the session the first time it is resumed out of time.- A streaming response's flush that waits for its client to make room (see Server-Sent Events) is resumed whenever the client takes a chunk, and otherwise at least every 16 milliseconds. It returns the first time it is resumed out of time, having sent its data only if the client made room by then.
A server shutdown that passes its drain deadline, and a recycle of the worker, cancel every request suspended at that moment. One whose limit had already passed is ended by that cancellation like the others: a 503, with its shutdown functions run and not cut short by the spent limit.
Nothing else ends a suspended request for you. A client disconnecting does not end a non-streaming request, which runs to its end by design, and a request running past the supervisor's threshold is reported through oxphp_worker_stuck_total, not cancelled.
Put the limit on the wait itself: pass a timeout to oxphp_async_await() and its variants, and set timeouts on sockets and database clients.
Development reloading
Worker mode keeps bootstrap state (autoloader, DI container, DB connections) in memory, so opcache.validate_timestamps=1 alone does not pick up changes to code that ran in the outer scope. For development loops there are two options:
- Recycle every request. Call
OxPHP\Server\Worker::current()->scheduleExit()at the end of every handler invocation (gated on anOXPHP_DEVenv flag, for example). The current request completes normally, then the worker exits and a replacement runs the outer scope again, at once on a static pool, which is what a development setup normally runs. You trade the worker-mode speedup for FPM-style reloads, and it is the simplest and most reliable approach for active development. - Keep the worker warm, reload request handlers. Skip
scheduleExit(), enableopcache.validate_timestamps=1, and keep your bootstrap minimal. OPcache refreshes code loaded inside the request callback on the next request; code loaded once in the outer scope stays as it was. See OPcache and JIT → Development settings for the full list of caveats.
Troubleshooting
Requests hang and never complete
If oxphp_worker() is never called in the bootstrap script, no requests are dispatched and every request waits indefinitely. Verify that your script calls oxphp_worker() unconditionally in the normal code path.
State leaks between requests
Variables defined inside the oxphp_worker() callback are cleaned up by PHP's garbage collector, but static properties and globals defined in the outer scope persist. If you see data from one request appearing in another, check for static properties or global variables that accumulate state across calls.
Fix: Reset static state explicitly at the start of each request callback, or avoid storing per-request state in statics. Worker State Between Requests lists what the worker resets for you.
500s on a fresh worker with RUNTIME_HOOKS
Symptom: Requests fail with an application error soon after a worker starts or recycles, and only with RUNTIME_HOOKS on. Yii3 reports CircularReferenceException: Circular reference to "Yiisoft\Router\Middleware\Router" detected while building.
Cause: One request is building a shared service, the build waits on a hooked socket, and a second request reaches the half-built service. A worker runs its first request alone until it ends or 250 ms after it first waits, so this takes a build still running after that, or one that happens in a later request.
Fix: Build the service in the worker script before oxphp_worker(). On Yii3 this line cures this exception: $container->get(\Yiisoft\Router\Middleware\Router::class);. If the errors instead say that per-request state is already set, or it disappears halfway through a request, the state lives in a shared service and building it ahead does not help: run without RUNTIME_HOOKS. Yii3's CurrentRoute is such a service, so this applies to any Yii3 handler that waits on a hooked socket.
Worker recycles immediately (memory limit)
The worker memory limit is checked after each request using PHP's reported memory usage. If your bootstrap allocates a lot of memory (a large cache, say), the initial footprint may already be close to the limit.
Fix: Increase WORKER_MAX_MEMORY_MIB, or defer large allocations to the first request. With RUNTIME_HOOKS on, read the entry on 500s on a fresh worker above before moving anything that waits on I/O there.
Check: At LOG_LEVEL=info, each such recycle logs the usage that passed the limit as memory_bytes, next to the limit as max_memory_bytes. Every earlier check found the usage within the limit, so the difference between the two is at most what the worker grew by since the last check: a small one fits gradual growth, a large one a single jump. On a worker that recycles after its first request, that jump includes everything the bootstrap allocated.
docker logs <container> 2>&1 | grep '"reason":"max_memory"'Worker recycles immediately (error limit)
Three consecutive counted failures trigger a recycle. A fatal error in the request callback is the usual one, so check your application logs for those first. Uncaught exceptions do not count, and cancelled requests count only if a fatal was reported on the cancelled request as well.
A recycle with no fatal behind it is one of the two fiber failures, and the WARN line names which. fiber would not start points at fiber.stack_size or at the host: that C stack is mapped from the operating system, not PHP's heap, so neither memory_limit nor WORKER_MAX_MEMORY_MIB is the knob for it. fiber refused to park points at a Fiber::suspend() your own code keeps retrying.
The server logs one WARN line per counted failure, naming the worker, where the failure came from and how many have run consecutively, and one more for the recycle that follows the third. The count is per worker: three lines from one worker are a recycle, three lines from three workers are not.
Check: Look for errors and warnings in the structured log output:
docker logs <container> 2>&1 | grep -E '"level":"(ERROR|WARN)"'Leaks or skipped destructors under Xdebug
Xdebug's develop mode takes over PHP's error reporting from the first request on and does not pass errors on, so the worker's own handling of an error never runs. It is the default when xdebug.mode is not set, and applies whenever develop is one of the modes listed. On a worker serving such requests:
- a request ended by a fatal error leaves what its abandoned frames held allocated for the life of the worker;
- after a request exceeds
memory_limit, the worker neither hands that memory back and restores the limit nor recycles for it (see Worker Recycling); - after a fatal error, the objects the worker keeps and those of the other requests in flight lose their destructors, as PHP does after a fatal (see Objects after a fatal error).
debug mode passes errors on, so none of this happens under it. Like develop, though, it keeps the server's own error callback out: errors are not logged with the server's structured fields, running out of max_execution_time is answered like any other fatal error instead of with 504, and the status of a fatal error is left to PHP, which answers 500 only with display_errors off. profile, trace and off leave error handling alone.
Fix: Keep develop for development.
Database connection drops after idle
If your database server closes idle connections, reconnect attempts in the next request may fail. Use a connection pool that handles reconnection, or catch the exception and reconnect manually.
Docker example
services:
app:
image: ghcr.io/oxphp/oxphp:0.16.0
ports:
- "8080:80"
volumes:
- ./src:/var/www/html
environment:
- DOCUMENT_ROOT=/var/www/html/public
- WORKER_MODE_ENABLED=true
- ENTRY_FILE=/var/www/html/worker.php
- WORKER_MAX_MEMORY_MIB=128PHP API
Worker introspection and the worker entry point are exposed through the OxPHP\Server\Worker class.
<?php
$worker = OxPHP\Server\Worker::current();
$worker->serve(function () {
handleRequest();
});The legacy free functions (oxphp_is_worker, oxphp_worker_id, oxphp_worker) remain available and route through the same internal state. New code should prefer the class API.
The class also exposes runtime introspection for self-recycling, observability and health checks:
| Method | Returns |
|---|---|
Worker::isWorkerMode(): bool |
Whether the server is running in worker mode |
$worker->id(): int |
Stable per-thread worker ID |
$worker->startTime(): float |
Unix timestamp of when this worker started |
$worker->requestCount(): int |
Number of requests this worker has handled |
$worker->memoryUsage(): int |
Current memory_get_usage() for this worker, the figure WORKER_MAX_MEMORY_MIB is compared with |
$worker->rss(): int |
Current resident set size in bytes (Linux/macOS) |
$worker->maxMemoryBytes(): int |
Recycle threshold: WORKER_MAX_MEMORY_MIB × 1 MiB, or 0 when unlimited |
$worker->isExitScheduled(): bool |
Whether an exit with reason "scheduled" is pending: scheduleExit() was called, or the worker retired itself |
$worker->exitReason(): ?string |
null while running; "scheduled", "max_memory", or "error" once the worker is going down |
See OxPHP\Server\Worker for full signatures and worked examples.
PHP examples
Detecting worker mode
Use OxPHP\Server\Worker::isWorkerMode() to check whether the current process is running in worker mode. This is useful for code that works in both traditional and worker mode.
<?php
if (OxPHP\Server\Worker::isWorkerMode()) {
// Reuse a persistent connection
$redis = new Redis();
$redis->pconnect('redis', 6379);
} else {
// Traditional mode: connect per request
$redis = new Redis();
$redis->connect('redis', 6379);
}Symfony worker script
<?php
use App\Kernel;
require __DIR__ . '/../vendor/autoload.php';
$kernel = new Kernel('prod', false);
$kernel->boot();
oxphp_worker(function () use ($kernel) {
$request = Symfony\Component\HttpFoundation\Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
});
$kernel->shutdown();Best practices
- Set
WORKER_MAX_MEMORY_MIB(e.g.128) so a leaking worker recycles automatically instead of consuming the host, and addWorker::scheduleExit()for application-driven recycling on top. A worker can grow even when the application leaks nothing: a fatal error or a cancellation that ends a request inside an internal function (ausort()sorting a copy of the array, say) keeps what that function allocated, and one that ends a request inside aFiberit runs (its own, or the one PHP runs garbage-collection destructors in) keeps what that fiber's frames held, for the life of the worker. Worker Recycling covers when that growth recycles the worker. - Close the session before a suspension point. While a request is paused with its session open, its worker takes no new request and
session_start()in its other requests waits. See Sessions. - Avoid storing per-request state in static properties or globals. They persist across requests, so leftover state from one request can leak into another.
- Validate the soft reset early. Add
Worker::current()->scheduleExit()to your handler under a development flag and exercise the application end to end. This catches state leaks before you commit to long-lived workers. - Handle database idle timeouts. If your database driver disconnects after an idle period, catch the exception and reconnect, or use a connection pool that reconnects automatically.
- Keep the outer scope minimal. Only bootstrap what truly needs to persist: autoloaders, configuration and shared services. Defer request-specific setup to the callback. With
RUNTIME_HOOKSon, build shared services there rather than lazily in a request, since a request can overlap the build (see the troubleshooting entry on 500s on a fresh worker).
Prompts for your agent
These prompts assume an agent with the OxPHP documentation MCP server connected. The agent reads the pages it needs itself.
Move my application to OxPHP worker mode. Read the `features/worker-mode` and `features/worker-state` pages through the OxPHP documentation MCP server.
Write the worker script for this repository: what to build once before `oxphp_worker()`, what the handler does per request, and the teardown after the loop. Then list the code that is not safe in a persistent worker (state kept between requests, a `Request` object kept past its handler, a session left open across a suspension point) with the change each one needs.See also
- Worker State Between Requests: what is reset after each request, what persists, and where the reset stops
- Worker Recycling: when a worker is recycled and what happens to its other requests
- Routing: how worker mode plugs into URL routing
- Early Response: send the response immediately and continue background processing
- PHP Functions: full reference for
oxphp_worker(),oxphp_is_worker(), and other built-in functions - Configuration Reference: complete list of environment variables