PHP Fibers: Cooperative Concurrency for WordPress Background Tasks

PHP Fibers, parallel HTTP requests and background work in WordPress

PHP 8.1 added Fibers, and articles promise “concurrency for WordPress” since then. A Fiber is a function that can pause itself and be resumed later; it does not run in parallel with anything. Without an event loop that does non-blocking I/O while fibers wait, they do not make WordPress faster. For the two problems people actually have, slow requests to several APIs and heavy work during a page view, WordPress already has better tools: parallel HTTP requests through the Requests library, and Action Scheduler or WP-Cron for background jobs.

Problem: A dashboard widget calls three external APIs one after another with wp_remote_get(), each taking about 800 ms, so the admin page loads in 2.5 seconds. A first attempt with Fibers changed nothing, because each fiber still blocked on its HTTP call.

Solution: Send the three requests in parallel with WpOrg\Requests\Requests::request_multiple(), which uses curl multi under the hood, cache the results in a transient, and move work that the user does not have to wait for into a scheduled action.

What a Fiber is

$fiber = new Fiber( function ( string $start ): string {
    $received = Fiber::suspend( $start . ' paused' );
    return 'resumed with ' . $received;
} );

$value = $fiber->start( 'step 1' ); // 'step 1 paused'
$fiber->resume( 'data' );
echo $fiber->getReturn();           // 'resumed with data'

The fiber runs until Fiber::suspend(), the caller continues, and later resumes it. Everything happens in one thread, one step at a time. Libraries such as Revolt, Amp and ReactPHP use Fibers to write asynchronous code that looks synchronous, but they need non-blocking I/O functions of their own; wp_remote_get() and $wpdb block the whole process, fiber or not.

Parallel HTTP requests in WordPress

use WpOrg\Requests\Requests;

function ha_dashboard_data(): array {
    $cached = get_transient( 'ha_dashboard_data' );
    if ( false !== $cached ) {
        return $cached;
    }

    $responses = Requests::request_multiple(
        array(
            'sales'   => array( 'url' => 'https://api.shop.example/sales/today', 'headers' => array( 'Authorization' => 'Bearer ' . HA_SHOP_TOKEN ) ),
            'tickets' => array( 'url' => 'https://helpdesk.example/api/open-count' ),
            'uptime'  => array( 'url' => 'https://status.example/api/summary' ),
        ),
        array( 'timeout' => 5 )
    );

    $data = array();
    foreach ( $responses as $key => $response ) {
        $data[ $key ] = ( $response instanceof WpOrg\Requests\Response && $response->success )
            ? json_decode( $response->body, true )
            : null; // a failed request returns an exception object, not a response
    }

    set_transient( 'ha_dashboard_data', $data, 5 * MINUTE_IN_SECONDS );
    return $data;
}

The Requests library that WordPress bundles (namespaced as WpOrg\Requests since WordPress 6.2) sends all three requests at once; the total time is that of the slowest, about 800 ms instead of 2.4 s. A failed request does not throw: its entry is a WpOrg\Requests\Exception, which the check above turns into null. The http_request_args and similar filters of wp_remote_*() do not apply here, because this bypasses the WordPress HTTP API wrapper.

Background work

// enqueue instead of doing it during the request
as_enqueue_async_action( 'ha_rebuild_report', array( 'report_id' => $report_id ), 'ha' );

add_action( 'ha_rebuild_report', function ( int $report_id ): void {
    ha_build_report( $report_id ); // runs in a separate request, seconds later
} );

Action Scheduler (bundled with WooCommerce, also available as a standalone library) runs the action in a background request triggered by WP-Cron or by its own async request runner, with retries and a log in Tools → Scheduled Actions. Without WooCommerce, wp_schedule_single_event( time(), 'ha_rebuild_report', array( $report_id ) ) does the same with fewer guarantees. With a system cron job instead of visitor-triggered WP-Cron, the timing is reliable: Linux cron jobs for WordPress.

NOTE: Fibers are useful in WordPress code mainly indirectly, through libraries that are built on them, for example in a long-running WP-CLI worker using an event loop. For page requests, parallel HTTP plus caching and moving work out of the request are the measures that reduce the time a visitor waits. Caching the results: the transients API.