Skip to content
Tutorials Center
My learning

Topics

Lesson 107 of 147 ยท Advanced PHP

Fibers and Asynchronous PHP

Learn PHP 8.1 Fibers - start, suspend and resume, passing values and exceptions, a tiny scheduler with async sleep, and how ReactPHP, Amp and Revolt use them.

A fiber (added in PHP 8.1) is a block of code with its own call stack that can pause itself in the middle of any function call and be resumed later, right where it left off. While one fiber is paused, the rest of your program carries on. That's the missing piece PHP needed for comfortable asynchronous programming: code that starts a slow operation (a network request, a database query, a timer), lets other work run while it waits, and continues when the result is ready.

Fibers don't make PHP multi-threaded. Only one piece of code runs at any moment; fibers simply let you switch between tasks at chosen points. This is called cooperative multitasking. In practice you'll rarely use the Fiber class directly. Libraries like Revolt, Amp and ReactPHP use it inside their event loops so that your code can look completely ordinary. This lesson shows the raw mechanics, builds a tiny scheduler so you can see how those libraries work, and then shows what real async code looks like.

The basic moves: start, suspend, resume

You create a fiber from any callable. Nothing runs until you call start(). Inside the fiber, Fiber::suspend() pauses it and returns control to whoever started or resumed it. resume() continues the fiber from the paused point:

PHP Start, suspend and resume

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.

Control bounces back and forth: main, fiber, main, fiber, main. A fiber has four states you can check: not started yet (isStarted() is false), running, suspended (isSuspended()), and terminated (isTerminated()). Once it has returned, getReturn() gives you the return value.

If you're coming from Generators, this looks familiar. The crucial difference is where you can pause:

  • A generator can only yield in the generator function's own body. If a helper function wants to pause, every caller in between must be a generator too (yield from all the way up).
  • A fiber can call Fiber::suspend() from any depth of ordinary function calls. The functions in between don't know or care; they're normal functions with normal return types.

That's what lets async libraries offer an ordinary-looking $response = $client->get($url); that secretly suspends the current fiber while waiting for the network.

PHP Suspending from deep inside a call

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.

Passing values in and out

Values travel in both directions, just like with a generator's send():

Call Direction What happens
$fiber->start(...$args) main to fiber Arguments go to the fiber's callable
Fiber::suspend($value) fiber to main $value is returned by the start() or resume() call that was running
$fiber->resume($value) main to fiber $value becomes the return value of the paused Fiber::suspend()
$fiber->throw($exception) main to fiber The exception is thrown at the paused Fiber::suspend()
$fiber->getReturn() fiber to main The fiber's return value, after it terminates

throw() is how an async library reports a failed operation: the fiber that was waiting for it sees an ordinary exception at the line where it suspended, and can handle it with a normal try/catch:

PHP Errors thrown into a fiber

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.

FiberError is thrown for invalid moves: starting a fiber twice, resuming one that isn't suspended, or calling Fiber::suspend() outside any fiber. Fiber::getCurrent() returns the running fiber, or null in the main program, so library code can check where it is.

A tiny scheduler

One fiber is a curiosity; many fibers plus a scheduler is concurrency. The scheduler (also called an event loop) keeps a queue of fibers and runs each one until it suspends, then moves on to the next. Here three tasks take turns, each giving up control after every step:

PHP Round-robin tasks

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 steps interleave: each task does a bit of work, yields, and waits for its next turn. The SplQueue from Iterators and the SPL is a natural fit for the ready queue.

Async sleep: waiting without blocking

Round-robin alone doesn't save time. The real win comes when tasks wait for something. A blocking usleep() freezes everything, but an async delay() can suspend just the current fiber and ask the scheduler to wake it later. While it's asleep, the other fibers run. Real event loops do the same with network sockets instead of timers:

PHP Concurrent waiting with an event loop

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.

All three "requests" start at once, finish in order of their duration, and the whole run takes about as long as the slowest one (150 ms) instead of the sum of all three (300 ms). The timestamps are rounded to the nearest 50 ms, because exact timings vary slightly between runs.

Look at fakeRequest(). It calls Loop::delay() and continues on the next line, exactly like blocking code. There's no callback, no promise and no yield. That's the whole idea behind fiber-based async PHP: the waiting is hidden inside library functions, and your code stays straight-line.

Fibers only help if everything that waits cooperates. A normal sleep(), file_get_contents('https://...'), PDO::query() or curl_exec() blocks the entire process, all fibers included. Async libraries provide non-blocking replacements (HTTP clients, MySQL and Redis drivers, file and process APIs) that suspend the fiber and let the event loop watch the socket.

Fibers in the real world: Revolt, Amp and ReactPHP

Writing your own event loop is a good exercise, but production code uses a library. The PHP async ecosystem has largely standardized on Revolt, a shared event loop that Amp (v3) and ReactPHP both build on, so their packages can work together.

With Amp v3, async code is plain code. async() starts a function in a new fiber and returns a Future; await() suspends until it has a value:

PHP
<?php
// composer require amphp/http-client
use Amp\Http\Client\HttpClientBuilder;
use Amp\Http\Client\Request;
use function Amp\async;
use function Amp\Future\await;

$client = HttpClientBuilder::buildDefault();

$futures = [];
foreach (['https://example.com/a', 'https://example.com/b'] as $url) {
    $futures[$url] = async(function () use ($client, $url) {
        $response = $client->request(new Request($url));   // suspends this fiber only
        return $response->getBody()->buffer();
    });
}

$bodies = await($futures);   // both requests ran concurrently

ReactPHP has used promises and callbacks since long before fibers, and its react/async package adds await() on top of fibers so you can write the same straight-line style:

PHP
<?php
// composer require react/http react/async
use React\Http\Browser;
use function React\Async\await;

$browser = new Browser();
$response = await($browser->get('https://example.com/'));
echo $response->getStatusCode();

These packages need Composer and network access, so they can't run in our editor. The tiny Loop class above follows the same principles in miniature: a queue of timers and sockets, fibers that suspend while they wait, and a loop that resumes them.

When async PHP makes sense

Traditional PHP is request-based: PHP-FPM gives each request its own process (see How PHP Works), so concurrency comes from running many processes, and that works very well for ordinary websites. Fibers shine elsewhere:

  • Long-running services: WebSocket and chat servers, message-queue consumers, proxies, real-time dashboards.
  • Fan-out work: calling ten APIs at once and combining the results, crawling, bulk imports.
  • High-concurrency servers built on runtimes such as AMPHP's HTTP server, ReactPHP or extensions like Swoole and its fork OpenSwoole (which have their own coroutine model).

For CPU-heavy work, fibers don't help at all: only one fiber runs at a time, on one CPU core. Use separate processes (queues and workers, or pcntl_fork() in command-line PHP) for that.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Fiber::suspend('x') return inside the fiber?

    'x' goes out to the code that called start() or resume(). When the fiber is resumed, the value passed to resume() becomes the result of Fiber::suspend().
  2. 2. What is the key difference between fibers and generators?

    Fibers have their own call stack, so a helper function many calls deep can suspend. Generators need yield (or yield from) at every level.
  3. 3. Three fiber tasks each call a blocking sleep(1). How long does running all three take?

    Fibers are cooperative. A blocking call never hands control back to the scheduler, so the sleeps happen one after another. Async libraries provide non-blocking delay() functions instead.
  4. 4. What happens when you call resume() on a fiber that has already terminated?

    Starting twice, resuming a non-suspended fiber and suspending outside a fiber all throw FiberError.
  5. 5. How does an async library report a failed network request to the fiber that was waiting?

    Fiber::throw() raises the exception inside the fiber at the suspension point, where ordinary try/catch code can handle it.

Summary

  • A Fiber (PHP 8.1) is code with its own call stack that can pause with Fiber::suspend() and continue with resume(). Nothing runs until start().
  • Values flow both ways: start($args), suspend($out), resume($in), throw($e) and getReturn(). Invalid moves throw FiberError.
  • Unlike generators, fibers can suspend from deep inside ordinary functions, which lets async code look like blocking code.
  • A scheduler (event loop) resumes fibers in turn, or when their timer or socket is ready. Waiting tasks overlap, so total time approaches the slowest task, not the sum.
  • Fibers are cooperative and single-threaded: blocking calls block everything, and CPU-heavy work gains nothing.
  • Use Revolt-based libraries (Amp v3, ReactPHP with react/async) for real async I/O, mainly in long-running services and fan-out workloads.

Next: Dates and Times