Architecture Overview
OxPHP is a single-binary HTTP server that replaces the traditional nginx + PHP-FPM stack. It handles HTTP parsing, TLS termination, routing, PHP execution, compression, and observability in one process with no external dependencies at runtime.
How OxPHP works
OxPHP combines two runtime layers, and an optional async pool, in a single process:
- The async HTTP layer is an event-driven network layer. It accepts TCP connections, performs TLS handshakes, parses HTTP requests, and sends responses. It handles thousands of concurrent connections using non-blocking I/O, so one slow client never blocks another.
- The PHP worker pool is a set of dedicated PHP workers that execute your PHP scripts. In standard mode, each worker handles one request at a time. In Worker mode with fiber multiplexing enabled, a single worker can serve multiple concurrent requests: when a script calls
oxphp_sleep()oroxphp_async_await(), the fiber yields the thread and the worker switches to the next request.
The two layers communicate through a bounded queue. When an HTTP request arrives that needs PHP execution, the async layer places it in the queue. An available PHP worker picks it up, executes the script, and returns the response to the async layer for delivery to the client.
The async pool is optional. It runs tasks submitted via oxphp_async() on separate OS threads, with a task queue of its own, and is enabled by setting ASYNC_WORKERS > 0. It is isolated from the worker pool, so background tasks do not block HTTP request handling.
This separation means that network I/O (accepting connections, reading headers, compressing responses, serving static files) never competes with PHP execution for resources. Each layer scales independently.
Worker pool
The PHP worker pool determines how many PHP scripts can execute concurrently. OxPHP supports two pool modes.
Static pool
A fixed number of workers start at boot and remain running for the lifetime of the server. This is the default mode.
PHP_WORKERS=8 # exactly 8 workers
PHP_WORKERS=0 # auto-detect (default): half of available CPU cores, minimum 1Dynamic pool
Workers scale up and down based on demand. Specify a minimum and maximum count separated by a colon:
PHP_WORKERS=2:16 # start with 2, scale up to 16 under loadWhen all current workers are busy, OxPHP spawns new workers up to the maximum. When a worker has been idle for longer than PHP_WORKERS_IDLE_SECONDS (default: 30 seconds), it is retired back down toward the minimum.
Retirement happens at a moment when the worker has nothing in flight, so a request it is still serving always runs to its own response. The same rule sets the boundary: a worker holding a request that never ends (an open stream, a read from a peer that stops answering) never reaches such a moment, and is not retired while it holds it.
Queue and backpressure
Between the async HTTP layer and the worker pool sits a bounded queue. Its capacity, QUEUE_CAPACITY, defaults to the initial worker count multiplied by 128: the configured count for a static pool, the minimum for a dynamic one (MIN:MAX).
A request that arrives at a full queue waits for a slot, for up to QUEUE_WAIT_TIMEOUT_MS (default: 1000 ms), and is admitted as soon as a worker picks up the request ahead of it. Waiting requests are admitted in arrival order. The wait budget is one deadline stamped on arrival, and it follows the request into the queue:
- When the deadline passes, the request is answered with
529, whether it is still waiting for a slot or sitting in the queue. A worker that picks up a request past its deadline refuses it instead of running it. - If the client has closed the connection by then, the answer is
499, so the overload series does not count clients that gave up waiting. QUEUE_WAIT_TIMEOUT_MSis the maximum wait, not a fixed length. Under overload the server shortens the budget while work admitted from the wait completes for clients that have already disconnected, and restores it once the queue drains (see The wait budget).
Load is shed on elapsed wait time rather than on queue depth: a burst that drains in microseconds is served, while a pool that cannot keep up sheds. The budget bounds waiting only. A request a worker picked up in time runs to its end however long the handler takes, so response time under load is the wait plus execution time.
Two caps bound the waiting set:
QUEUE_MAX_WAITINGcaps how many requests may wait at once (default: initial workers × 128, capped at half ofMAX_CONNECTIONS). Past it, admission rejects immediately. A waiting request holds its connection and its already-buffered body, so an uncapped waiting set would take every connection permit under sustained overload.QUEUE_MAX_WAITING_BYTES(default 64 MiB) caps the request-body bytes parked at once. Past it, a request carrying a body is refused immediately, while bodyless ones keep waiting. It does not cover bodies already handed to the queue (bounded in requests byQUEUE_CAPACITY, not in bytes) or a body still being read off the connection.
Keep PHP_WORKERS + QUEUE_CAPACITY + QUEUE_MAX_WAITING below MAX_CONNECTIONS. The MAX_CONNECTIONS / 2 ceiling covers the waiting set alone and QUEUE_CAPACITY has none, while queued and running requests hold their connections too. Once the sum reaches the budget, the accept loop parks with every permit taken, and a client arriving then gets no response at all instead of a 529. The server warns about this at startup and reports each park while it lasts:
- a
WARNwhen the accept loop parks and anINFOwith the duration when it resumes, rate-limited so that a server repeatedly hitting the ceiling does not flood its own log; - the
oxphp_accept_stalledgauge and theoxphp_accept_stalls_totalcounter, updated on every park (including the ones the log rate limit suppresses) and served by the internal listener, outside this budget; see the metrics reference.
A clean startup check does not rule out a park, because connections that never reach PHP hold permits too. The terms are counted in connections while the budget is spent by requests: over HTTP/2 one connection carries many requests, so an h2-heavy deployment should set QUEUE_MAX_WAITING explicitly and can sit above the sum. Keeping headroom for the accept loop has the sizing steps.
OxPHP returns 529 Site is Overloaded with a Retry-After header when a request cannot be served at all: the wait budget ran out, or one of the caps above refused it a place to wait. Status code 529 (non-standard, used by Cloudflare and others) keeps overload apart from application errors (500) and maintenance (503), so alerts and load balancers are easier to configure. Setting QUEUE_WAIT_TIMEOUT_MS=0 disables the wait and rejects the moment the queue is full.
Waiting requests occupy a connection rather than a queue slot, so under overload the concurrency ceiling is MAX_CONNECTIONS, or MAX_CONNECTIONS multiplied by H2_MAX_CONCURRENT_STREAMS over HTTP/2, where each stream carries a request of its own. The request body is already buffered when a request reaches the queue, so a longer budget means an overloaded server holds more requests, and their bodies, in memory before answering.
Request flow
Every request passes through the same pipeline, regardless of whether it serves a static file or executes PHP:
graph TD
Client(["Client"]) --> TLS["TLS termination<br/>(if configured)"]
TLS --> Parse["HTTP parsing + Request ID"]
Parse --> Proxy["Trusted proxy resolution<br/>(if TRUSTED_PROXIES set)"]
Proxy --> Rate["Rate limiting check"]
Rate --> Route{"Route resolution"}
Route -->|Static file| Cache["File cache / disk read"]
Cache --> Compress["Compression + Response headers"]
Route -->|PHP request| Queue["Bounded queue<br/>(529 past the wait budget)"]
Queue --> Worker["PHP worker executes script"]
Worker --> Normal["Normal response"]
Worker --> SSE["SSE streaming (chunked)"]
Worker --> Early["Early response (finish_request)<br/>+ background work"]
Compress --> Deliver(["Response to client"])
Normal --> Deliver
SSE --> Deliver
Early --> Deliver
- TLS termination happens in OxPHP itself when
TLS_CERTandTLS_KEYare configured, so you do not need a separate reverse proxy. - HTTP parsing reads the request and generates a unique request ID, or preserves an incoming
X-Request-IDheader. - Trusted proxy resolution applies when
TRUSTED_PROXIESis set and the connecting IP is trusted. OxPHP then extracts the real client IP, protocol, and host fromForwarded(RFC 7239) orX-Forwarded-*headers. With thecloudflarekeyword, a request whose forwarding chain shows it arrived from a Cloudflare edge takes its client IP fromCF-Connecting-IPinstead. The resolved IP is used for all subsequent steps including rate limiting and access logging. See Trusted Proxies. - Rate limiting, if
RATE_LIMITis set, checks the client's IP against the per-IP request counter. Requests that exceed the limit receive a429 Too Many Requestsresponse immediately. - Route resolution matches the URL against the configured routing mode (traditional, framework, SPA, or worker). The result is a static file, a PHP script, or a 404. Worker mode is a routing mode of its own that takes the place of the other three: it needs a
.phpENTRY_FILEand sends every request not served as a static file to that script (see Routing). - Static files are served directly from an in-memory cache (for frequently accessed files) or streamed from disk. OxPHP adds
ETag,Last-Modified, andCache-Controlheaders automatically. - For PHP execution, the request is placed in the bounded queue and picked up by an available worker. If the queue is full, the request waits for a slot for up to
QUEUE_WAIT_TIMEOUT_MS(default: 1000 ms). The client receives 529 when that budget runs out, or at once when the waiting set is already at one of its caps (see Queue and backpressure). - Compression is applied to text-based responses before they are sent, using whichever of Brotli, Zstandard, and gzip the client's
Accept-Encodingranks highest. On a tie, cached static files get Brotli and everything else gets Zstandard (configurable viaCOMPRESSION_ENCODINGSand the per-coding level variables). - SSE streaming starts if the script sets
Content-Type: text/event-streamor callsoxphp_stream_flush(). OxPHP then switches to streaming mode, where eachflush()call sends a chunk to the client immediately without buffering the entire response. In Worker mode, SSE works cooperatively with fiber multiplexing. - Early response lets the script call
oxphp_finish_request()to send the HTTP response to the client immediately. The script continues executing in the background (writing logs, updating caches, sending notifications) without holding the connection open. - Response delivery sends the completed response back over the connection and, if access logging is enabled, writes a log entry. A PHP response that does not stream and is larger than
RESPONSE_BUFFER_BYTES(1 MiB by default) is collected in a temporary file rather than in memory; see Response buffering.
Worker Mode vs Standard Mode
OxPHP supports two PHP execution models:
Creates a fresh PHP environment for every request. Autoloaders, configuration, and database connections are initialized on each request and torn down afterward. This model is compatible with all PHP applications out of the box.
Keeps PHP workers alive across requests. Your application bootstraps once (loading the autoloader, configuration, and establishing database connections) and then enters a request loop. Between requests, OxPHP automatically resets superglobals, output buffers, and response headers while preserving the bootstrapped state. $_ENV is the deliberate exception: with PHP's default auto_globals_jit=1 it is not reset, so it is worker state rather than request state, and a value written there during one request is read by every later request that worker serves. See Superglobals.
Worker mode eliminates per-request startup overhead, which can reduce response times significantly for framework-based applications (Laravel, Symfony, etc.) where bootstrapping is expensive.
To enable worker mode, set WORKER_MODE_ENABLED=true and point ENTRY_FILE at a PHP script that calls oxphp_worker():
<?php
require __DIR__ . '/../vendor/autoload.php';
$app = new MyApp\Application();
oxphp_worker(function () use ($app) {
$app->handle();
});For a detailed guide, see Worker Mode.
Internal server
If the INTERNAL_ADDR variable is set, OxPHP starts a separate HTTP server on the specified port. It serves three endpoints:
| Endpoint | Description |
|---|---|
GET /health |
Health status in JSON (uptime, request counters, connections, worker state). Returns 200 during normal operation, 503 during degradation. |
GET /metrics |
Prometheus-format metrics (request counters, response time, queue wait time, worker statistics, compression savings). |
GET /config |
Snapshot of the active configuration in JSON. TLS file paths are redacted. |
The internal server does not go through the PHP worker pool or the bounded queue. It responds directly from the async HTTP layer, so it remains accessible even when the PHP pool is fully loaded. That makes it suitable for Kubernetes probes, pointed at the dedicated endpoints (/health/liveness, /health/readiness and /health/startup) rather than at the aggregate /health, which answers 503 on states a restart does not fix and does not track the shutdown flag a draining server sets. See Health Checks.
For details, see Internal Server.
Safety
OxPHP provides several guarantees to keep your application running reliably in production:
- Requests are isolated. A fatal error in a PHP script ends the request that raised it, and the server goes on handling the others. Outside Worker mode, a fatal error inside an extension's own cleanup at the end of a request also retires the PHP worker thread it ran on (logged at
WARNasPHP worker thread retired: an extension's request shutdown was cut short, with the thread inworkerand the extension inmodule), and the pool replaces it. In Worker mode, a worker whose third request in a row comes apart is recycled, and the other requests it was serving are cancelled where they are suspended, as a rule with503 Service Unavailable(see Worker Recycling). - Some failures end the whole process. An allocation past PHP's hard memory limit on PHP 8.4.27 / 8.5.12 and later (see Memory limits) stops the server, and so does a native crash, such as a segmentation fault in PHP or in an extension. Bringing the server back is left to the container runtime or process supervisor.
- Workers respawn automatically. OxPHP replaces a PHP worker that dies unexpectedly, without manual intervention. A static pool refills to its configured count; a dynamic pool refills only to its minimum, and a worker lost above that is regained by ordinary scale-up.
- A server bug with a request open stops the server. A bug in OxPHP itself that brings down a worker, or an
oxphp_async()pool thread, while a PHP request is open on it stops the whole server, because that request cannot be shut down safely. On stderr the panic message is followed byoxphp: thread '<name>' panicked with a PHP request open; aborting(orpanicked in the async pool; aborting). The published images run OxPHP as PID 1, so the container exits with139, or with134when started withdocker run --init. - Backpressure. When the server is at capacity, a new request waits for a slot only as long as the wait budget allows, then receives a 529 response with a
Retry-Afterheader instead of queueing indefinitely and causing cascading timeouts. - Path traversal protection. All URL paths are sanitized before filesystem access. Percent-encoded traversal attempts,
..segments, and paths that escape the document root are blocked. - Graceful shutdown. On SIGTERM or SIGINT (Ctrl+C), OxPHP stops taking new connections (the listening socket stays open until the process exits; see Graceful Shutdown) and waits for in-flight requests to complete, up to a configurable drain timeout, before exiting.
See also
- Worker Mode: persistent PHP workers and the
oxphp_worker()API - Fiber Multiplexing: hundreds of concurrent requests on a single worker
- SSE Streaming: streaming events from PHP
- Early Response:
oxphp_finish_request()and background processing - Async Promises:
oxphp_async()/oxphp_async_await() - Internal Server: health, metrics, config
- Routing: the routing modes and how URLs are resolved
- Configuration Reference: complete list of environment variables
- Metrics: observing the worker pool and request pipeline
- Quick Start: get OxPHP running in under 5 minutes