Worker Recycling
A worker-mode worker is recycled when its memory, a run of failed requests or the application says so. Its loop ends, its PHP state is torn down, and the pool decides whether a fresh worker takes its place. This page lists the conditions, which failed requests count toward the error limit, and what recycling does to the other requests the worker was serving.
Recycling
A worker is recycled when any of these happens:
- Its memory passes the limit. The worker's PHP memory usage exceeds
WORKER_MAX_MEMORY_MIBMiB. - The application asks for it. The handler calls
Worker::scheduleExit(), for app-controlled hot reload, file-mtime-based reload, or running the bootstrap again on demand. - Requests keep coming apart. The worker took 3 consecutive requests that ended in a fatal error, an out-of-memory, or one of two failures around the fiber the request runs in. Three in a row say the worker is at fault rather than any one request, so it is replaced instead of patched up again. Which failed requests count lists what does and does not count.
- A destructor fails during the periodic garbage collection. The worker runs PHP's cycle collector periodically between requests. A fatal error in a destructor that collection runs recycles the worker the way a scheduled exit does: the requests it was serving get
503withRetry-After, the code afteroxphp_worker()runs, and the recycle counts underoxphp_worker_recycles_by_reason_total{reason="scheduled"}. - OPcache restarts. A worker that holds a restart OPcache has scheduled (one that booted with the cache, for instance) is recycled at its next moment with no request in flight. A worker that booted while the restart waited runs without the cache, and is recycled at such a moment once the restart has run, or once nothing else holds it. Under steady load a worker stops taking new requests for at most 5 seconds to reach that moment, in turn with the other workers; see OPcache restarts.
- A request ended inside an internal function left a lot behind. A fatal error or a cancellation (
max_execution_timeelapsing, say) that ends a request inside an internal function leaves behind what that function allocated for itself, and the worker cannot give it back.usort(), for example, sorts a copy of the array, and the copy keeps every element alive. See Memory left behind by an internal function. - An out-of-memory error left more than
memory_limitin use. PHP builds theAllowed memory size … exhaustedreport with the limit set aside, and on PHP 8.5.0 to 8.5.11 the report carries a backtrace of every frame on the stack (fatal_error_backtraces, on by default; from 8.5.12 this error's backtrace stops at its first frame). After a runaway recursion that backtrace can outgrow the limit: a recursion 400,000 calls deep undermemory_limit=128Mleft about 290 MiB in use. See Memory left in use after an out-of-memory error. - A request ended inside a cURL transfer. Ending a request from inside a transfer's callback leaves the cURL handle unusable. See A request ended inside a cURL transfer.
The last four are recycles the worker schedules for itself at its next moment with no request in flight, so none of them ends a request. They are counted under oxphp_worker_recycles_by_reason_total{reason="scheduled"}, as the garbage-collection recycle is, and none of them happens while the server is shutting down.
Which failed requests count
Not every failed request counts, because not every failure says the worker is unfit to serve:
| Outcome | Effect on the count |
|---|---|
Fatal error or out-of-memory, raised in the request handler, in a shutdown function, or in a destructor that runs as the request lets go of its shutdown functions, of what it left in a superglobal, or of the closure of an oxphp_async() task it never awaited and that had not started |
Counts |
| The fiber the request runs in would not start: the engine could not allocate its C stack, so the handler never ran | Counts |
| The request would not stop suspending that fiber from userland, and the server ended it | Counts |
Uncaught exception (answered 500) from the request handler or from a shutdown function |
Neutral |
Cancelled request: max_execution_time elapsed, the server is shutting down, or the client of a streaming response that has not called ignore_user_abort(true) hung up |
Neutral |
Request completed, exit()/die() included |
Clears the count |
"Neutral" means exactly that: one in the middle of a run of fatals neither adds to the count nor clears it, so fatal, exception, fatal, fatal still recycles the worker. A failure in a shutdown function is read like one in the request handler: a fatal there counts, an exception there is neutral.
Running out of C stack ends a request with Maximum call stack size … reached, an Error the engine throws, so it is neutral unless caught. A PHP function that calls itself directly does not use up the C stack; it runs into memory_limit instead, and that out-of-memory counts. Under an extension that wraps every call, such as Xdebug in any mode but off, it does use up the stack and ends in a neutral uncaught Error. The stack running out while PHP compiles a file is a fatal error and counts.
The count asks whether this worker is at fault, so it looks at why a request ended rather than at what it left behind. A request the server cut short is no evidence against the worker: a cancellation is neutral whether it lands in the handler or in a shutdown function, provided the request had not already hit a fatal. A deadline that expires in a shutdown function after the handler came apart leaves that failure counted. Shutting the server down is the one cancellation that is neutral unconditionally.
Outside a streaming response, a client hanging up does not end a worker-mode request. The request is free to finish and run its own cleanup, and is then read by how it ended: reaching its end clears the count, a fatal counts, an uncaught exception is neutral. A departing client therefore cannot keep alive a worker that fatals on every request.
The two fiber rows count for the reason a fatal does: the request did not reach the end of its own work, and the server did not cut it short. A fiber does not start when the engine cannot allocate its C stack (fiber.stack_size set below the platform minimum of two memory pages, or the process unable to map more memory). The other row is the application's own doing: the server drives the request's fiber, so a userland Fiber::suspend() on it is refused with a FiberError, and a handler that catches that and retries in a loop is ended. That ending cannot be caught, but it still runs the request's finally blocks, destructors and shutdown functions, and sends what the request produced under the status the handler set. The WARN line for a counted failure names which of the two it was: fiber would not start or fiber refused to park.
A wedged worker is a different matter. A request stuck in a syscall is reported through oxphp_worker_stuck_total for an operator to act on, and nothing in the server cancels, counts or recycles it, so the worker stays wedged until the call returns or the process restarts. max_execution_time is no backstop either, because a time limit ends a request only where PHP code runs (see Request deadlines).
Memory left behind by an internal function
The worker compares its memory usage between two moments when no request is in flight. If a request was ended with an internal function's call on its stack in between, and the usage grew by more than 4 MiB, the worker is recycled, with a warning in the log that names the reason. A request ended just as an internal function such as curl_exec() returned counts too, because a time limit is noticed while that call is still on the stack. The check does not depend on WORKER_MAX_MEMORY_MIB.
The stacks of fibers the worker created in that time are not counted, since it keeps them for as long as it lives. Garbage that only the cycle collector can free is collected first and not counted, including cycles let go of with the ended request's variables. With zend.enable_gc=0 in php.ini there is no collector to run, and such garbage counts. What decides is the growth, not the call, so anything else that grew the worker's memory in the same stretch counts too: a cache filled for the first time, a large request body not yet released.
The check does not catch:
- a leak under about 4 MiB, which adds up until
WORKER_MAX_MEMORY_MIBis passed or, without it, until requests start failing againstmemory_limit; - a leak in the first stretch in which a worker is busy, since what a fresh worker builds in its first requests would otherwise recycle every replacement in turn;
- anything while the server is shutting down;
- a worker that is never without a request in flight, where the check waits for the first such moment.
Memory left in use after an out-of-memory error
Up to PHP 8.4.26 / 8.5.11, while the allocator counts more than the limit as in use, it refuses nothing, for any request on the worker. PHP-FPM gets that memory back by shutting the request down. A worker hands it back and puts the limit back in force as the failing request ends, after its shutdown functions. Until then, a request the worker serves while the failing one is suspended (in oxphp_async_await(), oxphp_sleep()/oxphp_usleep(), or a sleep(), usleep() or socket wait taken over by RUNTIME_HOOKS) runs with no limit either.
Where the worker still holds more than the limit after that (a shutdown function of that request kept that much, say), it is recycled at its next moment with no request in flight, with a warning in the log that names the reason. The requests it serves until then run without memory_limit in force, as a rule with no limit at all.
From PHP 8.4.27 / 8.5.12 the allocation that takes a request past memory_limit is granted, and the error is reported just after it. A request can therefore also leave more than the limit behind in what outlives it (the worker's shared state, or a static variable it was filling), and the worker is recycled for that the same way. On those releases, while more than the limit is in use, a request that needs memory the worker does not already hold fails with Allowed memory size … exhausted instead of running with no limit.
Those releases also have a hard limit: memory_hard_limit_percent of memory_limit, by default twice the limit, or the limit plus 1 GiB for a limit above 1 GiB. An allocation past it ends the whole server process with exit code 137 and a Hard memory limit of … bytes exhausted line on stderr (see Memory limits for the setting that moves it). A worker that already holds more than memory_limit is that much closer to it.
Unlike the internal-function check, this recycle applies from a worker's first request. A thread of the async pool hands the memory back as the failing task ends and, where that is not enough, tries again as each later task ends; it is not recycled. fatal_error_backtraces=0 leaves the backtrace out, and with it most of what the report takes.
A request ended inside a cURL transfer
A request can be ended inside one of a transfer's callbacks (CURLOPT_WRITEFUNCTION, CURLOPT_HEADERFUNCTION, CURLOPT_READFUNCTION, CURLOPT_XFERINFOFUNCTION and the rest) while curl_exec(), curl_multi_exec(), curl_pause(), curl_multi_remove_handle() or curl_multi_close() is running. The last two call the progress callback once more when they end a transfer that has connected but not finished. A fatal error, the request's time limit, or output written to a departed client of a streaming response can end it there, and that leaves the transfer's handle unusable:
curl_reset()andcurl_close()throwAttempt to reset cURL handle from a callback(orclose);- libcurl fails every later transfer on the handle, and every later
curl_multi_exec()on its multi handle, withAPI function called from within callback.
That matters to a handle that outlives the request, such as an HTTP client built once at boot and kept in the worker's state. The worker cannot tell whether one did, so it is recycled whenever this happens, with a warning in the log that names the reason. This applies from a worker's first request.
A time limit noticed only after curl_exec() has returned does not count. Nor does a callback libcurl runs outside those calls, as a handle is destroyed, or a CURLOPT_DEBUGFUNCTION that curl_setopt() calls with CURLOPT_VERBOSE on. The request itself is answered and counted as its ending says, like any other fatal error or time limit, and a thread of the async pool is not recycled for this.
What happens when a worker is recycled
The worker's loop ends and its replacement runs the outer scope of the worker script again. Workers are OS threads of the single OxPHP process, so nothing the operating system sees restarts, and getmypid() returns the same value in every worker, before and after. Whether a replacement arrives at once depends on the pool:
- a static pool (
PHP_WORKERS=N) refills toNon its next scan, so the replacement is one-for-one; - a dynamic pool (
PHP_WORKERS=MIN:MAX) refills only toMIN, so a worker recycled above the minimum leaves the pool one smaller until ordinary scale-up grows it again.
For memory-based and scheduled exits, the current request completes normally before the worker exits. For error-based recycling, the worker exits after the failed request.
Other requests the worker was serving at the same time (suspended in oxphp_async_await(), oxphp_sleep()/oxphp_usleep(), or a sleep(), usleep() or socket wait taken over by RUNTIME_HOOKS) do not get to finish. Each is cancelled where it is suspended and answered 503 Service Unavailable with a Retry-After, after running its own shutdown functions. Clients whose requests happen to be in flight therefore see the recycle, which matters when you choose WORKER_MAX_MEMORY_MIB or call scheduleExit() on a worker that serves concurrent requests. A full server shutdown is different: there, in-flight requests get the drain window to finish.
A memory-based or scheduled recycle is logged at INFO as Worker mode thread recycled, with reason set to the label oxphp_worker_recycles_by_reason_total counts it under:
max_memory, together withmemory_bytes(the usage that passed the limit) andmax_memory_bytes(the limit);scheduled, which coversWorker::scheduleExit()and the recycles the worker schedules for itself.
The pool follows with Recycled workers detected. A worker recycled after consecutive errors is logged at WARN as Worker mode thread retired after consecutive request failures, and the pool reports it, like any worker thread that ends without choosing to, as Dead workers detected, respawning.
So at LOG_LEVEL=warn a recycle on WORKER_MAX_MEMORY_MIB or on Worker::scheduleExit() leaves no line of its own. A worker that recycles on memory often is a leak worth chasing, and the rate of oxphp_worker_recycles_by_reason_total{reason="max_memory"} is where that shows.
A dynamic pool retiring an idle worker (see Dynamic pool) also ends that worker's loop and runs the code after oxphp_worker(), but nothing is spawned in its place. Neither oxphp_worker_recycles_total nor oxphp_worker_recycles_by_reason_total moves, and oxphp_workers_retired_total counts it instead. Teardown placed after oxphp_worker() therefore also runs on a healthy, serving pool (see oxphp_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.
Set up worker recycling for my OxPHP deployment. Read the `features/worker-recycling` and `operations/metrics` pages through the OxPHP documentation MCP server.
Estimate how much memory my worker bootstrap and my heaviest requests hold, then pick a `WORKER_MAX_MEMORY_MIB`, tell me whether my code should call `Worker::scheduleExit()` anywhere, and give me alert rules on `oxphp_worker_recycles_by_reason_total` that tell a slow leak apart from a worker that keeps crashing.See also
- Worker Mode: how workers boot, serve requests and are configured
- Worker State Between Requests: what a worker resets after each request and what it keeps
- Worker Class: recycling a worker on demand with
scheduleExit() - Metrics:
oxphp_worker_recycles_totaland the per-worker gauges