PHP Advent

#[Production]

FrankenPHP, RoadRunner, and PHP-FPM: PHP Worker Mode

· 18 min read

Illuminated fiber optic patch cables connect glowing rackmount application servers in a dark server room beside a mobile crash cart with a laptop showing concurrency monitors.

PHP worker mode keeps your application framework in memory between HTTP requests. A PHP-FPM child process also stays alive for multiple requests, but PHP clears request state after each one. Your front controller runs again, including Composer autoloading and framework boot. FrankenPHP and RoadRunner can boot the framework once per worker and reuse it for later requests.

Skipping that repeated startup work can reduce response times for CPU-bound endpoints. It also changes assumptions that PHP developers have relied on for decades. Static class properties survive between requests, and memory leaks accumulate. Database sockets can time out while a worker is idle; an uncommitted transaction can affect the next request.

Before leaving PHP-FPM, measure how much time your application spends booting the framework. Then check whether its code can safely handle several requests in the same execution context. The speed gain has to justify the work of resetting state, managing connections, and monitoring workers.

The Classic Architecture: PHP-FPM and Share-Nothing Execution

The FastCGI Process Manager (FPM) is the standard production runtime for PHP web applications. It maintains a pool of pre-forked worker processes that communicate with Nginx or Apache over FastCGI sockets. The PHP-FPM reference manual describes this setup.

Each PHP-FPM worker follows this request lifecycle:

  1. Accept Request: The worker accepts a FastCGI connection carrying request headers and environment variables.
  2. **Request Initialization (RINIT)**: The Zend Engine initializes superglobals ($_SERVER, $_GET, $_POST, $_COOKIE, $_FILES, $_SESSION) and activates registered extensions.
  3. Script Execution: The worker executes the front controller (typically public/index.php). The script registers Composer class autoloaders, reads environment files, compiles dependency injection containers, and dispatches the request through the framework routing layer.
  4. Output Flushing: The response headers and body are transmitted through the FastCGI socket back to the web server.
  5. **Request Shutdown (RSHUTDOWN)**: PHP runs shutdown functions and releases request-scoped variables and resources, including nonpersistent database connections.
  6. Next Request or Recycling: The same FPM child can accept another request with fresh PHP request state. The process manager eventually replaces it according to pool settings such as pm.max_requests.

This share-nothing architecture has two major advantages:

  • Request State Isolation: PHP clears ordinary globals and static properties at request shutdown. A later request does not inherit those PHP values.
  • Request Memory Cleanup: PHP releases ordinary request allocations when the request ends. Native extensions and persistent resources can still retain process memory, which is one reason FPM supports recycling children.

This isolation costs CPU time on every HTTP request. Symfony and Laravel boot hundreds of classes, build dependency injection graphs, and configure service providers, allocating memory as they go. OPcache avoids recompiling source files into bytecode, but PHP still has to run the initialization code that creates services and wires up controllers.

Older engineering perspectives, such as Sean Coates' discussion of persistent daemons in PHP, explored running background workers to bypass repeated startup costs. Today, application servers bring that persistent execution model directly to web request handling.

The Worker Mode Architecture: Staying in Memory

In worker mode, the web server or process supervisor boots the framework kernel once. A loop receives requests, passes each one to that kernel, and collects the response. The PHP process then waits for the next request with the application still in memory.

FrankenPHP and RoadRunner both use this model, but they run PHP differently.

FrankenPHP: Caddy with Embedded PHP

FrankenPHP embeds the PHP Zend Engine in the Caddy web server through Go's cgo interface. Caddy is written in Go and supports HTTP/1.1, HTTP/2, HTTP/3, and automatic TLS certificate provisioning.

In worker mode, Caddy starts multiple worker threads, as described in the FrankenPHP worker documentation. Each thread runs an embedded PHP runtime and executes your bootstrap file once. The script registers an event handler closure with frankenphp_handle_request(). Caddy delivers incoming HTTP requests directly to a waiting PHP thread, without a network hop or FastCGI serialization over a Unix domain socket.

This affects how FrankenPHP handles requests:

  • In-Process Memory Access: Because the PHP interpreter is embedded directly within the Go process, request and response data pass across memory boundaries rather than through network sockets.
  • Native Superglobal Emulation: FrankenPHP populates standard superglobals like $_SERVER, $_GET, and $_POST for each request inside the worker loop, allowing legacy and non-PSR-7 code to run with fewer modifications.
  • Thread Management: Worker threads run alongside Caddy goroutines, taking advantage of modern multi-threaded server architectures.

RoadRunner: High-Performance Go Process Supervisor

RoadRunner is an application server written in Go and developed by SpiralScout. It manages a pool of separate PHP CLI worker processes, as described in the RoadRunner PHP worker guide. PHP runs outside the Go server process.

The Go server communicates with its PHP workers through Inter-Process Communication (IPC), usually standard input and output pipes or Unix domain sockets. The messages use the binary Goridge protocol.

RoadRunner handles isolation and request delivery as follows:

  • Process Isolation: Each PHP worker is a separate operating system process. RoadRunner's pool replaces a worker that stops; other workers can continue serving requests.
  • Strict PSR-7 HTTP Abstraction: RoadRunner translates incoming HTTP requests into PSR-7 server request objects (Psr\Http\Message\ServerRequestInterface). Workers read requests using a PSR-7 worker adapter, produce PSR-7 response objects, and transmit them back to the Go server.
  • Multiple Worker Types: RoadRunner has worker plugins for HTTP, jobs, gRPC, and Temporal workflows.
An ultrawide monitor on a dark timber desk displays an abstract supervisor pipeline and message queue telemetry with glowing amber and cyan data streams.

What Worker Mode Breaks: The State Problem

Code written for PHP-FPM often assumes that variables disappear when a request ends. Libraries can depend on that cleanup without providing a way to reset themselves. Before moving to worker mode, check where your application stores state, how it handles dropped connections, and whether its memory use grows across requests.

1. Static State and Tenant Leakage

Legacy applications often store the authenticated user in a static property or singleton service. Static properties also make convenient in-memory caches under PHP-FPM, where request shutdown clears them.

In worker mode, a static property keeps its value until something overwrites it. If request A sets a user ID or organization context and request B never clears it, request B uses request A's credentials or tenant data. That can expose one tenant's data to another.

Consider this example of an unsafe authentication context manager:

<?php

declare(strict_types=1);

namespace App\Security;

class UserContext
{
    private static ?int $currentUserId = null;

    public static function setCurrentUserId(int $id): void
    {
        self::$currentUserId = $id;
    }

    public static function getCurrentUserId(): ?int
    {
        return self::$currentUserId;
    }
}

If an unauthenticated request arrives at a worker that previously processed an authenticated request, and the authentication middleware skips setting the user context for guests, UserContext::getCurrentUserId() still returns the previous user's ID.

Pass request-specific state through request attributes, or register it with a lifecycle reset mechanism:

<?php

declare(strict_types=1);

namespace App\Security;

class UserContext
{
    private ?int $currentUserId = null;

    public function setCurrentUserId(?int $id): void
    {
        $this->currentUserId = $id;
    }

    public function getCurrentUserId(): ?int
    {
        return $this->currentUserId;
    }

    public function reset(): void
    {
        $this->currentUserId = null;
    }
}

2. Leaked Connections, Sockets, and Deadlocks

PHP-FPM closes a script's database connections when the request ends unless they use persistent connection flags. In worker mode, connections opened by Doctrine DBAL, Laravel Eloquent, or caching clients such as Redis stay open across requests.

Check for these connection problems:

  • Server-Side Idle Timeouts: Database servers like MySQL and PostgreSQL enforce idle timeouts (wait_timeout in MySQL). If traffic drops and a worker process sits idle for longer than the timeout period, the database server closes the socket. The next request handled by that worker attempts to execute a query on a closed socket, throwing the error "MySQL server has gone away".
  • Uncommitted Transactions: If a request begins a database transaction and encounters an unhandled exception before reaching the commit() or rollback() statement, the transaction remains open. The next request handled by that worker begins executing queries inside the uncommitted transaction of the previous request, holding database locks and corrupting data.
  • Connection Exhaustion: If you run 50 worker processes per server across 4 servers, your application maintains 200 persistent database connections even during zero-traffic periods, requiring adjustments to database connection pool limits.

Check connection health or ping the connection before running queries. At the end of each request, use rollback guards to close any unfinished transactions.

3. Memory Growth and Leaks

Under PHP-FPM, a memory leak that consumes two megabytes per request is largely invisible. When the request ends, the operating system and Zend Engine reclaim all allocated pages.

In worker mode, a retained two-megabyte object graph on every request would add roughly 500 megabytes after 250 requests. That is arithmetic for an example, not a measured leak. Watch resident memory as well as PHP allocations: native libraries and extensions can grow outside memory_limit, and a host can run out of memory before a PHP limit catches the problem.

Look for retained memory in these parts of the application:

  • Monolog and Logging Buffers: Log handlers configured to buffer log records in memory until a flush command is executed will grow indefinitely if the flush call is missed during exception handling.
  • Doctrine Entity Managers: The Doctrine Unit of Work maintains an in-memory identity map of all managed entities. If the entity manager is not cleared between requests via $entityManager->clear(), every entity queried during the lifetime of the worker remains pinned in memory.
  • Event Listeners and Observers: Dynamically registering event listeners inside request-scoped services causes listeners to accumulate on the central event dispatcher across requests.
  • Static Array Append Operations: Appending error messages, metric samples, or breadcrumbs to static class arrays without a corresponding reset step.

Static analysis can help detect unprotected static state and singleton registrations before deployment. Our guide to PHPStan on legacy code describes workflows for adding those checks.

Worked Example: Refactoring State for Long-Running Workers

To illustrate how to adapt application code for worker mode, examine an in-memory metric collector service that records API endpoint execution latencies.

Before: Static Accumulation (Unsafe in Worker Mode)

In this initial implementation, the metric collector uses a static array to hold request timing data. In PHP-FPM, this array holds only the metrics from the single active request. In worker mode, the array grows with every request handled by the worker, causing continuous memory consumption.

<?php

declare(strict_types=1);

namespace App\Monitoring;

class RequestMetrics
{
    /** @var array<string, float> */
    private static array $timings = [];

    public static function record(string $operation, float $durationMs): void
    {
        self::$timings[$operation] = $durationMs;
    }

    /** @return array<string, float> */
    public static function getTimings(): array
    {
        return self::$timings;
    }
}

When evaluated in worker mode, this code produces two major bugs:

  1. Memory grows continuously as new unique operation keys are added to self::$timings.
  2. A request inspecting getTimings() receives timing data recorded during previous requests by other clients.

After: Request-Scoped Instance with Lifecycle Reset

In the refactored version, the static state is removed. The service is instantiated within the dependency injection container and implements an explicit reset interface. The worker kernel invokes reset() after every completed request, clearing the internal array and freeing memory.

<?php

declare(strict_types=1);

namespace App\Monitoring;

class RequestMetrics
{
    /** @var array<string, float> */
    private array $timings = [];

    public function record(string $operation, float $durationMs): void
    {
        $this->timings[$operation] = $durationMs;
    }

    /** @return array<string, float> */
    public function getTimings(): array
    {
        return $this->timings;
    }

    public function reset(): void
    {
        $this->timings = [];
    }
}

The refactored code adds no new business requirements or external dependencies. It replaces the persistent static array with an instance property and provides an explicit reset method that the worker runtime executes at the end of each request cycle.

A dual-screen workstation displays a side-by-side comparative diagnostics view contrasting an accumulating red memory curve with a green cyclical reset pattern.

Framework Support and Ecosystem Reset Adapters

Symfony and Laravel provide ways to reset internal state between worker requests.

Symfony

Symfony provides Symfony\Contracts\Service\ResetInterface for services that need cleanup. The worker integration must call the container reset between requests; implementing the interface alone does not make a custom loop safe.

Check the reset behavior of services that hold request data, including security context, logging buffers, and Doctrine's identity map. FrankenPHP documents a Symfony worker integration; for RoadRunner, choose a maintained framework bridge and verify its reset hooks before carrying traffic.

Laravel Octane

Laravel Octane is the official integration for running Laravel applications on worker runtimes. It supports both FrankenPHP and RoadRunner.

Octane manages state isolation by creating a fresh sandbox for each incoming request:

  • The root application container boots once when the worker starts.
  • For each incoming request, Octane clones the service container into a request-scoped sandbox.
  • Request-specific bindings, such as the current authenticated user, configuration overrides, and session instances, are registered exclusively within the sandbox.
  • When the request completes, Octane tears down the sandbox, executes registered termination listeners, and flushes database query logs.

Octane offers a worker request limit so teams can recycle workers. That limit is a fallback for retained state, not a substitute for resetting request data.

Minimal Configurations: PHP-FPM, FrankenPHP, and RoadRunner

The following minimal production configurations show how each runtime sets up its worker pool.

1. PHP-FPM Configuration (www.conf)

PHP-FPM pool directives are configured in pool definition files, typically located at /etc/php/8.4/fpm/pool.d/www.conf. Full configuration options are listed in the PHP-FPM configuration documentation.

[www]
user = www-data
group = www-data
listen = /run/php/php8.4-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660

pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 15
pm.max_requests = 1000

request_terminate_timeout = 60s
catch_workers_output = yes
clear_env = no

Two directives control pool size and recycling:

  • pm = dynamic: Adjusts the number of child processes based on traffic demand.
  • pm.max_requests = 1000: Instructs the master process to restart each worker child after it has served 1,000 requests. This acts as an automated safety net to prevent slow memory leaks from consuming host RAM.

2. FrankenPHP Configuration (Caddyfile)

FrankenPHP uses Caddy's configuration format. This smoke test starts eight worker threads. Replace the handler with your framework's documented worker integration before using it for application traffic. The global max_requests option is currently marked experimental in the FrankenPHP configuration reference.

{
    frankenphp {
        max_requests 1000
    }
}

example.com {
    root * /var/www/html/public
    encode zstd gzip

    php_server {
        worker /var/www/html/public/worker.php 8
    }
}

The corresponding public/worker.php demonstrates the request loop on PHP 8.2 or later:

<?php

declare(strict_types=1);

$handler = static function (): void {
    header('Content-Type: text/plain; charset=utf-8');
    echo 'OK';
};

while (\frankenphp_handle_request($handler)) {
    gc_collect_cycles();
}

3. RoadRunner Configuration (.rr.yaml)

RoadRunner configurations use YAML syntax. This .rr.yaml file starts eight PHP workers and recycles each after 1,000 jobs. The RoadRunner worker pool reference documents num_workers, max_jobs, and the supervisor settings.

version: '3'

server:
  command: "php worker.php"
  relay: "pipes"

http:
  address: "0.0.0.0:8080"
  pool:
    num_workers: 8
    max_jobs: 1000
    allocate_timeout: 30s
    destroy_timeout: 30s
    supervisor:
      watch_tick: 1s
      ttl: 0s
      idle_ttl: 300s
      max_worker_memory: 256

Install spiral/roadrunner-http and nyholm/psr7 with Composer. This worker.php is a PHP 8.2 or later smoke test that uses RoadRunner's PSR-7 adapter. Replace its response body with your application's PSR-7 handler and reset logic:

<?php

declare(strict_types=1);

require_once __DIR__ . '/vendor/autoload.php';

use Nyholm\Psr7\Factory\Psr17Factory;
use Nyholm\Psr7\Response;
use Spiral\RoadRunner\Http\PSR7Worker;
use Spiral\RoadRunner\Worker;

$worker = Worker::create();
$factory = new Psr17Factory();
$psr7Worker = new PSR7Worker($worker, $factory, $factory, $factory);

while (true) {
    try {
        $request = $psr7Worker->waitRequest();
        if ($request === null) {
            break;
        }
    } catch (\Throwable $e) {
        $psr7Worker->respond(new Response(400, [], 'Bad Request'));
        continue;
    }

    try {
        $psr7Worker->respond(new Response(200, ['Content-Type' => 'text/plain'], 'OK'));
    } catch (\Throwable $e) {
        $psr7Worker->respond(new Response(500, [], 'Internal Server Error'));
    } finally {
        gc_collect_cycles();
    }
}

How to Measure the Difference Yourself

An OK response tests the server path, but it cannot predict the gain for a real application. Use the smoke tests above to confirm configuration, then benchmark the same application endpoint under each runtime. Do not treat a published benchmark as a forecast for your workload.

Production applications spend time querying databases, calling external services, and processing business rules. Amdahl's Law limits the gain from worker mode: removing bootstrap work can only save the time the application spent on that work.

Use a controlled benchmark to measure the gain for your application.

1. Isolate Database and External I/O from Runtime Bootstrap

Run your benchmark against two distinct endpoints:

  • A Lightweight Endpoint: A health check or token validation endpoint that performs no database queries or third-party HTTP calls. This endpoint isolates pure framework routing, dependency injection instantiation, and response serialization.
  • A Realistic Business Endpoint: An endpoint that executes representative database queries, deserializes JSON payloads, and runs domain validation logic.

Compare the endpoints to separate framework startup time from time spent waiting on storage and network I/O. A change in the lightweight endpoint with little change in the business endpoint suggests that database or network work dominates the latter. Record your own latency and throughput results; this article supplies no benchmark numbers.

2. Standardize Hardware and Runtime Environment

Avoid benchmarking on a developer laptop. Background processes, thermal throttling, and operating system scheduling can make results vary widely between runs.

  • Deploy the application to a dedicated staging server or container environment with fixed CPU and memory reservations.
  • Run load generation tools from a separate virtual machine on the same low-latency local network to avoid network latency noise and CPU contention between the client and server.
  • Ensure OPcache is fully enabled and preloaded identically across all runtimes.

3. Generate Realistic Load with wrk or k6

Use a load testing tool such as wrk or k6 to measure response latencies across increasing concurrency levels.

An example wrk execution using 8 threads and 100 concurrent connections over a two-minute test run:

wrk -t8 -c100 -d120s --latency http://10.0.1.20:8080/api/v1/health

Record more than requests per second (RPS):

  • Percentile Latency Distribution: Inspect median (p50), 95th percentile (p95), and 99th percentile (p99) latencies. Compare them across several runs, including the cold start and steady state.
  • CPU Utilization at Peak Concurrency: Check how much CPU capacity is consumed to deliver a given throughput. Repeated framework boot can cost CPU, but the size of that cost depends on the application.
  • Memory Stability Over Time: Monitor process memory using tools like htop or Prometheus node exporter over 50,000 requests. If worker memory increases monotonically rather than stabilizing at a plateau, your application contains a memory leak that must be resolved before production deployment.

Use the tools covered in our guide to PHP profiling to measure memory deltas and find execution hot paths under realistic load.

Write down the test procedure so deployment teams can reproduce the measurements in other environments. Clear technical documentation standards help keep those instructions consistent.

Common Mistakes When Adopting Worker Mode

Check these patterns in application code and vendor dependencies before changing runtimes:

1. Using exit() or die() in Controllers

Under PHP-FPM, exit() and die() end the current request. In a persistent worker script, either can end the worker process, which the supervisor must replace. Return a response or throw an exception handled inside the request loop instead.

2. Relying on Header and Cookie Global Functions

Framework response objects are the safest place to set headers and cookies when a bridge expects them. A custom FrankenPHP worker can also use header() and echo inside its request handler, as the smoke test above does; FrankenPHP resets request headers and output between calls. A RoadRunner PSR-7 worker should send a response object through its adapter.

3. Missing Worker Recycling Limits

Configure worker recycling even if you have found no leaks in your application or its dependencies. Use max_requests in FrankenPHP, max_jobs in RoadRunner, and pm.max_requests in PHP-FPM. Restarting workers after 1,000 or 5,000 requests keeps minor leaks from growing unchecked.

A curved monitor in a dark monitoring room displays circular worker process recycling dials and memory threshold meters with luminous status rings.

4. Overlooking Open File Descriptors

Creating temporary files on disk or opening file handles with fopen() without matching fclose() calls inside finally blocks leaks file descriptors. Operating systems enforce per-process file descriptor limits (ulimit -n). When a persistent worker exhausts its allocated descriptors, subsequent file reads and socket connections fail with "Too many open files" errors.

Decision Matrix: When to Migrate and When to Stay on FPM

Choose a runtime based on where your application spends time and how much state it retains between requests.

PHP-FPM

  • Architecture: Pre-forked FastCGI pool.
  • State isolation: PHP request state is reset.
  • Framework boot: Bootstraps on every request.
  • HTTP protocols: Relies on an upstream web server.
  • Code safety: Forgiving of legacy patterns.
  • Deployment: Standard OS packages.
  • Memory risk: Native or persistent allocations can grow.

FrankenPHP

  • Architecture: Caddy server with embedded PHP.
  • State isolation: Persistent in-memory state.
  • Framework boot: Bootstraps once per worker.
  • HTTP protocols: Native HTTP/1.1, HTTP/2, and HTTP/3.
  • Code safety: Requires clean, stateless code.
  • Deployment: Single binary or Docker container.
  • Memory risk: Requires reset hooks and recycling.

RoadRunner

  • Architecture: Go supervisor with CLI workers.
  • State isolation: Persistent in-memory state.
  • Framework boot: Bootstraps once per worker.
  • HTTP protocols: Native HTTP/1.1, HTTP/2, and gRPC.
  • Code safety: Requires clean, stateless code.
  • Deployment: Single Go binary with PHP CLI.
  • Memory risk: Requires reset hooks and recycling.

Stay on PHP-FPM If:

  • You maintain a large legacy codebase containing widespread global variables, singletons, and static utility properties.
  • You run content management systems like WordPress or Drupal with numerous community plugins that assume request termination.
  • Your application response time is heavily dominated by slow database queries or remote third-party API calls, making framework bootstrap overhead negligible.
  • Your engineering team does not have the capacity to audit vendor libraries for state retention or debug subtle cross-request data leaks.

Move to FrankenPHP or RoadRunner If:

  • You run modern, containerized applications built on Symfony, Laravel Octane, or API Platform.
  • Your measured endpoints spend enough time in framework boot that keeping the application resident improves latency or CPU use.
  • You can test request isolation and memory stability under a representative load.
  • You need features provided by a specific server, such as FrankenPHP's Caddy integration or RoadRunner's gRPC workers.

Frequently Asked Questions

Can I run WordPress or Drupal in worker mode?

Start with each CMS's supported deployment mode. FrankenPHP has a classic mode and documents a WordPress integration, but enabling a generic persistent worker around an existing plugin stack requires an audit of global and static state. A successful page load does not prove that later requests are isolated.

Does worker mode replace OPcache?

No. Enable both in production. OPcache keeps precompiled PHP bytecode in shared memory so the engine does not have to parse source files from disk on every invocation. Worker mode keeps the application objects, compiled service containers, and routed application state in memory too.

What happens if an unhandled exception occurs in worker mode?

A worker can catch a \Throwable raised by application code, send an error response, reset request-scoped services, and continue. If the process exits or crashes, the supervisor replaces it according to its pool configuration. Test both paths before deployment; a failed reset after an exception can leave stale state in the next request.

Is FrankenPHP faster than RoadRunner?

Neither is universally faster. FrankenPHP embeds PHP in Caddy; RoadRunner sends requests through IPC to separate PHP CLI processes. Compare them with the same application, PHP version, OPcache settings, worker count, and load profile. Choose from your measured latency, CPU use, memory behavior, and deployment needs.