Shared Memory & Caching
Because PAM workers stay in memory, you have caching options that do not exist under PHP-FPM:
- Worker memory. A static array survives between requests, so it is the fastest cache there is. It is private to one worker and lost when the worker restarts.
- Shared memory tables.
Pam\Shared\Tableis a fixed-size table in shared memory that every worker of a cluster can read and update atomically, with the API ofSwoole\Table. - The edge page cache. PAM can store complete HTTP responses in its Rust layer and answer later requests without entering PHP at all, like a built-in Varnish.
For application data that must be shared between servers, use Redis or your framework’s cache (Nimbus Cache, Laravel Cache).
Worker Memory
Section titled “Worker Memory”Anything you keep in a static property or a variable captured at boot lives as long as the worker:
final class CountryList{ private static ?array $countries = null;
public static function all(): array { return self::$countries ??= json_decode( Pam\Filesystem\File::read(__DIR__ . '/countries.json'), true, ); }}This is ideal for data that rarely changes (configuration, lookup tables, compiled templates). Keep it bounded: a cache that grows with every request is a memory leak, and each worker holds its own copy. See Memory & State.
Shared Memory Tables
Section titled “Shared Memory Tables”A Pam\Shared\Table has a fixed number of rows and typed columns, defined before the first use:
<?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: 'hits');$hits->column('count', Table::TYPE_INT);$hits->create();
Server::create(static function (Request $request, Response $response) use ($hits): Response { $count = $hits->incr('home', 'count');
return $response->json(['hits' => $count, 'worker' => getenv('PAM_WORKER_ID')]);})->listen(3000, '127.0.0.1');Run it as a cluster and every worker increments the same counter:
pam start index.php --workers 2Named and Anonymous Tables
Section titled “Named and Anonymous Tables”public function __construct(int $size, float $conflictProportion = 0.2, string $name = '', int $keySize = 64);- Named tables (
name: 'hits') are owned by the PAM master. Every worker that opens the same name with the same columns sees the same rows, and the rows survive worker recycling and zero-downtime reloads. They are freed when the server stops. - Anonymous tables behave like
Swoole\Table: they are shared with processes forked aftercreate().
Memory is committed only as rows are written. $conflictProportion is accepted for Swoole compatibility and ignored.
Columns
Section titled “Columns”| Constant | Stored as | Size argument |
|---|---|---|
Table::TYPE_INT |
64-bit integer | ignored |
Table::TYPE_FLOAT |
64-bit float | ignored |
Table::TYPE_STRING |
bytes | maximum length, required |
Define every column with column() before create(); columns cannot change afterwards.
Reading and Writing
Section titled “Reading and Writing”use Pam\Shared\Table;
$sessions = new Table(1024);$sessions->column('user', Table::TYPE_STRING, 64);$sessions->column('hits', Table::TYPE_INT);$sessions->column('score', Table::TYPE_FLOAT);$sessions->create();
$sessions->set('s1', ['user' => 'alice', 'hits' => 1, 'score' => 0.5]);$sessions->incr('s1', 'hits'); // 2, atomic$sessions->get('s1'); // ['user' => 'alice', 'hits' => 2, 'score' => 0.5]$sessions->get('s1', 'user'); // 'alice'$sessions->exists('s2'); // falsecount($sessions); // 1
foreach ($sessions as $key => $row) { echo "{$key}: {$row['user']}\n";}
$sessions->del('s1');| Method | Returns |
|---|---|
set($key, $values) |
true, or false when the table is full |
get($key, $field = null) |
The row, one field, or false when missing |
exists($key) / exist($key) |
bool |
del($key) / delete($key) |
bool |
incr($key, $column, $by = 1) / decr(...) |
The new value, or false |
count() |
Rows in use |
stats() |
size, memory_size, key_size, recoveries |
getSize() / getMemorySize() |
Capacity in rows / bytes reserved |
destroy() |
Detach this handle |
Keys are limited to keySize bytes (64 by default); a longer key throws ValueError. A table created with new Table(2) accepts two rows and then set() returns false for new keys, so size tables for your peak, not your average.
The Edge Page Cache
Section titled “The Edge Page Cache”The page cache stores full responses in each worker’s Rust layer. A hit is served without a PHP slot, without your framework, and with precompressed gzip/brotli copies and ETag/304 handling. It is opt-in twice: the server must enable it and each response must ask to be cached with standard headers.
<?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 { return $response ->header('Cache-Control', 'public, s-maxage=600, stale-while-revalidate=60') ->header('Pam-Cache-Tags', 'products,product:42') ->json(['generatedAt' => microtime(true)]);})->listen(3000, '127.0.0.1', [ 'responseCache' => true, 'responseCacheInvalidationLog' => __DIR__ . '/storage/page-cache.log',]);curl -si http://127.0.0.1:3000/products/42 | grep -i x-pam-cache# x-pam-cache: MISScurl -si http://127.0.0.1:3000/products/42 | grep -i x-pam-cache# x-pam-cache: HITWhat Gets Stored
Section titled “What Gets Stored”A response is stored only when all of these hold:
- the request is a
GET(aHEADis answered from theGETentry) withoutRange,Upgradeor a multipart body; - the request has no
CookieorAuthorizationheader, unless you enableresponseCacheAllowCookies/responseCacheAllowAuthorization(only for routes that do not depend on the session); - the response has
s-maxage=N(orpublicwithmax-age=N), N greater than zero, and a status inresponseCacheStatuses; - the response has no
Set-Cookie,private,no-store,no-cache,Pragma: no-cache,Vary: *orContent-Range.
The key is scheme, host, path, normalized query and the forwarding headers that change generated URLs (X-Forwarded-Host, X-Forwarded-Proto, Forwarded and similar). Headers named in the response’s Vary must match exactly. Concurrent misses for the same URL run PHP once (single flight), and within stale-while-revalidate a stale copy is served immediately while one request refreshes it in the background.
The X-Pam-Cache response header reports HIT, STALE, MISS or BYPASS.
Purging
Section titled “Purging”Tag responses with Pam-Cache-Tags (or X-Pam-Cache-Tags, or the header named in responseCacheTagHeader) and purge by tag, URL or everything:
// From PHP: purges this worker now and publishes the purge to the others.pam_cache_purge(tags: ['products']);pam_cache_purge(urls: ['/products/42', '/blog/*']);pam_cache_purge(all: true);# From the command line or a deploy script:pam cache:purge --tag=products --url=/home --log=storage/page-cache.logPAM_CACHE_INVALIDATION_LOG=storage/page-cache.log pam cache:purge --allPublished 1 purge(s) to storage/page-cache.logPurges reach sibling workers through an append-only invalidation log that each worker reads every 100 ms. pam start creates a private log automatically; set responseCacheInvalidationLog (or PAM_CACHE_INVALIDATION_LOG) to a stable path so that pam cache:purge, queue workers and other processes can reach it too. Without --log, pam cache:purge reads PAM_CACHE_INVALIDATION_LOG, then the Laravel default storage/framework/cache/pam-page-cache.log, and otherwise fails with PAM-E005. A URL without a query purges every query of that path; a trailing * purges a prefix.
You can also expose an HTTP purge endpoint with responseCachePurgePath and responseCachePurgeSecret (at least 32 bytes): POST to it with Authorization: Bearer <secret> and a body such as {"tags":["products"]}, {"urls":["/home"]} or {"all":true}.
Options
Section titled “Options”| Option | Default | Description |
|---|---|---|
responseCache |
false |
Enable header-driven caching |
responseCacheMaxBytes |
67108864 (64 MiB) |
Byte budget per worker (LRU) |
responseCacheMaxEntries |
1024 |
Entry budget per worker |
responseCacheMaxObjectBytes |
8388608 (8 MiB) |
Largest cacheable body |
responseCacheMaxTtlMs |
7 days | Upper bound for any TTL |
responseCacheStatuses |
[200, 203, 204, 300, 301, 308, 404, 410] |
Cacheable statuses |
responseCacheIgnoredQueryParams |
[] |
Query parameters left out of the key, such as utm_source |
responseCacheAllowCookies / responseCacheAllowAuthorization |
false |
Cache requests that carry these headers |
responseCacheCompress |
true |
Keep gzip and brotli copies of text bodies of 1 KiB or more |
responseCacheStatusHeader |
true |
Send X-Pam-Cache |
responseCacheTagHeader |
x-pam-cache-tags |
Extra tag header name |
responseCacheInvalidationLog |
none | Shared purge log path |
responseCachePurgePath / responseCachePurgeSecret |
none | HTTP purge endpoint |
The older path-based mode still works: responseCachePaths caches the listed paths for responseCacheTtlMs (30 s by default, plus responseCacheStaleWhileRevalidateMs) even without cache headers, and responseCacheVaryHeaders adds request headers to every key.
Hit, miss, stale, purge and size counters appear in /metrics as pam_http_response_cache_*.
Framework Caches
Section titled “Framework Caches”- Nimbus provides
Nimbus\Cache\Repositoryover a per-workerMemoryStoreor aRedisCacheStore, with tags and locks, plus a response cache middleware. See the Nimbus README. - Laravel keeps its cache drivers. The Laravel host can also use the edge page cache; see Laravel.
Next Steps
Section titled “Next Steps”- Redis: a shared cache across servers.
- Concurrency: coordinate work inside a request.
- Production: sizing workers and memory.