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.
Production Checklist
Section titled “Production Checklist”Before you expose an application, walk through this list:
- Install production dependencies:
pam composer install --no-dev --classmap-authoritative. - Run
pam doctoron the release directory (or inside the final bundle or image). - Start with
pam start(orpam up/pam apply), never withpam dev. - Choose
--workersfrom measurements; start around one worker per CPU core. - Bind the control plane (
--admin-address) to loopback, or setPAM_ADMIN_TOKEN_FILE. - Behind a proxy, set
trustedProxies(orPAM_TRUSTED_PROXIES) to only your proxies. - Keep
exposeErrorsoff (the default) and ship logs from stderr. - Keep
/metricson loopback (the default) or protect it withmetricsToken. - 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), setPAM_IO_THREADS=1. - Never commit
.env*files, TLS keys, tokens orwebsocketResumeSecret. - Plan reloads (
SIGHUPorpam reload) and a rollback path before the first deploy.
Starting the Cluster
Section titled “Starting the Cluster”Install dependencies, verify the environment, then start the supervised cluster:
pam composer install --no-dev --classmap-authoritativepam doctorpam 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:3010The 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=2Pam master 1032739 started 2 worker(s); send SIGHUP for zero-downtime reloadThe 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:
PAM_HOST=0.0.0.0 PAM_PORT=8080 pam start index.php --workers 8Hardening Defaults
Section titled “Hardening Defaults”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 |
Configuring the Listener
Section titled “Configuring the Listener”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:
<?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.
Behind a Reverse Proxy
Section titled “Behind a Reverse Proxy”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:
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:
PAM_TRUSTED_PROXIES=10.0.0.0/8,172.16.0.1 pam start index.phpHow 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-Forentry 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.
TLS, HTTP/2 and HTTP/3
Section titled “TLS, HTTP/2 and HTTP/3”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
h2and over cleartext with prior knowledge (h2c). Tune it withhttp2MaxConcurrentStreams(256),http2StreamWindowBytes(1 MiB) andhttp2ConnectionWindowBytes(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' => falsewhere UDP is not exposed. - Certificates and keys are read when a worker starts. After renewing them, reload the cluster (
kill -HUP <master-pid>orpam reload <name>). - TLS connections always use separate I/O threads, and connections TLS-terminated by PAM are not balanced between sibling workers.
Threads and Blocking Code
Section titled “Threads and Blocking Code”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.
Set one I/O thread per worker so connections keep being accepted (and answered with 503/504) while PHP is busy:
PAM_IO_THREADS=1 pam start index.php --workers 8In both modes a short requestTimeoutMs bounds how long a stuck request holds a worker.
Limits and Capacity
Section titled “Limits and Capacity”| 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 torequestTimeoutMs, then gets503withRetry-After. - Multipart uploads are streamed to temporary files (
upload_tmp_dir, mode0600) and are governed by PHP’s ownupload_max_filesize,post_max_size,max_file_uploadsandmax_multipart_body_parts.maxBodyBytesdoes not apply to them. - When a request exceeds
requestTimeoutMs, the transport answers504 Gateway Timeoutby itself, even if PHP is blocked. The worker is then recycled make-before-break; requests queued behind it on the same worker get503withRetry-After: 1. rateLimitPerSecondis a local token bucket per worker. For a global policy, rate limit at the edge or in middleware with shared storage.
Graceful Shutdown and Reloads
Section titled “Graceful Shutdown and Reloads”The master reacts to two signals:
kill -HUP <master-pid> # zero-downtime reload: boot a new generation, then drain the old onekill -TERM <master-pid> # graceful shutdown: stop accepting, finish in-flight requests, exitReloads and recycling are make-before-break:
- 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.
- A draining worker leaves connection balancing and sends
Connection: closeon HTTP/1 responses, so each client finishes its current request and reconnects to a live worker. Idle connections are closed afterPAM_DRAIN_IDLE_MS(default 1000); HTTP/2 connections get a gracefulGOAWAY. - 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.
- 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.
Readiness with pam_draining()
Section titled “Readiness with pam_draining()”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.
Health Checks and Metrics
Section titled “Health Checks and Metrics”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) |
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_TOKENorPAM_ADMIN_TOKEN_FILE(32 to 256 ASCII characters, no spaces). With a token, every endpoint requiresAuthorization: Bearer <token>. - Prefer
PAM_ADMIN_TOKEN_FILEpointing 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:
pam top http://127.0.0.1:3010 --iterations 60 --lag-warn-ms 10Logging
Section titled “Logging”Workers write to stdout and stderr; let your supervisor (systemd, Docker, Kubernetes, or pam up) collect them.
accessLog: truewrites one JSON line per request to stderr. At high traffic, sample withaccessLogSampleRate(for example100logs one request in a hundred) and rely on metrics for aggregates.- Server errors (
5xx) are logged even when the access log is off. telemetryHeaders: trueaddsx-request-id,traceparentandServer-Timingto responses. It is off by default to avoid formatting work on every response.
Running as a Service
Section titled “Running as a Service”The repository ships a hardened unit in packaging/pam.service (dynamic user, read-only filesystem, private /tmp):
[Service]Type=simpleDynamicUser=yesWorkingDirectory=/srv/pam/currentEnvironment=PAM_WORKERS=4Environment=PAM_MAX_REQUESTS=10000000Environment=PAM_ENTRYPOINT=index.phpEnvironmentFile=-/etc/pam/pam.envExecStart=/usr/local/bin/pam start ${PAM_ENTRYPOINT} --workers ${PAM_WORKERS} --max-requests ${PAM_MAX_REQUESTS} --admin-address 127.0.0.1:3010ExecReload=/bin/kill -HUP $MAINPIDKillSignal=SIGTERMKillMode=mixedTimeoutStopSec=45sRestart=alwaysLimitNOFILE=1048576PAM_WORKERS and PAM_ENTRYPOINT are variables of this unit, not settings PAM reads itself. systemctl reload pam sends SIGHUP.
The repository Dockerfile pins its base images by digest and PHP by exact package version, runs as UID 10001 under tini, and uses pam as the entry point:
FROM acme/pam-runtimeCOPY --chown=10001:10001 . /appENV PAM_HOST=0.0.0.0CMD ["start", "index.php", "--workers", "4", "--admin-address", "0.0.0.0:3010"]Build the base image from a checkout of the PAM repository first, for example docker build --tag acme/pam-runtime ~/src/pam. Because the control plane binds a non-loopback address here, mount a secret and set PAM_ADMIN_TOKEN_FILE=/run/secrets/pam-admin.
Without systemd or containers, the PAM process manager keeps the cluster alive, restarts it with backoff, and survives reboots through a user unit:
pam up --name api --workers 8 --health-check-url http://127.0.0.1:3000/readypam startup --installSee Process Management.
Deploying a New Release
Section titled “Deploying a New Release”With a symlinked release layout, a deploy is:
- Publish the code and
vendorinto a new versioned directory. - Run
pam doctorthere. - Atomically switch the
currentsymlink. - Send
SIGHUPto the master (orpam reload <name>). - Wait for
/readyand the newgenerationin/metrics. - To roll back, point
currentat 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.
Next Steps
Section titled “Next Steps”- Clustering: every
pam startflag, prefork and pools. - Process Management:
pam up,ps,logs,monit. - Security & Bundle Integrity: bundles, checksums and release gates.
- Configuration Reference and Environment Variables.