Memory & State
A PAM worker lives for a long time. That is a gift for performance (nothing boots twice) and a responsibility for correctness: a value you store in the wrong place can leak memory across millions of requests or, worse, leak one user’s data into another user’s response.
The good news is that the rules are short. This page explains where state lives in PAM, shows the classic pitfalls with good and bad examples, and gives you the tools to detect leaks before they reach production.
Where State Lives
Section titled “Where State Lives”| Place | Lifetime | Shared with | Use it for |
|---|---|---|---|
| Local variables | One function call | Nobody | Almost everything |
RequestScope, FiberContext, Nimbus scoped bindings |
One request | Nobody | Current user, tenant, locale, request ID, transactions |
| Statics, globals, singletons, handler closures | The worker’s life | Every request on that worker | Immutable configuration, compiled routes, connection pools, bounded caches |
Pam\Shared\Table |
The cluster’s life | Every worker of the cluster | Counters, rate limits, small shared caches |
| Redis, a database | Beyond the process | Every host | Sessions, queues, anything that must survive a restart |
The rule of thumb: request data goes in request scope, boot data goes in worker memory, and anything that must be identical across workers goes in shared memory or an external store.
Memory Limits
Section titled “Memory Limits”Every worker is one PHP process with one memory_limit (128M in the bundled php.ini). All requests running concurrently on that worker, including suspended ones, share it. Change it like any PHP setting:
pam -d memory_limit=256M index.phpWhen a request exhausts memory_limit, PHP raises a fatal error. PAM answers that request with 500 and recycles the worker, because the engine cannot continue safely:
PHP Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 67112960 bytes){"event":"php_engine_failed","level":"error","message":"a PHP fatal error left the engine unusable; recycling this worker"}To protect the limit from large uploads, PAM also caps the request bodies held by PHP at once (maxInflightBodyBytes, a quarter of memory_limit by default). See Request Lifecycle.
Pitfall 1: Request Data in Statics
Section titled “Pitfall 1: Request Data in Statics”A static property is shared by every request on the worker, including requests that run at the same time while another one is suspended on async I/O. Storing “the current user” there is a data leak waiting to happen.
final class CurrentUser{ public static ?string $name = null;}
Server::create(static function (Request $request, Response $response): Response { CurrentUser::$name = $request->getQuery('name', 'guest');
Pam\Async\delay(0.2); // another request runs meanwhile...
return $response->json(['user' => CurrentUser::$name]);})->listen(3000);use Pam\Async\FiberContext;
Server::create(static function (Request $request, Response $response): Response { FiberContext::set('user', $request->getQuery('name', 'guest'));
Pam\Async\delay(0.2); // another request runs meanwhile...
return $response->json(['user' => FiberContext::get('user')]);})->listen(3000);Here is what happens when Alice and Bob call the bad version 50 ms apart on the same worker:
curl 'http://127.0.0.1:3000/?name=alice' → {"static":"bob","context":"alice"}curl 'http://127.0.0.1:3000/?name=bob' → {"static":"bob","context":"bob"}Alice received Bob’s name from the static, while FiberContext kept each request’s value private. In Nimbus, register request-dependent services as scoped:
$app->container()->scoped(CurrentUser::class);Pitfall 2: Unbounded Caches
Section titled “Pitfall 2: Unbounded Caches”Caching in worker memory is one of PAM’s superpowers, but a cache that only grows will eventually exhaust memory_limit.
final class ReportCache{ /** @var array<string, string> */ public static array $rows = [];}
// One new entry per distinct query string, forever.ReportCache::$rows[$request->getQuery('q', '')] = renderReport($request);final class ReportCache{ private const MAX_ENTRIES = 1_000;
/** @var array<string, string> */ private static array $rows = [];
public static function remember(string $key, callable $render): string { if (isset(self::$rows[$key])) { // Move to the end: the array keeps insertion order. $value = self::$rows[$key]; unset(self::$rows[$key]);
return self::$rows[$key] = $value; } if (count(self::$rows) >= self::MAX_ENTRIES) { unset(self::$rows[array_key_first(self::$rows)]); // evict the oldest }
return self::$rows[$key] = $render(); }}Every in-memory cache needs a size bound, and preferably a TTL. When the cache must be consistent across workers, use a Pam\Shared\Table or Redis instead.
Pitfall 3: Resources That Are Never Closed
Section titled “Pitfall 3: Resources That Are Never Closed”File handles, sockets and locks opened during a request stay open after the response unless something closes them. Register them with the request scope, and they are closed however the request ends, including exceptions, timeouts and client disconnects:
$handle = fopen('/var/log/acme/audit.log', 'ab');fwrite($handle, $line);// An exception here leaves the handle open for the life of the worker.processOrder($order);fclose($handle);use Pam\Runtime\RequestScope;
$scope = RequestScope::current();$handle = $scope->manage(fopen('/var/log/acme/audit.log', 'ab'));fwrite($handle, $line);processOrder($order); // the handle is closed even if this throwsmanage() closes stream resources, calls close() or dispose() on objects, or runs the callback you pass as its second argument. For anything else, use defer():
$lock = $locks->acquire("order:{$order->id}");RequestScope::current()->defer(static fn () => $lock->release());Cleanups run in reverse order of registration, after the response is produced.
Pitfall 4: Connections Inherited Across Requests
Section titled “Pitfall 4: Connections Inherited Across Requests”A database or Redis connection kept in a singleton is reused by the next request. That is fast and usually what you want, but it carries risks:
- a transaction left open by a failed request is still open for the next one;
- session variables (
SET search_path,SET time_zone) persist; - a connection that broke during one request is broken for every later request.
Close or reset per-request connection state in a defer() callback, and handle reconnection where you use the connection. Nimbus and its Arcano ORM give each request Fiber its own connections and identity map and roll back unfinished transactions during cleanup, so these issues do not apply there.
When workers are forked from a booted application (PAM_PREFORK_BOOT=app), close connections opened during boot in pam_before_fork() so each worker opens its own. See Fork Hooks.
Request-Local Storage
Section titled “Request-Local Storage”PAM offers two request-local stores. Both are cleared automatically when the request ends.
RequestScope
Section titled “RequestScope”use Pam\Runtime\RequestScope;
$scope = RequestScope::current(); // throws outside a request$scope = RequestScope::currentOrNull(); // null outside a request
$scope->set('tenantId', 42);$scope->get('tenantId'); // 42$scope->forget('tenantId');$scope->defer(static fn () => audit('request finished'));$file = $scope->manage(fopen('php://temp', 'w+b'));FiberContext
Section titled “FiberContext”use Pam\Async\FiberContext;
FiberContext::set('traceId', $traceId);FiberContext::setMany(['tenant' => 'acme', 'locale' => 'en']);FiberContext::get('locale', 'en');FiberContext::snapshot(); // every value of the current FiberFiberContext::remove('tenant');Futures created with Pam\Async\async() start with a copy of their parent’s context, so values set before you fan out are visible in the child Fibers.
Sharing State Across Workers
Section titled “Sharing State Across Workers”Workers are separate processes: a static incremented in worker 1 is invisible to worker 2. For counters, rate limits and small caches that every worker must see, use a named Pam\Shared\Table. It has the API of Swoole\Table: a fixed number of rows, fixed-size int, float and string columns, and atomic increments.
<?php
declare(strict_types=1);
use Pam\Http\Request;use Pam\Http\Response;use Pam\Http\Server;use Pam\Shared\Table;
$hits = new Table(1024, name: 'app.hits');$hits->column('count', Table::TYPE_INT);$hits->create();
Server::create(static function (Request $request, Response $response) use ($hits): Response { $hits->incr('home', 'count'); // atomic across workers
return $response->json([ 'worker' => getenv('PAM_WORKER_ID'), 'total' => $hits->get('home', 'count'), ]);})->listen(3000);pam start index.php --workers 2{"worker":"1","total":1}{"worker":"1","total":2}{"worker":"2","total":3}{"worker":"2","total":4}The master owns the memory, so rows survive worker crashes, recycling and reloads, and are freed when the cluster stops. set() returns false when the table is full, and a string longer than its column throws a ValueError instead of being truncated. See Shared Memory & Caching for the complete API and limits.
Detecting Leaks
Section titled “Detecting Leaks”The Leak Detector
Section titled “The Leak Detector”PAM samples requests to catch leaks early. On a sampled request it records memory usage and the number of open resources when the request starts, runs a cycle collection after cleanup, and compares. If memory grew by more than the threshold, resources were left open, or a cleanup callback failed, it logs a warning:
{"level":"warning","message":"Potential request resource leak","context":{"requestId":"standalone-1058197-2","memoryDeltaBytes":71016,"resourceDelta":0,"cleanupFailures":0}}By default one request in 1,024 is sampled with an 8 MiB threshold. Make it stricter while you investigate:
Server::create($handler)->listen(3000, '127.0.0.1', [ 'leakDetectionSampleRate' => 1, // sample every request (0 disables sampling) 'leakThresholdBytes' => 16 * 1024, // warn above 16 KiB of growth]);Sampling only runs while a single request is in flight on the worker, so concurrent requests do not distort the numbers. Read the counters from PHP with Pam\Runtime\LeakDetector::metrics():
{"activeScopes":1,"sampledScopes":2,"suspectedLeaks":2,"cleanupFailures":0,"lastMemoryDeltaBytes":71016,"lastResourceDelta":0}Memory Snapshots
Section titled “Memory Snapshots”pam heap boots your entrypoint and prints the memory section of the runtime diagnostics; pam diagnostics prints the complete snapshot, including the leak counters and open resources:
pam heap index.php{ "allocatedBytes": 4194304, "peakBytes": 4194304, "usedBytes": 1971256, "gc": { "runs": 0, "collected": 0, "roots": 4, "threshold": 10001 }}(Output trimmed.) For live workers, watch memory and event-loop lag with pam top against the control plane; see Observability & Diagnostics.
Garbage Collection
Section titled “Garbage Collection”PAM runs gc_collect_cycles() every 256 requests and gc_mem_caches() every 1,024 requests. Tune them with the gcCollectCyclesEvery and gcMemCachesEvery listen options; 0 disables each one.
Recycling as a Safety Net
Section titled “Recycling as a Safety Net”Some leaks live in third-party code you cannot change. Recycling bounds their damage: pam start --max-requests N replaces a worker after N requests, without dropping traffic. Treat it as a seatbelt, not a fix:
pam start index.php --workers 8 --max-requests 200000Checklist
Section titled “Checklist”- Keep request data in local variables,
RequestScope,FiberContextor scoped bindings. - Keep worker memory for immutable or bounded data built at boot.
- Put a size limit on every in-memory cache.
- Close resources with
RequestScope::manage()ordefer(). - Reset connection state, and never leave a transaction open.
- Close boot-time connections in
pam_before_fork()when workers fork from a booted app. - Never call
exit()inside a request. - Run a soak test with
leakDetectionSampleRateset to1before you ship.