Skip to content

Production

In production, PAM runs as a master process that supervises a set of disposable workers. Each worker boots your application once, keeps it in memory, and serves requests until it is recycled, reloaded or replaced after a crash. The master never runs PHP itself: it starts workers, watches their readiness, exposes health and metrics, and turns SIGHUP and SIGTERM into zero-downtime reloads and graceful shutdowns.

This page is the checklist for getting there. It covers how to start the cluster, which defaults protect you out of the box, how to sit behind a reverse proxy, TLS and HTTP/2/HTTP/3, request limits, graceful shutdown and readiness. For the cluster flags in depth, see Clustering; for keeping applications online after your terminal closes, see Process Management.

Before you expose an application, walk through this list:

  • Install production dependencies: pam composer install --no-dev --classmap-authoritative.
  • Run pam doctor on the release directory (or inside the final bundle or image).
  • Start with pam start (or pam up / pam apply), never with pam dev.
  • Choose --workers from measurements; start around one worker per CPU core.
  • Bind the control plane (--admin-address) to loopback, or set PAM_ADMIN_TOKEN_FILE.
  • Behind a proxy, set trustedProxies (or PAM_TRUSTED_PROXIES) to only your proxies.
  • Keep exposeErrors off (the default) and ship logs from stderr.
  • Keep /metrics on loopback (the default) or protect it with metricsToken.
  • Raise ulimit -n; PAM keeps 256 descriptors for PHP and uses the rest for connections.
  • If your code makes blocking calls (synchronous cURL, sleep(), blocking PDO on slow queries), set PAM_IO_THREADS=1.
  • Never commit .env* files, TLS keys, tokens or websocketResumeSecret.
  • Plan reloads (SIGHUP or pam reload) and a rollback path before the first deploy.

Install dependencies, verify the environment, then start the supervised cluster:

Terminal window
pam composer install --no-dev --classmap-authoritative
pam doctor
pam start index.php \
--workers 8 \
--max-requests 10000000 \
--graceful-timeout 15000 \
--startup-timeout 30000 \
--watchdog-grace 250 \
--restart-backoff 100 \
--admin-address 127.0.0.1:3010

The values above are the defaults except --workers (which defaults to the number of available CPUs) and --admin-address (which is off unless you set it). The master prints one line per ready worker:

Pam control plane listening on http://127.0.0.1:3010
● READY Pam listening on http://127.0.0.1:3000 worker=1
● READY Pam listening on http://127.0.0.1:3000 worker=2
Pam master 1032739 started 2 worker(s); send SIGHUP for zero-downtime reload

The port and host come from your application’s listen() call, not from the CLI. The scaffolded templates read PAM_PORT and PAM_HOST, so you can change them per environment:

Terminal window
PAM_HOST=0.0.0.0 PAM_PORT=8080 pam start index.php --workers 8

These defaults are part of PAM’s security contract (see SECURITY.md). Changing one is a behaviour change that is called out in the changelog.

Area Default Change it with
Client address The TCP peer. X-Forwarded-For is only read from trusted proxies, and the client is the rightmost entry that is not a trusted proxy trustedProxies, PAM_TRUSTED_PROXIES
Worker /metrics Answers loopback peers only, and not loopback requests carrying X-Forwarded-For, Forwarded or X-Real-IP metricsToken / PAM_METRICS_TOKEN, metricsPublic / PAM_METRICS_PUBLIC=1
WebSocket origin An upgrade from another site’s page (Origin not allowed and not the request host) gets 403 websocketOrigins / PAM_WEBSOCKET_ORIGINS (falls back to corsOrigins)
PHP errors display_errors=0, log_errors=1 in server mode; expose_php off exposeErrors
Request bodies in memory maxBodyBytes 2 MiB; all bodies a worker holds at once are capped at a quarter of memory_limit maxBodyBytes, maxInflightBodyBytes, PAM_MAX_INFLIGHT_BODY_BYTES
Headers 100 headers, 32 KiB, 10 seconds to read maxHeaders, maxHeaderBytes, headerReadTimeoutMs
Headers with _ in the name Kept out of $_SERVER (so X-Forwarded_For cannot overwrite HTTP_X_FORWARDED_FOR); still in the request’s header list —
Connections per worker Open file limit minus 256; past it the worker stops accepting and the kernel queue holds new connections maxConnections
Request deadline requestTimeoutMs 30 seconds, hard: 504 and the worker is recycled requestTimeoutMs
Request ID Generated by the worker; a client X-Request-Id is only a correlation label —
Control plane Off; a non-loopback --admin-address refuses to start without a token PAM_ADMIN_TOKEN, PAM_ADMIN_TOKEN_FILE
Runtime rate limit Off rateLimitPerSecond

Production limits are options of the third listen() argument. Here is a complete raw-runtime entry point with a readiness route, sane limits and a protected metrics endpoint:

index.php
<?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 match ($request->path) {
'/ready' => pam_draining()
? $response->json(['ready' => false], 503)
: $response->json(['ready' => true]),
default => $response->json(['message' => 'Hello from Acme']),
};
})->listen((int) (getenv('PAM_PORT') ?: 3000), getenv('PAM_HOST') ?: '127.0.0.1', [
'requestTimeoutMs' => 10_000,
'maxBodyBytes' => 1024 * 1024,
'trustedProxies' => ['127.0.0.1', '10.0.0.0/8'],
'metricsToken' => getenv('PAM_METRICS_TOKEN') ?: null,
'accessLog' => true,
'accessLogSampleRate' => 100,
'http3' => false,
]);

Every option, its type and its default is listed in the Configuration Reference. Nimbus applications pass the same options through their own listen() call.

A dedicated proxy (Caddy, nginx, a cloud load balancer) is still useful for automated certificates, a WAF and routing. Point it at the application port and keep the control plane private:

Caddyfile
example.com {
reverse_proxy 127.0.0.1:3000 {
health_uri /ready
health_interval 10s
}
}

Then tell PAM which peers may set forwarding headers:

'trustedProxies' => ['127.0.0.1', '10.0.0.0/8'],

or, without changing code:

Terminal window
PAM_TRUSTED_PROXIES=10.0.0.0/8,172.16.0.1 pam start index.php

How the client address is chosen:

  • Forwarding headers from untrusted peers are ignored; the client is the TCP peer.
  • With a trusted peer, the client is the rightmost X-Forwarded-For entry that is not itself a trusted proxy. Everything to its left was written by the client and is not trusted.
  • Entries must be IP addresses; anything else stops the walk at the last trusted hop.
  • * trusts every peer and logs a warning at boot. Do not use it on a public network.

The result feeds $_SERVER['REMOTE_ADDR'] and rateLimitPerSecond.

PAM can terminate TLS itself. Set tlsCert and tlsKey to PEM files:

'tlsCert' => '/etc/pam/example.com.pem',
'tlsKey' => '/etc/pam/example.com.key',
  • HTTP/2 is served over TLS with ALPN h2 and over cleartext with prior knowledge (h2c). Tune it with http2MaxConcurrentStreams (256), http2StreamWindowBytes (1 MiB) and http2ConnectionWindowBytes (4 MiB).
  • HTTP/3 (QUIC) is on by default (http3: true) when TLS is configured. It needs the same port open for UDP as well as TCP; set 'http3' => false where UDP is not exposed.
  • Certificates and keys are read when a worker starts. After renewing them, reload the cluster (kill -HUP <master-pid> or pam reload <name>).
  • TLS connections always use separate I/O threads, and connections TLS-terminated by PAM are not balanced between sibling workers.

By default (PAM_IO_THREADS=0) each worker serves plain HTTP/1 connections on the PHP thread: no thread hop per request, which measured fastest. The trade-off: PHP code that blocks synchronously (sleep(), synchronous cURL, blocking PDO, long CPU loops) stalls every connection of that worker until the request deadline.

Keep the default. Use Pam\Async, the HTTP client, PAM database drivers and background tasks for slow work.

In both modes a short requestTimeoutMs bounds how long a stuck request holds a worker.

Concern Option Default
Body kept in memory (JSON, forms, raw) maxBodyBytes 2 MiB
All bodies held by one worker maxInflightBodyBytes memory_limit / 4 (0 disables)
Concurrent requests (Fibers) per worker maxConcurrentRequests 4096
Open connections per worker maxConnections open file limit − 256
Request deadline requestTimeoutMs 30000 ms
Header read deadline headerReadTimeoutMs 10000 ms
Body read deadline bodyReadTimeoutMs 30000 ms
Response size / chunk maxResponseBytes / maxResponseChunkBytes 256 MiB / 1 MiB
WebSocket connections per worker websocketMaxConnections 10000

A few rules of thumb:

  • Every request of a worker shares one memory_limit. Exhausting it recycles the worker with every request in flight. That is why bodies are budgeted per worker: a request over the budget waits up to requestTimeoutMs, then gets 503 with Retry-After.
  • Multipart uploads are streamed to temporary files (upload_tmp_dir, mode 0600) and are governed by PHP’s own upload_max_filesize, post_max_size, max_file_uploads and max_multipart_body_parts. maxBodyBytes does not apply to them.
  • When a request exceeds requestTimeoutMs, the transport answers 504 Gateway Timeout by itself, even if PHP is blocked. The worker is then recycled make-before-break; requests queued behind it on the same worker get 503 with Retry-After: 1.
  • rateLimitPerSecond is a local token bucket per worker. For a global policy, rate limit at the edge or in middleware with shared storage.

The master reacts to two signals:

Terminal window
kill -HUP <master-pid> # zero-downtime reload: boot a new generation, then drain the old one
kill -TERM <master-pid> # graceful shutdown: stop accepting, finish in-flight requests, exit

Reloads and recycling are make-before-break:

  1. The new generation (or the replacement worker) boots and reports ready before the old one starts draining. If the new generation fails readiness, the old one keeps serving.
  2. A draining worker leaves connection balancing and sends Connection: close on HTTP/1 responses, so each client finishes its current request and reconnects to a live worker. Idle connections are closed after PAM_DRAIN_IDLE_MS (default 1000); HTTP/2 connections get a graceful GOAWAY.
  3. The listening socket belongs to the master and is adopted by the next incarnation of the worker, so connections already queued in the kernel are never reset.
  4. The master waits up to --graceful-timeout (default 15000 ms) before killing a worker that has not exited.

The repository’s cluster tests reload three times under load without client retries and expect zero failed requests, and check that SIGTERM finishes an in-flight request and exits 0.

When a worker starts draining (on SIGTERM, a reload, a --max-requests recycle or a wedged request), PHP sees pam_draining() return true. Use it in your application’s readiness endpoint so a load balancer stops sending new traffic while in-flight requests finish:

'/ready' => pam_draining()
? $response->json(['ready' => false], 503)
: $response->json(['ready' => true]),

Nimbus’s HealthEndpoints already uses pam_draining() for its /ready route.

Start the master with --admin-address to expose its control plane. It never enters PHP:

Endpoint Meaning
/live The supervisor is alive
/startup The first worker generation finished booting
/ready Every desired worker is ready or busy and within its deadline
/metrics Prometheus text: cluster, worker, HTTP, cache, WebSocket and event-loop-lag series
/diagnostics A versioned JSON snapshot per worker (lifecycle, PID, generation, lag)
Terminal window
curl -s http://127.0.0.1:3010/ready
{"schemaVersion":1,"surfaceCode":1,"resultCode":1,"healthy":true,"generation":1,"desiredWorkers":2,"readyWorkers":2,"workers":[{"id":1,"generation":1,"pid":1032748,"pool":null,"state":2},{"id":2,"generation":1,"pid":1032749,"pool":null,"state":2}]}

Worker state is 1 starting, 2 ready, 3 busy, 4 draining. Unhealthy answers use HTTP 503.

Securing the control plane:

  • On loopback, a token is optional. On any other address, the master refuses to start without PAM_ADMIN_TOKEN or PAM_ADMIN_TOKEN_FILE (32 to 256 ASCII characters, no spaces). With a token, every endpoint requires Authorization: Bearer <token>.
  • Prefer PAM_ADMIN_TOKEN_FILE pointing at a mounted secret. The file must be a regular file (no symlink); setting both variables is an error.
  • The control plane speaks plain HTTP. Across hosts, add TLS in a sidecar or tunnel; the bearer token is not transport security.

Watch it live from a terminal with pam top:

Terminal window
pam top http://127.0.0.1:3010 --iterations 60 --lag-warn-ms 10

Workers write to stdout and stderr; let your supervisor (systemd, Docker, Kubernetes, or pam up) collect them.

  • accessLog: true writes one JSON line per request to stderr. At high traffic, sample with accessLogSampleRate (for example 100 logs one request in a hundred) and rely on metrics for aggregates.
  • Server errors (5xx) are logged even when the access log is off.
  • telemetryHeaders: true adds x-request-id, traceparent and Server-Timing to responses. It is off by default to avoid formatting work on every response.

The repository ships a hardened unit in packaging/pam.service (dynamic user, read-only filesystem, private /tmp):

/etc/systemd/system/pam.service
[Service]
Type=simple
DynamicUser=yes
WorkingDirectory=/srv/pam/current
Environment=PAM_WORKERS=4
Environment=PAM_MAX_REQUESTS=10000000
Environment=PAM_ENTRYPOINT=index.php
EnvironmentFile=-/etc/pam/pam.env
ExecStart=/usr/local/bin/pam start ${PAM_ENTRYPOINT} --workers ${PAM_WORKERS} --max-requests ${PAM_MAX_REQUESTS} --admin-address 127.0.0.1:3010
ExecReload=/bin/kill -HUP $MAINPID
KillSignal=SIGTERM
KillMode=mixed
TimeoutStopSec=45s
Restart=always
LimitNOFILE=1048576

PAM_WORKERS and PAM_ENTRYPOINT are variables of this unit, not settings PAM reads itself. systemctl reload pam sends SIGHUP.

With a symlinked release layout, a deploy is:

  1. Publish the code and vendor into a new versioned directory.
  2. Run pam doctor there.
  3. Atomically switch the current symlink.
  4. Send SIGHUP to the master (or pam reload <name>).
  5. Wait for /ready and the new generation in /metrics.
  6. To roll back, point current at the previous release and reload again.

The process manager can do the same through pam deploy, pam rollback and pam deploy:remote; see Declarative Deploys.