← Tous les articles

PHP: calling an external API without letting its slowness take your site down

When a third-party API slows down, your own site is the one that goes offline. cURL timeouts, telling errors apart, careful retries and a fallback response: the approach we use.

PHP: calling an external API without letting its slowness take your site down

Key points

  • Without explicit timeouts, cURL can wait a very long time on an unresponsive API, and every visitor ties up a PHP worker.
  • Set the connection timeout separately from the total timeout, and treat network errors differently from HTTP error responses.
  • Retry once at most during a page request, and always have a fallback.

We’ve seen this play out many times. A page shows a block fed by an external API (exchange rates, stock levels, reviews, weather), that API has a bad day, and the whole site slows to a crawl and then stops responding. The provider isn’t even fully down: it just takes thirty seconds to answer instead of two hundred milliseconds. That’s worse than a clean outage, and it only takes a few lines to defend against.

How one slow API stalls an entire site

Under PHP-FPM, your server has a fixed pool of workers. Every visitor whose page is waiting on the API holds one of those workers for the full wait. Once the pool is exhausted, new visitors queue up, including people browsing pages that have nothing to do with the API.

The defaults won’t save you. cURL sets no total time limit (CURLOPT_TIMEOUT is 0, meaning none), and file_get_contents() on a URL relies on default_socket_timeout, commonly 60 seconds. Set timeouts yourself, on every call.

Short timeouts and clearly separated errors

We start with a small exception that records whether retrying makes sense:

final class ApiError extends RuntimeException
{
    public function __construct(string $message, public readonly bool $retryable)
    {
        parent::__construct($message);
    }
}

Then a request helper with two limits, one for connecting and one for the whole request, so an unreachable host fails in three seconds rather than eating the full budget:

function api_get(string $url, array $headers = []): array
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 3,  // establishing the connection
        CURLOPT_TIMEOUT        => 8,  // maximum total duration
        CURLOPT_HTTPHEADER     => array_merge(['Accept: application/json'], $headers),
    ]);

    $body  = curl_exec($ch);
    $errno = curl_errno($ch);
    $code  = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);

    if ($errno !== 0) {
        // 28 = timed out, 6 = DNS, 7 = connection refused...
        throw new ApiError("Network error $errno: " . curl_error($ch), true);
    }
    if ($code >= 400) {
        throw new ApiError("HTTP response $code", in_array($code, [429, 502, 503, 504], true));
    }

    return json_decode($body, true, 512, JSON_THROW_ON_ERROR);
}

What matters is telling the cases apart. A network error or a 503 may succeed next time; a 404 or 401 won’t change however often you ask. Also note that cURL doesn’t treat a 500 as a failure: without the status check, you’d happily decode an HTML error page as if it were your JSON.

Retry, but sparingly

A retry smooths over brief network blips, as long as it stays modest:

function with_retry(callable $call, int $attempts = 2): mixed
{
    for ($i = 1; ; $i++) {
        try {
            return $call();
        } catch (ApiError $e) {
            if (!$e->retryable || $i >= $attempts) {
                throw $e;
            }
            usleep((250 * 2 ** ($i - 1) + random_int(0, 150)) * 1000);
        }
    }
}

The delay grows with each attempt, plus some randomness so your workers don’t all hit the API again at the exact same instant. During a page load we cap it at two attempts in total: with an eight-second timeout, three attempts could leave a visitor staring at a blank screen for nearly half a minute. Anything that can afford to be patient, like a data sync, belongs in a scheduled job, not in the page.

Always have a fallback

The last safety net is to keep the most recent good response and serve it when the API fails. With APCu, PHP’s in-memory cache:

try {
    $rates = with_retry(fn () => api_get('https://api.example.com/v1/rates'));
    apcu_store('rates_last_good', $rates);
} catch (ApiError | JsonException $e) {
    error_log('Rates API unavailable: ' . $e->getMessage());
    $rates = apcu_fetch('rates_last_good') ?: null; // null: hide the widget
}

For data that doesn’t change much, a value a few hours old beats an error page. With nothing cached, hiding the block is still far better than hanging the page. If you run several servers, use Redis or the database instead of APCu, since they’re shared.

FAQ

What timeout values should I pick?

Look at the API’s usual response time in your logs and leave a comfortable margin above it. For an API that normally answers in a few hundred milliseconds, three seconds to connect and eight in total gives it room without leaving visitors waiting forever.

What about WordPress?

wp_remote_get() uses a 5-second timeout by default, adjustable through the timeout argument. Same principles: check is_wp_error(), inspect wp_remote_retrieve_response_code(), and keep a fallback copy in a transient.

Does your site depend on third-party APIs and slow down whenever they struggle? We audit and harden those integrations so a provider’s outage stays invisible to your visitors.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →