Skip to content

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.

When a worker starts, Application::boot():

  1. requires bootstrap/app.php;
  2. applies PAM_LARAVEL_STORAGE_PATH when set;
  3. binds a placeholder GET http://127.0.0.1/ request (some packages, such as Telescope, expect one while their providers boot);
  4. bootstraps the HTTP kernel: environment, configuration, facades, service providers (register and boot), and routes;
  5. resolves auth, cache, db, filesystem, mail.manager, queue, and session in the root container so their connections and stores persist; and
  6. removes the placeholder request.

Anything your service providers do in boot() therefore runs once per worker, not once per request.

For each request or Socket callback, the worker:

  1. builds an Illuminate\Http\Request from the native request, including uploaded files;
  2. clones the booted container into a sandbox and makes it the current container (Container::getInstance(), facades);
  3. 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;
  4. runs the normal HTTP kernel: middleware, routing, controller, exception handler;
  5. writes the response: streamed and file responses are sent in chunks with backpressure, never buffered whole;
  6. calls $kernel->terminate() after the response finishes or the client disconnects;
  7. clears request state (listed below) and flushes the sandbox; and
  8. restores the root container for the next 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.

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:

routes/api.php
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,
];
});
app/Providers/AppServiceProvider.php
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);
}
app/Providers/AppServiceProvider.php
$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'));
});

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.

app/Support/CurrencyFormatter.php
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.

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.

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.

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:

.env.testing
PAM_LARAVEL_STATE_GUARD=true
PAM_LARAVEL_STATE_GUARD_STRICT=true

In strict mode a request that leaks a transaction returns 500 instead of silently succeeding. Violations are visible in /__pam/metrics under stateViolations (see Observability).

For application-specific cleanup, implement Pam\Laravel\Contracts\LifecycleHook and register it with the LifecycleManager:

app/Pam/ResetTenantHook.php
<?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();
}
}
app/Providers/AppServiceProvider.php
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.

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:

Terminal window
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.

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.

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.