Request Lifecycle
Under PHP-FPM, every request starts from nothing: PHP loads Laravel, runs the request, and throws everything away. Under PAM, a worker boots Laravel once and then serves thousands of requests from the same process. That is where the speed comes from, and it is also the one thing you must understand to run Laravel safely on PAM.
The short version:
- Laravel’s own request state (the request, auth guards, session store, queued cookies, scoped bindings, facades, config changes) is reset by PAM after every request.
- Your static properties, and singletons resolved while booting, live as long as the worker. Do not keep per-request data in them.
Worker Boot
Section titled “Worker Boot”When a worker starts, Application::boot():
- requires
bootstrap/app.php; - applies
PAM_LARAVEL_STORAGE_PATHwhen set; - binds a placeholder
GET http://127.0.0.1/request (some packages, such as Telescope, expect one while their providers boot); - bootstraps the HTTP kernel: environment, configuration, facades, service
providers (
registerandboot), and routes; - resolves
auth,cache,db,filesystem,mail.manager,queue, andsessionin the root container so their connections and stores persist; and - removes the placeholder request.
Anything your service providers do in boot() therefore runs once per worker,
not once per request.
Handling a Request
Section titled “Handling a Request”For each request or Socket callback, the worker:
- builds an
Illuminate\Http\Requestfrom the native request, including uploaded files; - clones the booted container into a sandbox and makes it the current
container (
Container::getInstance(), facades); - gives the sandbox its own copies of
config,url,events,translator,validator, and the Bus dispatcher, and points the kernel, router, managers, Eloquent’s event dispatcher, and views at the sandbox; - runs the normal HTTP kernel: middleware, routing, controller, exception handler;
- writes the response: streamed and file responses are sent in chunks with backpressure, never buffered whole;
- calls
$kernel->terminate()after the response finishes or the client disconnects; - clears request state (listed below) and flushes the sandbox; and
- restores the root container for the next request.
What PAM Resets After Every Request
Section titled “What PAM Resets After Every Request”| State | How it is reset |
|---|---|
| The current request | Forgotten from the root and sandbox containers |
config() changes |
The sandbox received a clone; changes vanish with it |
| Auth guards | forgetGuards(): the next request resolves the user again |
| Session store | Flushed after StartSession saved it, so a request without a cookie cannot inherit it |
| Queued cookies | flushQueuedCookies() |
| Views | flushState() (sections, stacks, shared render state) |
| Database connections | Query log, record-modification state, and duration handlers reset |
| Log context | flushSharedContext() / withoutContext() |
| Scoped bindings | forgetScopedInstances() and resetScope() |
| Facade cache | Facade::clearResolvedInstances() |
| Controllers | Route::flushController() |
| Framework static caches | Once::flush(), Str::flushCache(), Validator::flushState(), FormRequest::flushState(), Http\Client\Response::flushState(), JsonResource::flushState() |
With pushinbr/pam-laravel installed, the state guard
additionally rolls back leaked transactions and restores the process locale.
What Survives Between Requests
Section titled “What Survives Between Requests”This is real output from a test route that increments four counters, served by one worker, three requests in a row:
{"static":1,"boot_singleton":1,"lazy_singleton":1,"scoped":1,"config_before":null}{"static":2,"boot_singleton":2,"lazy_singleton":1,"scoped":1,"config_before":null}{"static":3,"boot_singleton":3,"lazy_singleton":1,"scoped":1,"config_before":null}| Kind of state | Lives for | Why |
|---|---|---|
| Static property | The whole worker | PHP statics are process-global |
Singleton resolved during boot (provider boot(), middleware constructor at boot, etc.) |
The whole worker | The sandbox clone shares the same instance |
| Singleton first resolved during a request | That request | It lands in the sandbox, which is discarded |
scoped() binding |
That request | Forgotten after every request |
config([...]) set in a request |
That request | Each request gets a cloned repository |
The route that produced it:
use App\Support\BootCounter;use App\Support\Counter;use App\Support\LazyCounter;
Route::get('/state', function (BootCounter $boot, LazyCounter $lazy, Counter $scoped) { Counter::$static++; $boot->value++; $lazy->value++; $scoped->value++;
$before = config('demo.flag'); config(['demo.flag' => 'set']);
return [ 'static' => Counter::$static, 'boot_singleton' => $boot->value, 'lazy_singleton' => $lazy->value, 'scoped' => $scoped->value, 'config_before' => $before, ];});public function register(): void{ $this->app->singleton(BootCounter::class); $this->app->singleton(LazyCounter::class); $this->app->scoped(Counter::class);}
public function boot(): void{ // Resolved while the worker boots, so it lives as long as the worker. $this->app->make(BootCounter::class);}Common Pitfalls
Section titled “Common Pitfalls”Capturing the Request in a Singleton
Section titled “Capturing the Request in a Singleton”$this->app->singleton(TenantContext::class, function ($app) { // Captures the request that existed when it was first resolved. return new TenantContext($app['request']->header('X-Tenant'));});// A new instance per request, built from the current request.$this->app->scoped(TenantContext::class, function ($app) { return new TenantContext($app['request']->header('X-Tenant'));});The same applies to the authenticated user, the locale, and anything derived
from them. Use scoped(), resolve from the container inside the method that
needs the value, or pass the value as an argument.
Static Caches That Grow
Section titled “Static Caches That Grow”final class CurrencyFormatter{ /** @var array<string, \NumberFormatter> */ private static array $formatters = [];
public static function for(string $locale): \NumberFormatter { // Bounded by the number of locales you support: fine. return self::$formatters[$locale] ??= new \NumberFormatter($locale, \NumberFormatter::CURRENCY); }}A static cache keyed by something bounded (locales, currencies) is a feature. A static array keyed by user ID, URL, or request ID is a memory leak: bound it, key it on something finite, or move it to the cache store.
Open Transactions
Section titled “Open Transactions”A request that calls DB::beginTransaction() and returns without committing
leaves the shared connection inside a transaction. With pushinbr/pam-laravel
installed, the state guard rolls it back after the request and records a
violation. Without it, wrap work in DB::transaction(fn () => ...), which
always commits or rolls back.
Global PHP State
Section titled “Global PHP State”setlocale(), date_default_timezone_set(), ini_set(), putenv(), and
mb_internal_encoding() change the whole process. Prefer Laravel’s
App::setLocale() (reset per request) and Carbon’s per-instance timezones.
The State Guard
Section titled “The State Guard”pushinbr/pam-laravel pushes Pam\Laravel\Http\Middleware\GuardPersistentState
onto the web and api middleware groups. Around every request it:
- records each connection’s transaction level, then rolls back anything above
it and reports “Rolled back leaked transaction on connection
sqlite.”; - calls
forgetGuards()on the auth manager; - restores the ICU default locale (
Locale::setDefault); and - clears resolved facade instances.
Make leaks fail loudly in CI and staging:
PAM_LARAVEL_STATE_GUARD=truePAM_LARAVEL_STATE_GUARD_STRICT=trueIn strict mode a request that leaks a transaction returns 500 instead of
silently succeeding. Violations are visible in /__pam/metrics under
stateViolations (see Observability).
Lifecycle Hooks
Section titled “Lifecycle Hooks”For application-specific cleanup, implement Pam\Laravel\Contracts\LifecycleHook
and register it with the LifecycleManager:
<?php
namespace App\Pam;
use App\Support\TenantRegistry;use Illuminate\Http\Request;use Pam\Laravel\Contracts\LifecycleHook;use Symfony\Component\HttpFoundation\Response;
final class ResetTenantHook implements LifecycleHook{ public function beforeRequest(Request $request): void { TenantRegistry::clear(); }
public function afterRequest(Request $request, Response $response, int $durationNanoseconds): void { TenantRegistry::clear(); }}use App\Pam\ResetTenantHook;use Pam\Laravel\Services\LifecycleManager;
public function boot(): void{ $this->app->make(LifecycleManager::class)->register(new ResetTenantHook());}Hooks run from the ObserveRequest middleware on the web and api groups:
beforeRequest in registration order, afterRequest in reverse order. When the
request throws, afterRequest still runs with a synthetic 500 response that
carries an X-Pam-Exception header. Hooks only run while
PAM_LARAVEL_OBSERVABILITY or PAM_OTLP_ENABLED is on, and only for routes in
the web and api groups.
Concurrency
Section titled “Concurrency”Each worker runs one Laravel request at a time. Requests that arrive while the
worker is busy wait in its queue (up to phpExecutorQueueCapacity, default
1024) instead of being rejected. Six concurrent requests to a route that
sleeps for 500 ms, sent to a single worker, all returned 200 after about
three seconds. Waiting is still bounded by requestTimeoutMs.
That is why worker count is your concurrency knob:
pam start pam.php --workers "$(nproc)"A native (non-Laravel) PAM application can run many requests per worker in Fibers; the one-request rule is specific to Laravel’s process-global state.
Streamed and File Responses
Section titled “Streamed and File Responses”StreamedResponse and BinaryFileResponse are sent incrementally through a
bounded queue with client backpressure. HEAD and byte ranges work, and a
client disconnect cancels the request. maxResponseBytes and
maxResponseChunkBytes cap what a single response may send; raise them in
pam.php if you serve larger legitimate downloads.
Worker Recycling
Section titled “Worker Recycling”Sandboxing protects the state PAM knows about. It cannot prove that every
third-party package releases memory. Keep --max-requests as a safety net
(see Performance Tuning) and run the
persistent smoke test.