PHP

HTTP Retry with Exponential Backoff

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Wrap any HTTP call in a retry loop with capped exponential backoff and jitter. Retries on 5xx / network errors but not on 4xx (those won't fix themselves).
PHP
Raw
<?php
function withRetry(callable $fn, int $maxAttempts = 5, int $baseMs = 200): mixed {
    $attempt = 0;
    retry:
    $attempt++;
    try {
        return $fn();
    } catch (Throwable $e) {
        // Only retry on transient errors — adapt to your exception types.
        $msg = $e->getMessage();
        $transient = preg_match('/timeout|reset|temporarily|HTTP 5\d\d/', $msg);
        if (!$transient || $attempt >= $maxAttempts) throw $e;

        $sleepMs = $baseMs * (2 ** ($attempt - 1));
        $sleepMs += random_int(0, $sleepMs);   // jitter
        usleep($sleepMs * 1000);
        goto retry;
    }
}

$json = withRetry(fn() => httpGet('https://flaky.api/users'));
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.