Skip to content

Request Lifecycle

When you write PHP for PHP-FPM, you can rely on one comfortable fact: every request starts from nothing. In PAM, your application boots once and then serves thousands or millions of requests from the same process. That is where the speed comes from, and it is also the one thing you must keep in mind while writing code.

This page walks through the life of a worker and of a single request, so you know exactly which state PAM resets for you and which state is yours to manage.

A worker goes through four states. The master reads them to decide when a worker can receive traffic and when it can be stopped:

Code State Meaning
1 Starting The engine is booting and your entrypoint is running
2 Ready Listening and idle
3 Busy At least one request is running
4 Draining Finishing in-flight requests; accepts no new work
boot entrypoint ──► Ready ⇄ Busy ──► Draining ──► exit
▲ │
└── replacement ◄────┘ (master starts a new worker)

You can see these codes in the state field of the master’s /ready endpoint:

Terminal window
pam start index.php --workers 2 --admin-address 127.0.0.1:3010
curl -s http://127.0.0.1:3010/ready
{"schemaVersion":1,"surfaceCode":1,"resultCode":1,"healthy":true,"generation":1,"desiredWorkers":2,"readyWorkers":2,"workers":[{"id":2,"generation":1,"pid":1026730,"pool":null,"state":2},{"id":1,"generation":1,"pid":1026911,"pool":null,"state":2}]}

Everything your entrypoint does before the handler is registered runs once per worker: loading Composer, reading configuration, building the router and the container, compiling templates or schemas.

index.php
<?php
declare(strict_types=1);
use Pam\Http\Request;
use Pam\Http\Response;
use Pam\Http\Server;
// Boot phase: runs once per worker.
$config = require __DIR__ . '/config.php';
$routes = require __DIR__ . '/routes.php';
// Request phase: runs for every request.
Server::create(static function (Request $request, Response $response) use ($routes): Response {
$handler = $routes[$request->path] ?? null;
return $handler === null
? $response->json(['error' => 'Not Found'], 404)
: $handler($request, $response);
})->listen((int) (getenv('PAM_PORT') ?: 3000));

With Nimbus, bootstrap/app.php builds the Nimbus\App once and index.php calls $app->listen(); the same rule applies.

For every request, PAM runs these steps:

  1. Transport. The HTTP/1.1, HTTP/2 or HTTP/3 transport validates the request against its limits (headers, body size, timeouts) and reads the body. Multipart uploads are streamed to temporary files using PHP’s own upload settings.
  2. Admission. The request takes a slot from maxConcurrentRequests and, when it has a body, a share of the maxInflightBodyBytes budget.
  3. A new Fiber. PAM creates a root Fiber for the request and opens its RequestScope.
  4. Superglobals. $_GET, $_POST, $_COOKIE, $_FILES, $_REQUEST, $_SERVER and php://input are populated for this request, and the session ID is taken from the cookie.
  5. Your handler runs. Middleware and the handler run until they return a response or suspend on an async operation. While suspended, other requests can run on the same worker.
  6. Response. The response is serialized and handed back to Rust, which validates the status and headers again before writing it. Streamed responses advance only when the client accepts each chunk.
  7. Cleanup. PAM runs the scope’s cleanup callbacks, discards output buffers, closes the session, clears the superglobals, cancels pending futures, clears the Fiber context and deletes temporary uploads.
  8. Housekeeping. Every 256 requests PAM runs gc_collect_cycles(), and every 1,024 requests it calls gc_mem_caches() to return memory from PHP’s allocator.

You can tune step 8 with the gcCollectCyclesEvery and gcMemCachesEvery listen options (0 disables each one).

After every request, whether it succeeded, threw an exception, timed out or was cancelled because the client disconnected:

Reset by PAM Details
Superglobals $_GET, $_POST, $_COOKIE, $_FILES, $_REQUEST, $_SERVER and $_SESSION are emptied
Response state The SAPI header list and response code are reset before the next request
Output buffers Any buffer your code left open is discarded
Sessions An active session is written and closed; the session ID is cleared
Uploads Temporary upload files are deleted
Request scope RequestScope cleanups run in reverse order, then its values are dropped
Fiber context FiberContext values of the request are cleared
Pending futures Futures started by the request and never awaited are cancelled

Anything stored outside those mechanisms lives as long as the worker:

  • static properties and static variables inside functions;
  • global variables ($GLOBALS) and constants;
  • objects captured by your handler closure, and container singletons;
  • open connections, file handles and sockets you keep in those places;
  • loaded classes and OPcache-compiled code.

Here is the effect in practice. The counter keeps growing because the static property lives in the worker, not in the request:

server.php
<?php
declare(strict_types=1);
use Pam\Http\Request;
use Pam\Http\Response;
use Pam\Http\Server;
final class Counter
{
public static int $hits = 0;
}
Server::create(static function (Request $request, Response $response): Response {
Counter::$hits++;
return $response->json(['hits' => Counter::$hits, 'pid' => getmypid()]);
})->listen(3000);
Terminal window
pam server.php
curl -s http://127.0.0.1:3000/ # {"hits":1,"pid":998881}
curl -s http://127.0.0.1:3000/ # {"hits":2,"pid":998881}

That is exactly what you want for a cache of compiled routes, and exactly what you do not want for “the current user”. Memory & State shows how to keep the two apart.

PAM gives every request two places for request-local data. Both are cleared automatically.

Pam\Runtime\RequestScope::current() returns the scope of the running request. Use it to store values and to register cleanup that must run however the request ends:

use Pam\Runtime\RequestScope;
$scope = RequestScope::current();
$scope->set('tenantId', 42);
$tenantId = $scope->get('tenantId');
// Closed automatically when the request ends (it has a close() method).
$report = $scope->manage(fopen('php://temp', 'w+b'));
// Runs after the response, in reverse registration order.
$scope->defer(static function (): void {
// release a lock, roll back a transaction, reset a client...
});

manage() accepts a stream resource, an object with a close() or dispose() method, or any value together with your own cleanup callback. Cleanup callbacks run in LIFO order on success, on exceptions, on timeouts and on cancellation. A callback that throws is logged and counted, and the remaining callbacks still run.

Pam\Async\FiberContext is a key-value store attached to the current Fiber. Because each request has its own Fiber, the values are private to the request, even when another request runs while this one is suspended:

use Pam\Async\FiberContext;
FiberContext::set('user', 'alice');
FiberContext::get('user'); // 'alice'
FiberContext::get('locale', 'en'); // default when missing
FiberContext::remove('user');

Futures started with Pam\Async\async() receive a copy of the parent’s context, so request IDs, trace context and the request scope follow your concurrent work.

Every request has a hard deadline, requestTimeoutMs (30 seconds by default). What happens when it passes depends on what the PHP code is doing:

Situation Result
The Fiber is suspended on a PAM operation (delay(), HTTP client, streams…) The client gets 504 Gateway Timeout; the Fiber is cancelled and its finally blocks and cleanups run. The worker keeps serving.
PHP blocks the thread (sleep(), a blocking extension call, an infinite loop) A watchdog answers 504, closes the connection, logs php_request_timeout and marks the worker for replacement. Other requests queued on that worker are answered immediately, and the master starts a new worker.
slow.php
<?php
declare(strict_types=1);
use Pam\Http\Request;
use Pam\Http\Response;
use Pam\Http\Server;
use function Pam\Async\delay;
Server::create(static function (Request $request, Response $response): Response {
if ($request->path === '/wait') {
delay(5.0); // cooperative: 504 after 1 s, the worker keeps serving
}
if ($request->path === '/block') {
sleep(5); // blocking: 504 after 1 s, the worker is replaced
}
return $response->json(['ok' => true]);
})->listen(3000, '127.0.0.1', ['requestTimeoutMs' => 1000]);

Under pam start, the master also enforces the deadline from outside: a worker that stays busy past its deadline plus --watchdog-grace (250 ms by default) and a fixed one-second allowance is killed with SIGKILL and replaced.

A PHP fatal error, an exhausted memory_limit or a call to exit() leaves the engine unusable. PAM answers that request with 500, logs php_engine_failed and recycles the worker:

PHP Fatal error: Allowed memory size of 33554432 bytes exhausted ...
{"event":"php_engine_failed","level":"error","message":"a PHP fatal error left the engine unusable; recycling this worker"}

Ordinary uncaught exceptions do not recycle the worker. PAM logs Unhandled request exception with the request ID and answers 500 with a generic JSON body; exception details reach the response only when exposeErrors is enabled.

Every request of a worker shares one memory_limit. To stop a burst of large uploads from exhausting it, PAM caps the request bodies that PHP holds at once with maxInflightBodyBytes. The default is a quarter of memory_limit; 0 disables the budget, and the PAM_MAX_INFLIGHT_BODY_BYTES environment variable overrides the option.

A request that does not fit waits up to requestTimeoutMs for budget to free up, then receives 503 with a Retry-After header.

A worker starts draining when it receives SIGTERM, when the master reloads the application, when it reaches --max-requests, or when a request wedged its PHP thread. A draining worker:

  1. stops accepting new connections and closes HTTP/1 keep-alive connections after their current response;
  2. finishes the requests it already holds, up to --graceful-timeout (15 seconds by default);
  3. exits, and the master replaces it if it is still wanted.

Your code can ask whether the worker is draining with pam_draining(). Use it in readiness endpoints, so load balancers stop routing to the worker while it finishes in-flight work:

server.php
<?php
declare(strict_types=1);
use Pam\Http\Request;
use Pam\Http\Response;
use Pam\Http\Server;
Server::create(static function (Request $request, Response $response): Response {
if ($request->path === '/ready') {
return pam_draining()
? $response->json(['ready' => false], 503)
: $response->json(['ready' => true]);
}
return $response->json(['hello' => 'world']);
})->listen(3000);

Nimbus’s HealthEndpoints use pam_draining() for their /ready route.

pam start --max-requests N replaces a worker after it has served N requests that ran PHP (responses served entirely by Rust, such as page-cache hits or /metrics, do not count). The default is 10,000,000. Recycling is make-before-break: the old worker keeps serving until its replacement is ready, then drains.

To avoid every worker recycling at the same moment, PAM staggers the limit per worker by up to 25%: --max-requests is a ceiling, not an exact count.