Skip to content

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.

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.

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:

Terminal window
pam -d memory_limit=256M index.php

When 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.

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);

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);

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);

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);

manage() 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.

PAM offers two request-local stores. Both are cleared automatically when the request ends.

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'));
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 Fiber
FiberContext::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.

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.

index.php
<?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);
Terminal window
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.

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}

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:

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

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.

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:

Terminal window
pam start index.php --workers 8 --max-requests 200000

See Workers & Supervision.

  • Keep request data in local variables, RequestScope, FiberContext or 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() or defer().
  • 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 leakDetectionSampleRate set to 1 before you ship.