Backend development

PHP and Asynchronous REST APIs: Non-Blocking HTTP Requests, Parallel Calls, and Timeouts Without Switching Stacks

Ruslan Ismailov Published 14 min read
P

Introduction: Why Synchronous HTTP Requests Kill Performance

In 2026, a typical PHP backend integrates with dozens of external services: payment gateways, CRMs, analytics, notifications, geolocation services. Each one means an HTTP request that blocks script execution until a response arrives. If five such requests run sequentially at 300ms each, the user waits a full second and a half on I/O alone — while the CPU sits idle.

The traditional answer is "switch to Go or Node.js." But in reality, most products are built on PHP, run on Laravel, and nobody is going to rewrite them. The good news: PHP has long supported parallelism. The bad news: it requires understanding several different tools and their limitations.

This article covers every practical approach to asynchronous requests in PHP — from low-level curl_multi to Laravel HTTP pool, PHP Fibers, queues, and Redis coordination. For each approach: code, use cases, and honest trade-offs.

curl_multi: Low-Level Parallelism Without Dependencies

curl_multi is PHP's built-in mechanism for parallel HTTP requests via libcurl. It requires no additional dependencies and works in all PHP environments since PHP 5. The concept is straightforward: create multiple curl handles, add them to a multi-handle, and run an event processing loop.

$urls = [
    'users'    => 'https://api.example.com/users',
    'orders'   => 'https://api.example.com/orders',
    'products' => 'https://api.example.com/products',
];

$multiHandle = curl_multi_init();
$handles = [];

foreach ($urls as $key => $url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json']);
    curl_multi_add_handle($multiHandle, $ch);
    $handles[$key] = $ch;
}

// Launch all requests simultaneously
$running = null;
do {
    $status = curl_multi_exec($multiHandle, $running);
    if ($status === CURLM_CALL_MULTI_PERFORM) {
        continue;
    }
    curl_multi_select($multiHandle); // wait for activity without busy-loop
} while ($running > 0);

$results = [];
foreach ($handles as $key => $ch) {
    $error = curl_error($ch);
    if ($error) {
        $results[$key] = ['error' => $error];
    } else {
        $results[$key] = json_decode(curl_multi_getcontent($ch), true);
    }
    curl_multi_remove_handle($multiHandle, $ch);
    curl_close($ch);
}
curl_multi_close($multiHandle);

// Total time ≈ max(each_request_time), not sum()
print_r($results);

The key advantage: all three requests run in parallel, so the total time equals the slowest request — not the sum of all. curl_multi_select blocks the thread at the OS level without wasting CPU cycles.

Downsides: verbose boilerplate, complex error handling, no built-in retry. Use this approach when you can't add Guzzle or need full control.

Guzzle Promises and Concurrent Requests: Pool, settle, unwrap in Practice

Guzzle is the de facto standard HTTP client in PHP. Its asynchronous mode is built on promises and uses curl_multi under the hood, but provides a convenient API. Three key tools: Pool, settle(), and unwrap().

Parallel Requests with Promise::all and unwrap

use GuzzleHttp\Client;
use GuzzleHttp\Promise\Utils;

$client = new Client([
    'base_uri' => 'https://api.example.com',
    'timeout'  => 5.0,
]);

// Create async requests — they start immediately
$promises = [
    'weather'  => $client->getAsync('/weather?city=Moscow'),
    'currency' => $client->getAsync('/currency?from=USD&to=RUB'),
    'news'     => $client->getAsync('/news?limit=5'),
];

// unwrap throws an exception on the first error
try {
    $results = Utils::unwrap($promises);
    $weather  = json_decode($results['weather']->getBody(), true);
    $currency = json_decode($results['currency']->getBody(), true);
    $news     = json_decode($results['news']->getBody(), true);
} catch (\Exception $e) {
    // One request failed — the entire group is considered failed
    logger()->error('API request failed', ['error' => $e->getMessage()]);
}

settle: Get All Results Including Errors

// settle does not throw exceptions — it returns the state of each promise
$settled = Utils::settle($promises)->wait();

foreach ($settled as $key => $result) {
    if ($result['state'] === 'fulfilled') {
        $data[$key] = json_decode($result['value']->getBody(), true);
    } else {
        // $result['reason'] is the exception
        logger()->warning("API {$key} failed", [
            'reason' => $result['reason']->getMessage()
        ]);
        $data[$key] = null; // use a default or cached value
    }
}

Guzzle Pool for Concurrency Control

When you have hundreds of requests, launching them all at once is risky — you'll exhaust your sockets. Pool lets you cap concurrency:

use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;

$client = new Client(['timeout' => 10.0]);
$userIds = range(1, 100);

$requests = function () use ($userIds) {
    foreach ($userIds as $id) {
        yield new Request('GET', "https://api.example.com/users/{$id}");
    }
};

$pool = new Pool($client, $requests(), [
    'concurrency' => 10, // maximum 10 simultaneous requests
    'fulfilled' => function ($response, $index) use (&$results) {
        $results[$index] = json_decode($response->getBody(), true);
    },
    'rejected' => function ($reason, $index) use (&$errors) {
        $errors[$index] = $reason->getMessage();
    },
]);

$pool->promise()->wait();

Pool is the right choice for batch processing: it manages the request queue automatically and prevents overloading both your server and the external API.

PHP Fibers in 2026 for Async HTTP: A Real-World Scenario

PHP Fibers (introduced in PHP 8.1) are first-class coroutines — lightweight execution units that can be paused and resumed without blocking the main thread. By 2026, they have become a fully mature tool for async I/O when combined with an event loop from ReactPHP or Amp.

Example with Amp HTTP Client

// composer require amphp/http-client amphp/amp
use Amp\Http\Client\HttpClientBuilder;
use Amp\Http\Client\Request;
use function Amp\async;
use function Amp\await;

$client = HttpClientBuilder::buildDefault();

// Launch three requests as Fiber coroutines
$futures = [
    'alpha' => async(function () use ($client) {
        $request  = new Request('https://api.alpha.com/data');
        $response = await($client->request($request));
        return json_decode(await($response->getBody()->buffer()), true);
    }),
    'beta' => async(function () use ($client) {
        $request  = new Request('https://api.beta.com/data');
        $response = await($client->request($request));
        return json_decode(await($response->getBody()->buffer()), true);
    }),
    'gamma' => async(function () use ($client) {
        $request  = new Request('https://api.gamma.com/data');
        $response = await($client->request($request));
        return json_decode(await($response->getBody()->buffer()), true);
    }),
];

// Await all results in parallel
$results = Amp\Future\awaitAll($futures);
// $results[0] — errors, $results[1] — successful values

Fibers do not create true multithreading — PHP remains single-threaded. They allow the event loop to switch between tasks while waiting for I/O. This is especially effective in long-running processes (Swoole, RoadRunner, FrankenPHP), where a single worker handles many requests concurrently.

For traditional PHP-FPM, Fibers are less relevant — each HTTP request already runs in its own process. But if you use RoadRunner or Swoole, Fibers deliver a noticeable efficiency gain on I/O-heavy workloads.

Laravel HTTP Client: Parallel Requests with pool() and Error Handling

Laravel 9+ includes a built-in HTTP client based on Guzzle with a convenient fluent API. The pool() method lets you execute parallel requests with minimal boilerplate.

use Illuminate\Support\Facades\Http;

// Parallel requests to multiple services
$responses = Http::pool(fn ($pool) => [
    $pool->as('user')->get('https://api.example.com/user/42'),
    $pool->as('orders')->get('https://api.example.com/orders', ['user_id' => 42]),
    $pool->as('recommendations')->get('https://api.recommend.com/for/42'),
]);

// Access results by name
if ($responses['user']->successful()) {
    $user = $responses['user']->json();
}

if ($responses['orders']->failed()) {
    logger()->error('Orders API failed', [
        'status' => $responses['orders']->status()
    ]);
}

$recs = $responses['recommendations']->json('items', []);

Timeout and Retry Directly in pool

$responses = Http::pool(fn ($pool) => [
    $pool->as('payment')
         ->timeout(3)
         ->retry(2, 100)
         ->withToken(config('services.payment.token'))
         ->post('https://pay.example.com/charge', $payload),

    $pool->as('notification')
         ->timeout(2)
         ->withHeaders(['X-API-Key' => config('services.notify.key')])
         ->post('https://notify.example.com/send', $notifyPayload),
]);

The Laravel HTTP pool is the most readable option for typical Laravel applications. Under the hood it uses Guzzle Promises, but hides all the complexity of promise management.

Timeouts, Retry, and Circuit Breaker for External REST APIs in PHP

Parallelism without proper failure handling is a recipe for cascading outages. External REST APIs go down, slow down, and return 5xx errors. Three essential patterns:

Timeouts: connect vs. read

In Guzzle, separate the connect timeout from the total timeout. Recommended values for API integrations: connect — 2 seconds, total — 5–10 seconds depending on criticality.

$client = new Client([
    'connect_timeout' => 2,   // maximum time to establish a connection
    'timeout'         => 8,   // maximum time for the entire request
]);

Retry with Exponential Backoff

use GuzzleHttp\Middleware;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;

$stack = HandlerStack::create();
$stack->push(Middleware::retry(
    function ($retries, $request, $response, $exception) {
        // Retry on network errors or 429/503
        if ($exception instanceof ConnectException) return $retries < 3;
        if ($response && in_array($response->getStatusCode(), [429, 503])) {
            return $retries < 3;
        }
        return false;
    },
    function ($retries) {
        return (int) (100 * pow(2, $retries)); // 100ms, 200ms, 400ms
    }
));

$client = new Client(['handler' => $stack]);

Circuit Breaker with Redis

A circuit breaker prevents a flood of requests from hitting a failing service. A simple Redis-based implementation:

class CircuitBreaker
{
    private Redis $redis;
    private string $service;
    private int $threshold;
    private int $ttl;

    public function __construct(Redis $redis, string $service, int $threshold = 5, int $ttl = 60)
    {
        $this->redis     = $redis;
        $this->service   = $service;
        $this->threshold = $threshold;
        $this->ttl       = $ttl;
    }

    public function isOpen(): bool
    {
        return (int) $this->redis->get("cb:open:{$this->service}") === 1;
    }

    public function recordFailure(): void
    {
        $key    = "cb:failures:{$this->service}";
        $count  = $this->redis->incr($key);
        $this->redis->expire($key, $this->ttl);

        if ($count >= $this->threshold) {
            $this->redis->setex("cb:open:{$this->service}", $this->ttl, 1);
            logger()->critical("Circuit breaker opened for {$this->service}");
        }
    }

    public function recordSuccess(): void
    {
        $this->redis->del("cb:failures:{$this->service}");
        $this->redis->del("cb:open:{$this->service}");
    }
}

// Usage
$cb = new CircuitBreaker($redis, 'payment-api');

if ($cb->isOpen()) {
    return $this->getFallbackResponse(); // return cached or default response
}

try {
    $response = $client->post('https://pay.example.com/charge', $payload);
    $cb->recordSuccess();
} catch (Exception $e) {
    $cb->recordFailure();
    throw $e;
}

Queues as an Async Tool: When to Defer an API Call

Not all API calls need to happen synchronously within the user's HTTP request. If the result isn't needed immediately — it's a job for a queue. Typical scenarios: sending email via an external service, updating a CRM after an order is placed, generating reports via an analytics API, sending notifications to Slack or Telegram.

// app/Jobs/SyncOrderToCrm.php
namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Http;

class SyncOrderToCrm implements ShouldQueue
{
    use Queueable;

    public int $tries = 3;
    public int $backoff = 60; // seconds between attempts
    public int $timeout = 30;

    public function __construct(private array $order) {}

    public function handle(): void
    {
        $response = Http::withToken(config('services.crm.token'))
            ->timeout(10)
            ->post('https://crm.example.com/api/orders', $this->order);

        if ($response->failed()) {
            throw new \RuntimeException(
                'CRM sync failed: ' . $response->status()
            );
        }
    }

    public function failed(\Throwable $exception): void
    {
        logger()->error('CRM sync ultimately failed', [
            'order_id' => $this->order['id'],
            'error'    => $exception->getMessage(),
        ]);
        // Send an alert to Slack, flag the order as requiring manual sync
    }
}

// Dispatch from the controller — the user response is not delayed
SyncOrderToCrm::dispatch($order)->onQueue('crm-sync');

Queues provide fault tolerance (automatic retries), observability (Horizon), and decoupling between components. They don't make a request "faster" — they remove it from the user's critical path.

Redis for Coordinating Parallel Tasks and Storing Intermediate Results

Redis is ideal for storing results of parallel API requests, caching responses, and coordinating between processes. Two patterns are most in demand in PHP applications.

Short-TTL Cache for Frequent External Requests

function fetchWithCache(string $key, int $ttl, callable $fetcher): array
{
    $cached = Cache::get($key);
    if ($cached !== null) {
        return $cached;
    }

    // Use an atomic lock to avoid stampede
    return Cache::lock("lock:{$key}", 5)->block(3, function () use ($key, $ttl, $fetcher) {
        // Re-check inside the lock
        $cached = Cache::get($key);
        if ($cached !== null) {
            return $cached;
        }

        $result = $fetcher();
        Cache::put($key, $result, $ttl);
        return $result;
    });
}

// Usage
$weatherData = fetchWithCache('weather:moscow', 300, function () use ($client) {
    return $client->get('https://api.weather.com/moscow')->json();
});

Storing Intermediate Results During Batch Processing

// Worker writes results as they become ready
$pipe = $redis->pipeline();
foreach ($batchResults as $userId => $data) {
    $pipe->setex("api_result:user:{$userId}", 3600, json_encode($data));
}
$pipe->execute();

// Main process reads when needed
$userIds = [1, 2, 3, 4, 5];
$keys    = array_map(fn($id) => "api_result:user:{$id}", $userIds);
$cached  = $redis->mget($keys);

$results = [];
foreach ($userIds as $i => $id) {
    $results[$id] = $cached[$i] ? json_decode($cached[$i], true) : null;
}

Redis pipeline lets you write thousands of keys in a single round-trip. This is critical during batch processing of parallel API call results, where Redis latency becomes the bottleneck.

Benchmarks: Comparing Approaches Under Real Load

The benchmark scenario: 10 parallel requests to external REST APIs, each with ~200ms latency, PHP 8.3, server with 4 vCPU / 8 GB RAM.

  • Sequential requests (curl): ~2050ms. Simple code, zero overhead, but time grows linearly with the number of requests. Acceptable for 1–2 non-critical calls.
  • curl_multi: ~215ms. Close to the theoretical minimum (time of the slowest request). Maximum control, minimal dependencies, but verbose code.
  • Guzzle Promise / unwrap: ~220ms. Almost the same as curl_multi (which it uses under the hood). Much more convenient to use, with built-in error handling via settle.
  • Guzzle Pool (concurrency=5): ~430ms. Processed 10 requests in two waves of 5. Best choice for large numbers of requests (100+) — controls load on the external service.
  • Laravel HTTP pool(): ~225ms. Minimal overhead over Guzzle Promises. The most readable code, ideal for Laravel projects.
  • Amp Fibers (RoadRunner): ~205ms. Best result in long-running processes due to the absence of bootstrap overhead. Requires changes to the deployment architecture.
  • Sequentially via Queue: User-facing latency — 0ms (instant response). Result available after 2–10 seconds depending on the queue. Not suitable when the result is needed synchronously.

Conclusion: How to Choose the Right Approach

Tool selection depends on context, not trends. Here's a practical guide:

  • Laravel project, 2–10 parallel requests, result needed synchronously: use Http::pool(). Minimal code, native ecosystem integration.
  • Plain PHP without a framework, no Guzzle: curl_multi. Built into PHP, works everywhere.
  • Batch processing of 50–1000+ requests: Guzzle Pool with limited concurrency. Protects both your server and the external API from overload.
  • API result not needed immediately by the user: Laravel Queue. Adds retry, observability, and fault tolerance for free.
  • Long-running processes (RoadRunner, Swoole, FrankenPHP): PHP Fibers + Amp. Maximum efficiency on I/O-heavy workloads.
  • Protection against failing external services: circuit breaker on Redis + proper timeouts everywhere, regardless of the parallelism approach chosen.

Async in PHP is not about switching languages. It's about choosing the right tool for each task. curl_multi, Guzzle Promises, Laravel HTTP pool, queues, and Fibers all address different aspects of the same problem — and work great together within a single application.

Technologies

Tags

Ruslan Ismailov

Senior Web / Backend Developer. Senior web/backend developer with 9 years of experience. Stack: PHP, Laravel, PostgreSQL, Redis, Docker, Kubernetes, REST, microservices, CI/CD. More about me →