Skip to content
Tutorials Center
My learning

Topics

Lesson 126 of 147 ยท Modern PHP and Ecosystem

Long-Running PHP: Workers, Swoole and RoadRunner

Learn how persistent PHP workers differ from PHP-FPM, why memory leaks and shared state bite, and how event loops, Swoole and RoadRunner keep an app alive.

Classic PHP has a famously simple life cycle: a request arrives, PHP boots, your script runs, the response is sent and everything is thrown away. Variables, objects, open connections, even the compiled application state all disappear. That "shared nothing" design is why PHP is so forgiving. A leaked variable or a forgotten static property can only hurt the one request that created it.

The price is repeated work. A framework such as Laravel or Symfony may spend several milliseconds on every request just to load configuration, build a service container and register routes, long before your own code runs. Long-running PHP turns the model around: you start a worker process once, boot the application once, and let that process serve thousands of requests. This lesson explains how that works, what can go wrong, and which tools (Swoole, RoadRunner, FrankenPHP, plain CLI workers) you will meet.

Two life cycles

Compare the two models side by side:

flowchart LR
  subgraph FPM["PHP-FPM: one request, one clean slate"]
    A1["Request"] --> B1["Boot app"] --> C1["Handle"] --> D1["Free everything"]
  end
  subgraph W["Persistent worker: boot once, loop forever"]
    B2["Boot app (once)"] --> L{"Wait for request"}
    L --> H["Handle"] --> R["Reset request state"] --> L
  end

PHP-FPM repeats the boot step for every request; a persistent worker pays for it once and loops.

With PHP-FPM (FastCGI Process Manager), the usual production setup behind nginx or Apache, a pool of worker processes is kept alive, but each request still starts from scratch. PHP's request shutdown frees all user variables, resets static properties and closes resources. The process lives on; your application state does not. (OPcache keeps compiled bytecode in shared memory, which is why FPM is fast enough for most sites.)

In a persistent worker your own PHP code runs a while (true) loop. The application is built before the loop. Inside the loop you receive a request, produce a response and go back to waiting. Nothing resets unless you reset it yourself.

The gains can be large for framework-heavy apps: no repeated bootstrap, warm caches in memory, and connections (database, Redis) that stay open between requests. The cost is that you now own the life cycle. Everything PHP used to clean up for you is your job.

The loop in plain PHP

The smallest long-running program is just a loop. Here is a worker that boots an application once and then handles a queue of simulated requests. Because the editor has no web server, requests are plain arrays:

PHP A worker loop: boot once, handle many

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In a real worker, the foreach becomes while ($request = $server->waitForRequest()), and the tool you use (RoadRunner, Swoole, FrankenPHP) supplies the request object. The shape stays the same.

The big danger: state that survives

Once the process outlives the request, anything stored outside a function's local scope sticks around. Three places cause nearly all long-running bugs:

  1. Static properties and global variables. A static cache that only grows is a memory leak. A static $currentUser is worse: it is a security bug if the next request reads the previous user.
  2. Singletons and container services that hold request data. A service that stores "the current request" or "the logged-in user" on a property will leak that data into the next request.
  3. Superglobals. $_SERVER, $_GET, $_SESSION and friends are populated by the SAPI per request in FPM. In a worker, the server tool either fills them for you or provides its own request object. Do not assume they are fresh.

This demo makes the problem visible. The LeakyCounter keeps a static list; the SafeCounter keeps data only in local variables:

PHP Static state leaks between requests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The second request, from an anonymous visitor, was treated as alice. In production that is a data breach. The rule of thumb is simple: anything that belongs to one request must be created at the start of that request and be unreachable afterwards. Pass a context object down through your call chain instead of stashing it in a static.

Frameworks that support workers (Laravel Octane, Symfony's Runtime component with worker mode) ship "reset" hooks for their own services. Your own code, and third-party packages that were written for FPM, are the usual source of leaks. Audit every static property and every singleton.

Memory leaks and recycling

Even without static state, PHP can leak in a long-lived process. Circular references are normally cleaned by the garbage collector, but large caches, event listeners that are never removed, and growing arrays are not. In FPM a leak of a few kilobytes per request is invisible. In a worker that serves a million requests it is a gigabyte.

Workers therefore take a defensive approach: recycle them. After N requests, or after the memory limit is near, the worker exits and the supervisor starts a fresh one. RoadRunner calls this max_jobs and ttl; Octane has --max-requests; PHP-FPM itself has pm.max_requests. You can also watch memory yourself with memory_get_usage() and memory_get_peak_usage():

PHP Measuring a leak and recycling the worker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Recycling is a safety net, not a fix. Find the leak (bounded caches, removing listeners, unset() on big arrays) and use the net as insurance.

Event loops and concurrency

A worker that handles one request at a time wastes time whenever it waits for a database or an HTTP call. An event loop lets one process switch to other work while waiting. This is the idea behind Node.js, and PHP has it too: Swoole, ReactPHP and AMPHP are event-loop runtimes, and since PHP 8.1 Fibers make it easy to write waiting code in a straight-line style.

sequenceDiagram
  participant L as Event loop
  participant A as Task A
  participant B as Task B
  L->>A: run
  A-->>L: waiting for I/O (suspend)
  L->>B: run
  B-->>L: waiting for I/O (suspend)
  L->>A: I/O finished, resume
  A-->>L: done
  L->>B: I/O finished, resume
  B-->>L: done

Tasks hand control back to the loop while they wait, so a single process interleaves many requests.

To see the mechanism without real I/O, here is a tiny scheduler built on Fibers. It uses a virtual clock: a task "sleeps" by suspending with its wake-up time, and the loop resumes the task with the earliest time. Nothing actually waits, so the output is instant and deterministic:

PHP Two tasks sharing one thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both "requests" finish after 400 ms of virtual time, not 800, because while A waits, B runs. Real runtimes do exactly this with sockets instead of a virtual clock. The trade-off is that a task that blocks (a plain sleep(), a synchronous file_get_contents() on a slow URL, a heavy CPU loop) stalls every other task on that loop. Event-loop code must use the loop's own non-blocking I/O.

The tools you will meet

Tool What it is Notes
PHP-FPM Process pool with a clean slate per request Default for most hosting; no leaks between requests
RoadRunner A Go application server that talks to PHP worker processes over pipes Plain PHP workers, no extension; also does queues, gRPC, WebSockets
Swoole / OpenSwoole PHP extension with a built-in async server, coroutines and timers Fastest option; needs the extension and coroutine-aware libraries
FrankenPHP A Caddy-based server embedding PHP, with an optional worker mode HTTP/2/3, automatic HTTPS, worker mode boots the app once
ReactPHP / AMPHP Pure-PHP event-loop libraries No extension; you write async code explicitly
CLI workers A php worker.php script under Supervisor or systemd Ideal for queue consumers and schedulers

Frameworks hide much of this: Laravel Octane runs a Laravel app on Swoole, RoadRunner or FrankenPHP, and Symfony's Runtime component offers worker-mode runtimes. For these, the earlier rules still apply. Octane tells you to avoid injecting the request or container into singletons, and to reset anything request-bound.

A RoadRunner worker is typically this small:

PHP
<?php
use Nyholm\Psr7\Response;
use Nyholm\Psr7\Factory\Psr17Factory;
use Spiral\RoadRunner\Http\PSR7Worker;
use Spiral\RoadRunner\Worker;

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

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

// Boot the application here, once.

while ($request = $worker->waitRequest()) {
    try {
        $worker->respond(new Response(200, [], 'Hello from a worker'));
    } catch (Throwable $e) {
        $worker->getWorker()->error((string) $e);
    }
}

That block is read-only because the editor can't run a server. It shows the same loop you wrote earlier.

Practical rules for long-running code

  • Reset on every request. Create request-scoped objects fresh; clear or re-bind them in a reset hook.
  • Bound every cache. Use a maximum size or time-to-live, or store the data in Redis.
  • Reconnect gracefully. Database connections can time out while the worker idles; check and reconnect.
  • Handle errors without dying. A fatal error kills the worker, so log it and let the supervisor restart it.
  • Be careful with exit/die. In a worker, they end the whole process, not just the request.
  • Test under repetition. Send the same requests thousands of times and watch memory.
  • Start with FPM. Move to workers when profiling shows the bootstrap cost matters. See Performance first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main difference between PHP-FPM and a persistent worker?

    FPM discards user-level state after each request, while a worker keeps its objects alive and loops, which is both the speed advantage and the source of leaks.
  2. 2. A static property Auth::$user is set during request 1. What can happen in a persistent worker?

    Static properties live as long as the process. Nothing resets them unless you do, so data leaks across requests.
  3. 3. Why do worker managers recycle workers after a number of requests?

    Recycling bounds how far a leak can grow. It is a safety net, not a replacement for fixing the leak.
  4. 4. What happens if one task on an event loop makes a blocking call such as a synchronous sleep()?

    An event loop runs on one thread. A blocking call stops the thread, so no other task can run until it returns.

Summary

  • PHP-FPM gives every request a clean slate; persistent workers boot once and loop, saving bootstrap time at the cost of managing state yourself.
  • Static properties, singletons holding request data and unbounded caches are the main sources of cross-request leaks and security bugs.
  • Recycle workers after N requests or a memory threshold, but still fix the leaks.
  • An event loop interleaves tasks that wait for I/O; Fibers make such code easy to write, and blocking calls stall the whole loop.
  • RoadRunner, Swoole/OpenSwoole and FrankenPHP are the main runtimes; Laravel Octane and Symfony's Runtime build on them.
  • Start with PHP-FPM and move to workers only when measurements justify it.

Next: Static Analysis and Code Quality