Skip to content

PHP 8.1 Fibers: cooperative concurrency without a framework

How PHP 8.1 Fibers work, where they fit in production workloads, and how to use them for cooperative concurrency without an event loop framework.

PHP 8.1 Fibers add cooperative concurrency as a first-class language primitive — not a library feature, not a generator hack, but a proper coroutine mechanism built into the runtime. Fibers are not async in the Node.js or Go sense: they do not make I/O non-blocking on their own, and they do not spawn OS threads. What they do is give you explicit yield points where a running function can pause, hand control back to a scheduler, and be resumed later with a value. This article explains the mechanics, the real production use cases, and how to build a minimal fiber scheduler without pulling in a full event loop library.

How to verify

Confirm Fibers are available:

php -r 'echo PHP_VERSION . PHP_EOL;'
# Must be >= 8.1.0

php -r 'echo class_exists(Fiber::class) ? "Fibers available\n" : "Not available\n";'

# Run a quick smoke test
php -r '
$fiber = new Fiber(function (): void {
    $v = Fiber::suspend("first");
    echo "Fiber resumed with: $v\n";
});
$yielded = $fiber->start();
echo "Main got: $yielded\n";
$fiber->resume("hello");
'

Expected output:

Main got: first
Fiber resumed with: hello

What’s happening

A Fiber wraps a callable. When you call $fiber->start(), the callable begins executing in the Fiber’s own stack. When the callable calls Fiber::suspend($value), execution returns to the code that called start() (or resume()), and $value is the return of start()/resume(). The Fiber is now suspended — its stack is intact, its local variables are preserved. When you call $fiber->resume($value), the Fiber wakes up and $value is the return of the Fiber::suspend() call inside the Fiber.

This is cooperative concurrency: the Fiber decides when to yield. The scheduler (your code, or a library’s event loop) decides when to resume which Fiber. PHP’s runtime handles the stack switching — you are not doing it with generators or callback nesting.

What Fibers do not do on their own:

  • Make curl_exec(), file_get_contents(), or PDO queries non-blocking. The OS will still block the thread while waiting for I/O.
  • Provide event-driven I/O like Node.js. You need either a non-blocking I/O library (ReactPHP, Revolt, Amp) or PHP extensions that provide async I/O (openswoole, RoadRunner) for that.

What Fibers are genuinely useful for:

  • Building cooperative task schedulers for CPU-bound workloads that you want to interleave.
  • Implementing generator-based or coroutine-based APIs at the library level (Revolt/Amp use Fibers internally as of their v3 releases).
  • Managing complex state machines where explicit yield points are cleaner than callbacks or promise chains.
  • Long-running CLI processes that need to poll multiple data sources in a round-robin without blocking.

The procedure

  1. Build a minimal fiber scheduler.

    The following scheduler runs a list of fibers in round-robin order until all are complete:

    <?php
    
    class FiberScheduler
    {
        /** @var SplQueue<Fiber> */
        private SplQueue $queue;
    
        public function __construct()
        {
            $this->queue = new SplQueue();
        }
    
        public function add(Fiber $fiber): void
        {
            $this->queue->enqueue($fiber);
        }
    
        public function run(): void
        {
            while (!$this->queue->isEmpty()) {
                $fiber = $this->queue->dequeue();
    
                if ($fiber->isStarted()) {
                    $fiber->resume();
                } else {
                    $fiber->start();
                }
    
                // If the fiber suspended (not terminated), re-queue it
                if ($fiber->isSuspended()) {
                    $this->queue->enqueue($fiber);
                }
            }
        }
    }
  2. Use the scheduler for interleaved CPU work.

    $scheduler = new FiberScheduler();
    
    // Task 1: process a batch of records
    $scheduler->add(new Fiber(function (): void {
        foreach (range(1, 1000) as $i) {
            // Do work for one record
            expensive_transform($i);
            // Yield every 100 records to let other fibers run
            if ($i % 100 === 0) {
                Fiber::suspend();
            }
        }
        echo "Task 1 done\n";
    }));
    
    // Task 2: poll an external endpoint
    $scheduler->add(new Fiber(function (): void {
        $attempts = 0;
        while ($attempts < 10) {
            $result = check_job_status(); // blocking HTTP call
            if ($result === 'done') break;
            $attempts++;
            Fiber::suspend(); // yield, let other fibers run while we wait
        }
        echo "Task 2 done after $attempts attempts\n";
    }));
    
    $scheduler->run();
  3. Pass values between the scheduler and a fiber.

    Fibers can receive values from the scheduler and send values out:

    $fiber = new Fiber(function (): string {
        $chunk1 = Fiber::suspend("ready for chunk 1");
        $chunk2 = Fiber::suspend("ready for chunk 2");
        return "processed: $chunk1 + $chunk2";
    });
    
    $msg1 = $fiber->start();          // "ready for chunk 1"
    $msg2 = $fiber->resume("alpha");  // "ready for chunk 2"
    $fiber->resume("beta");           // fiber finishes
    
    echo $fiber->getReturn();         // "processed: alpha + beta"
  4. Integrate with Revolt for non-blocking I/O.

    For production workloads requiring genuine async I/O, use Revolt (the event loop used by Amp v3 and ReactPHP v3):

    composer require revolt/event-loop
    use Revolt\EventLoop;
    
    EventLoop::queue(function (): void {
        // This runs in a fiber managed by Revolt's event loop
        $fiber = Fiber::getCurrent();
        // ... do cooperative work, suspend as needed
    });
    
    EventLoop::run();

    Revolt schedules fibers on a libuv or uv-extension event loop when available, falling back to a select-based loop. All I/O callbacks run inside fibers automatically.

  5. Handle fiber exceptions correctly.

    Exceptions thrown inside a fiber propagate when the fiber is started or resumed:

    $fiber = new Fiber(function (): void {
        throw new RuntimeException("fiber failure");
    });
    
    try {
        $fiber->start();
    } catch (RuntimeException $e) {
        echo "Caught: " . $e->getMessage() . "\n";
    }
    // $fiber->isTerminated() === true, but not via getReturn()

    You can also throw an exception into a suspended fiber using $fiber->throw(new SomeException()).

Common pitfalls

  • Fibers do not make blocking I/O non-blocking. A curl_exec() inside a fiber will block the entire PHP process for the duration of the HTTP request, starving all other fibers. Use non-blocking I/O libraries or the openswoole/RoadRunner extensions for actual async I/O.
  • Memory per fiber scales with stack depth. Each fiber maintains its own call stack. A scheduler with 10,000 fibers each holding deep call stacks can consume significant memory. Profile with large concurrency before deploying.
  • Fiber::getCurrent() returns null outside a fiber context. Library code that needs to work both in and out of a fiber context must guard against null. This is a common source of bugs in code written to support both synchronous and fiber-based execution.
  • Fibers are not threads — shared state is still shared. If two fibers read and modify the same global variable or static property, race conditions are possible at yield points. The cooperative nature means races only happen at suspend() calls, but that is still enough to corrupt state.
  • The fiber’s getReturn() throws a FiberError if the fiber has not finished. Always check $fiber->isTerminated() before calling getReturn().

PHP Fibers are a sophisticated tool for application-layer concurrency that most PHP developers will interact with through frameworks (Amp, ReactPHP) rather than directly. For operators managing PHP processes at the runtime level, understanding the fiber execution model is valuable for diagnosing memory usage patterns in long-running workers. Stack Harbor’s managed operations service supports workloads using ReactPHP, Amp, RoadRunner, and Swoole alongside traditional PHP-FPM.