Skip to content

PHP cURL performance: connection reuse, timeouts, and parallel requests

Learn how to make PHP's cURL calls faster and safer. This guide shows you how to reuse connections, set timeouts so a slow API cannot freeze your site, and send several requests in parallel with curl_multi.

This guide is for PHP developers and server admins whose code calls outside services with cURL, the built-in library PHP uses to make HTTP requests. Payment gateways, internal APIs and webhook deliveries often rely on it. The usual pattern (create a handle, send one request, close it, repeat) is also the slowest one. A handle is the object cURL uses to hold a connection and its settings. Closing it after every call means the TCP connection and the TLS encryption handshake are set up again each time. Requests also run one after another, and a call with no timeout can wait forever. While it waits, it holds a PHP-FPM worker, one of the limited processes that run your PHP code and serve your pages. The fix comes in three parts. Keep handles open so connections are reused, always set a connect timeout and a total timeout, and use curl_multi to send independent requests at the same time.

How to verify

# confirm cURL extension and version
php -i | grep -E 'curl|libcurl'

# check if curl_multi_* functions are available
php -r 'var_dump(function_exists("curl_multi_init"));'

# measure naive vs pooled cURL performance on a target endpoint
time php -r '
  for ($i = 0; $i < 10; $i++) {
      $ch = curl_init("https://httpbin.org/get");
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_exec($ch);
      curl_close($ch);
  }
'

# compare with a persistent handle (connection reuse)
time php -r '
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  for ($i = 0; $i < 10; $i++) {
      curl_setopt($ch, CURLOPT_URL, "https://httpbin.org/get");
      curl_exec($ch);
  }
  curl_close($ch);
'

The persistent handle version should be 2–5x faster on HTTPS endpoints because TCP and TLS are negotiated once and then reused. The difference is more pronounced against HTTP/2 targets.

What’s happening

libcurl maintains a connection cache per handle. When you call curl_close(), the cache is destroyed and the underlying socket is closed. When you instantiate a new handle for the next request to the same host, libcurl goes through the full TCP handshake + TLS 1.3 handshake cycle again — roughly 100–300ms of added latency per request on a cross-region call.

Keeping the handle alive across requests lets libcurl reuse the keep-alive socket. Most modern HTTP APIs support persistent connections. HTTP/2 multiplexing extends this further: a single TCP connection can carry multiple concurrent streams, eliminating the connection-per-request overhead entirely.

The second expensive pattern is sequential fan-out: calling curl_exec() in a loop when requests are to different hosts and results are needed together. If you make 5 independent API calls each taking 200ms, sequential execution costs 1 000ms. curl_multi_* executes them concurrently in a single event loop iteration, with total time bounded by the slowest response — in this example, 200ms.

Timeouts are the third dimension. Without CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT, a cURL call will wait indefinitely for a response. On a payment processor or upstream API that hangs, your FPM worker is stuck, consuming a slot from pm.max_children and never releasing it. Worker pool exhaustion from upstream hangs is one of the most common causes of PHP site outages under normal traffic.

The procedure

1. Reuse handles across requests

For a service class that wraps an HTTP API, hold the cURL handle as a class property:

class ApiClient
{
    private \CurlHandle $ch;

    public function __construct(private string $baseUrl)
    {
        $this->ch = curl_init();
        curl_setopt_array($this->ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => false,
            CURLOPT_CONNECTTIMEOUT => 3,      // TCP connect timeout in seconds
            CURLOPT_TIMEOUT        => 10,     // total request timeout
            CURLOPT_ENCODING       => '',     // accept gzip/br automatically
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_2TLS, // prefer HTTP/2
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
        ]);
    }

    public function get(string $path): array
    {
        curl_setopt($this->ch, CURLOPT_URL, $this->baseUrl . $path);
        curl_setopt($this->ch, CURLOPT_HTTPGET, true);
        $body = curl_exec($this->ch);
        if ($body === false) {
            throw new \RuntimeException(
                'cURL error ' . curl_errno($this->ch) . ': ' . curl_error($this->ch)
            );
        }
        return json_decode($body, true, 512, JSON_THROW_ON_ERROR);
    }

    public function __destruct()
    {
        curl_close($this->ch);
    }
}

In a DI container, register ApiClient as a shared/singleton service so the same handle is reused across all calls within a request lifecycle.

2. Always set timeouts

Never omit these two options on any cURL handle in production:

curl_setopt_array($ch, [
    CURLOPT_CONNECTTIMEOUT => 3,   // fail fast if TCP connect hangs
    CURLOPT_TIMEOUT        => 15,  // overall budget for the full response
]);

For health checks or internal service calls over a LAN, tighten these considerably:

CURLOPT_CONNECTTIMEOUT_MS => 500,   // 500ms connect (millisecond variant)
CURLOPT_TIMEOUT_MS        => 2000,  // 2s total

3. Parallel requests with curl_multi_*

For fan-out patterns — fetching data from multiple APIs to compose a single response — use the multi interface:

function curl_multi_get(array $urls, array $options = []): array
{
    $defaults = [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 3,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_ENCODING       => '',
        CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_2TLS,
    ];

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

    foreach ($urls as $key => $url) {
        $ch = curl_init($url);
        curl_setopt_array($ch, $defaults + $options);
        curl_multi_add_handle($mh, $ch);
        $handles[$key] = $ch;
    }

    // event loop — runs until all handles complete or time out
    do {
        $status = curl_multi_exec($mh, $running);
        if ($running) {
            curl_multi_select($mh, 0.5); // yield to OS for up to 500ms
        }
    } while ($running && $status === CURLM_OK);

    $results = [];
    foreach ($handles as $key => $ch) {
        $results[$key] = [
            'body'  => curl_multi_getcontent($ch),
            'info'  => curl_getinfo($ch),
            'error' => curl_error($ch),
        ];
        curl_multi_remove_handle($mh, $ch);
        curl_close($ch);
    }
    curl_multi_close($mh);
    return $results;
}

// usage
$responses = curl_multi_get([
    'prices'    => 'https://api.pricing.internal/v1/rates',
    'inventory' => 'https://api.warehouse.internal/v2/stock',
    'user'      => 'https://api.auth.internal/v1/profile/' . $userId,
]);

Total latency is bounded by max(individual_latencies) rather than sum(individual_latencies).

4. Connection sharing across handles with curl_share_*

For applications that create many short-lived handles but talk to the same hosts, a share handle lets libcurl reuse DNS lookups and TLS sessions across handles:

$sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SHARE, $sh);
// ... execute ...
curl_close($ch);
// $sh persists and is used by the next handle

Common pitfalls

  • Mixing CURLOPT_TIMEOUT and CURLOPT_TIMEOUT_MS. Setting both causes the later one to override the earlier in the same curl_setopt_array call. Pick one unit. _MS variants are more precise for sub-second timeouts.

  • curl_multi_exec() without curl_multi_select(). A tight polling loop on curl_multi_exec() without yielding with curl_multi_select() pegs a CPU core while waiting for I/O. Always include the select() call with a reasonable timeout (0.1–1.0 seconds).

  • Not checking curl_multi_info_read() for per-handle errors. curl_multi_exec() returns CURLM_OK even if individual handles fail. Inspect the result queue:

    while ($info = curl_multi_info_read($mh)) {
        if ($info['result'] !== CURLE_OK) {
            // handle individual error
        }
    }
  • Reusing handles without resetting state. A reused handle carries previous response headers, cookies, and redirect state. Before reusing a handle for a different endpoint, reset options explicitly or call curl_reset($ch) (PHP 8.0+) to return to libcurl defaults.

  • No timeout on redirect chains. CURLOPT_FOLLOWLOCATION = true with CURLOPT_MAXREDIRS unset and CURLOPT_TIMEOUT missing allows an infinite redirect loop to hold a worker slot indefinitely. Set CURLOPT_MAXREDIRS = 3 and always set a total timeout.

Proper cURL configuration is a routine part of PHP service layer setup. Stack Harbor’s managed operations practice reviews HTTP client configuration during provisioning audits and adds timeout alerts to catch upstream hangs before they exhaust FPM worker pools.