PHPackages                             philiprehberger/http-retry-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. philiprehberger/http-retry-client

ActiveLibrary[HTTP &amp; Networking](/categories/http)

philiprehberger/http-retry-client
=================================

HTTP client wrapper with automatic retries, exponential backoff, and jitter

v1.2.0(2mo ago)138MITPHPPHP ^8.2CI passing

Since Mar 13Pushed 1mo agoCompare

[ Source](https://github.com/philiprehberger/http-retry-client)[ Packagist](https://packagist.org/packages/philiprehberger/http-retry-client)[ Docs](https://github.com/philiprehberger/http-retry-client)[ GitHub Sponsors](https://github.com/philiprehberger)[ RSS](/packages/philiprehberger-http-retry-client/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (6)Versions (6)Used By (0)

PHP HTTP Retry Client
=====================

[](#php-http-retry-client)

[![Tests](https://github.com/philiprehberger/http-retry-client/actions/workflows/tests.yml/badge.svg)](https://github.com/philiprehberger/http-retry-client/actions/workflows/tests.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/51f62d463ad23ce7f52f927874b5499b8d2a39818bee08b5a9ec68a4cb08dae8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7068696c69707265686265726765722f687474702d72657472792d636c69656e742e737667)](https://packagist.org/packages/philiprehberger/http-retry-client)[![Last updated](https://camo.githubusercontent.com/b1c86ba47f3acb01a8b7547a81d5c9b5636d6f7844ceb4ee178f32bf7cc0ae12/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f7068696c69707265686265726765722f687474702d72657472792d636c69656e74)](https://github.com/philiprehberger/http-retry-client/commits/main)

HTTP client wrapper with automatic retries, exponential backoff, jitter, circuit breaker, and request logging.

Requirements
------------

[](#requirements)

- PHP 8.2+

Installation
------------

[](#installation)

```
composer require philiprehberger/http-retry-client
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

Implement the `HttpExecutor` interface to wrap your preferred HTTP client:

```
use PhilipRehberger\HttpRetry\Contracts\HttpExecutor;
use PhilipRehberger\HttpRetry\HttpRequest;
use PhilipRehberger\HttpRetry\HttpResponse;
use PhilipRehberger\HttpRetry\RetryClient;

class CurlExecutor implements HttpExecutor
{
    public function execute(HttpRequest $request): HttpResponse
    {
        $ch = curl_init($request->url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request->method);

        if ($request->body !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $request->body);
        }

        $body = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return new HttpResponse($statusCode, $body);
    }
}

$client = new RetryClient(new CurlExecutor());
$result = $client->send(new HttpRequest('GET', 'https://api.example.com/data'));

if ($result->successful()) {
    echo $result->body;
}
```

### Custom Retry Policy

[](#custom-retry-policy)

```
use PhilipRehberger\HttpRetry\RetryClient;
use PhilipRehberger\HttpRetry\RetryPolicy;

$policy = new RetryPolicy(
    maxRetries: 5,
    baseDelayMs: 200,
    maxDelayMs: 30000,
    multiplier: 2.0,
    jitter: true,
    retryableStatusCodes: [429, 500, 502, 503, 504],
);

$client = new RetryClient($executor, $policy);
```

### Fluent Builder

[](#fluent-builder)

```
use PhilipRehberger\HttpRetry\RetryPolicy;

$policy = RetryPolicy::builder()
    ->maxRetries(5)
    ->baseDelay(200)
    ->maxDelay(30000)
    ->multiplier(3.0)
    ->withoutJitter()
    ->retryOn([500, 502, 503])
    ->build();
```

### Handling Retry Results

[](#handling-retry-results)

```
use PhilipRehberger\HttpRetry\Exceptions\MaxRetriesExceededException;

try {
    $result = $client->send($request);

    echo "Status: {$result->statusCode}\n";
    echo "Attempts: {$result->attempts}\n";
    echo "Total delay: {$result->totalDelayMs}ms\n";
    echo "Was retried: " . ($result->wasRetried ? 'yes' : 'no') . "\n";
} catch (MaxRetriesExceededException $e) {
    echo "Failed after {$e->attempts} attempts: {$e->getMessage()}\n";
}
```

### Jitter Modes

[](#jitter-modes)

Control the jitter algorithm used for backoff delays:

```
use PhilipRehberger\HttpRetry\JitterMode;
use PhilipRehberger\HttpRetry\RetryPolicy;

// Full jitter (default): rand(0, delay)
$policy = RetryPolicy::builder()
    ->jitterMode(JitterMode::Full)
    ->build();

// Equal jitter: delay/2 + rand(0, delay/2)
$policy = RetryPolicy::builder()
    ->jitterMode(JitterMode::Equal)
    ->build();

// Decorrelated jitter: rand(base, previous * 3)
$policy = RetryPolicy::builder()
    ->jitterMode(JitterMode::Decorrelated)
    ->build();
```

### Retry Hooks

[](#retry-hooks)

Register callbacks that run before and after each retry attempt:

```
use PhilipRehberger\HttpRetry\RetryPolicy;

$policy = RetryPolicy::builder()
    ->beforeRetry(function (int $attempt, ?\Throwable $error): void {
        echo "Retrying attempt {$attempt}...\n";
    })
    ->afterRetry(function (int $attempt, ?\Throwable $error): void {
        if ($error !== null) {
            echo "Attempt {$attempt} failed: {$error->getMessage()}\n";
        }
    })
    ->build();
```

### Custom Retryable Status Codes

[](#custom-retryable-status-codes)

```
$policy = RetryPolicy::builder()
    ->retryOn([408, 429, 500, 502, 503, 504])
    ->build();
```

### Circuit Breaker

[](#circuit-breaker)

Protect downstream services with a circuit breaker that opens after consecutive failures:

```
use PhilipRehberger\HttpRetry\CircuitBreakerWrapper;
use PhilipRehberger\HttpRetry\Exceptions\CircuitBreakerOpenException;

$breaker = new CircuitBreakerWrapper(failureThreshold: 5, recoveryTimeoutSeconds: 30);

try {
    $result = $breaker->execute(fn () => $client->send($request));
} catch (CircuitBreakerOpenException $e) {
    // Circuit is open, requests are being rejected
}

// Or configure via the builder
$builder = RetryPolicy::builder()
    ->withCircuitBreaker(failureThreshold: 5, recoveryTimeout: 30);
```

The circuit breaker transitions through three states:

- **Closed**: Requests flow normally; failures are counted
- **Open**: Requests are rejected immediately with `CircuitBreakerOpenException`
- **Half-Open**: After the recovery timeout, one request is allowed through to test recovery

### Request Logging

[](#request-logging)

Log HTTP requests, responses, and failures for observability:

```
use PhilipRehberger\HttpRetry\RequestLogger;

$logger = new RequestLogger(function (array $entry): void {
    // $entry contains: event, method, url, attempt, status_code, duration_ms, error, etc.
    error_log(json_encode($entry));
}, logBodies: true);

$logger->logRequest($request, attempt: 1);
$logger->logResponse($response, attempt: 1, durationMs: 42.5);
$logger->logFailure($exception, attempt: 1);

// Or configure via the builder
$builder = RetryPolicy::builder()
    ->withLogger(fn (array $entry) => error_log(json_encode($entry)), logBodies: false);
```

### Timeout Configuration

[](#timeout-configuration)

Set connection and request timeouts:

```
$policy = RetryPolicy::builder()
    ->connectionTimeout(5000)  // 5 seconds
    ->requestTimeout(30000)    // 30 seconds
    ->build();

// Timeouts can also be set per-request
$request = new HttpRequest(
    method: 'GET',
    url: 'https://api.example.com/data',
    connectionTimeoutMs: 3000,
    requestTimeoutMs: 15000,
);
```

API
---

[](#api)

### `RetryPolicy`

[](#retrypolicy)

ParameterTypeDefaultDescription`maxRetries``int``3`Maximum number of retry attempts`baseDelayMs``int``100`Base delay in milliseconds`maxDelayMs``int``10000`Maximum delay cap in milliseconds`multiplier``float``2.0`Backoff multiplier`jitter``bool``true`Whether to add random jitter`retryableStatusCodes``array``[429, 500, 502, 503, 504]`Status codes that trigger a retry`jitterMode``JitterMode``JitterMode::Full`Jitter algorithm (`Full`, `Equal`, `Decorrelated`)`beforeRetry``?callable``null`Callback invoked before each retry `(int $attempt, ?\Throwable $error)``afterRetry``?callable``null`Callback invoked after each retry `(int $attempt, ?\Throwable $error)``connectionTimeoutMs``?int``null`Default connection timeout in milliseconds`requestTimeoutMs``?int``null`Default request timeout in milliseconds### `RetryPolicyBuilder`

[](#retrypolicybuilder)

MethodDescription`maxRetries(int $maxRetries)`Set max retry attempts`baseDelay(int $ms)`Set base delay in milliseconds`maxDelay(int $ms)`Set max delay cap in milliseconds`multiplier(float $multiplier)`Set backoff multiplier`withJitter(bool $jitter)`Enable/disable jitter`withoutJitter()`Disable jitter`retryOn(array $codes)`Set retryable status codes`jitterMode(JitterMode $mode)`Set jitter algorithm`beforeRetry(callable $callback)`Register before-retry callback`afterRetry(callable $callback)`Register after-retry callback`connectionTimeout(int $ms)`Set connection timeout in milliseconds`requestTimeout(int $ms)`Set request timeout in milliseconds`withCircuitBreaker(int $failureThreshold, int $recoveryTimeout)`Enable circuit breaker`withLogger(callable $logger, bool $logBodies)`Enable request/response logging`build()`Build the `RetryPolicy`### `RetryClient`

[](#retryclient)

MethodDescription`send(HttpRequest $request): RetryResult`Send a request with automatic retries### `RetryResult`

[](#retryresult)

PropertyTypeDescription`statusCode``int`HTTP status code of the final response`body``string`Response body`headers``array`Response headers`attempts``int`Total number of attempts made`totalDelayMs``int`Total delay spent waiting (ms)`wasRetried``bool`Whether the request was retried`successful()``bool`Whether the status code is 2xx### `HttpExecutor` (Interface)

[](#httpexecutor-interface)

MethodDescription`execute(HttpRequest $request): HttpResponse`Execute an HTTP request### `CircuitBreakerWrapper`

[](#circuitbreakerwrapper)

MethodDescription`__construct(int $failureThreshold, int $recoveryTimeoutSeconds)`Create a circuit breaker`execute(callable $action): mixed`Execute action through the circuit breaker`isOpen(): bool`Check if circuit is open`isClosed(): bool`Check if circuit is closed`state(): string`Get current state (`closed`, `open`, `half_open`)`reset(): void`Reset to closed state`failureCount(): int`Get current failure count### `RequestLogger`

[](#requestlogger)

MethodDescription`__construct(callable $logger, bool $logBodies)`Create a logger`logRequest(HttpRequest $request, int $attempt): void`Log an outgoing request`logResponse(HttpResponse $response, int $attempt, float $durationMs): void`Log a response`logFailure(\Throwable $exception, int $attempt): void`Log a failure### `MaxRetriesExceededException`

[](#maxretriesexceededexception)

PropertyTypeDescription`attempts``int`Total number of attempts made### `CircuitBreakerOpenException`

[](#circuitbreakeropenexception)

Thrown when a request is rejected because the circuit breaker is in the open state.

Development
-----------

[](#development)

```
composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse
```

Support
-------

[](#support)

If you find this project useful:

⭐ [Star the repo](https://github.com/philiprehberger/http-retry-client)

🐛 [Report issues](https://github.com/philiprehberger/http-retry-client/issues?q=is%3Aissue+is%3Aopen+label%3Abug)

💡 [Suggest features](https://github.com/philiprehberger/http-retry-client/issues?q=is%3Aissue+is%3Aopen+label%3Aenhancement)

❤️ [Sponsor development](https://github.com/sponsors/philiprehberger)

🌐 [All Open Source Projects](https://philiprehberger.com/open-source-packages)

💻 [GitHub Profile](https://github.com/philiprehberger)

🔗 [LinkedIn Profile](https://www.linkedin.com/in/philiprehberger)

License
-------

[](#license)

[MIT](LICENSE)

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance88

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 94.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~5 days

Total

5

Last Release

86d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/cfd7d24cbbf32400fa13ce0bbe7a31edd2d66a6d4488eafdb3d64c5337bf0435?d=identicon)[philiprehberger](/maintainers/philiprehberger)

---

Top Contributors

[![philiprehberger](https://avatars.githubusercontent.com/u/8218077?v=4)](https://github.com/philiprehberger "philiprehberger (17 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

httppsr-18retryJitterbackoff

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/philiprehberger-http-retry-client/health.svg)

```
[![Health](https://phpackages.com/badges/philiprehberger-http-retry-client/health.svg)](https://phpackages.com/packages/philiprehberger-http-retry-client)
```

###  Alternatives

[psr/http-client

Common interface for HTTP clients

1.7k714.1M2.7k](/packages/psr-http-client)[php-http/curl-client

PSR-18 and HTTPlug Async client with cURL

48348.5M435](/packages/php-http-curl-client)[elastic/transport

HTTP transport PHP library for Elastic products

2022.9M9](/packages/elastic-transport)[phpro/http-tools

HTTP tools for developing more consistent HTTP implementations.

28146.3k](/packages/phpro-http-tools)[vultr/vultr-php

The Official Vultr API PHP Wrapper.

2246.5k1](/packages/vultr-vultr-php)[amphp/http-client-psr7

PSR-7 adapter for Amp's HTTP client.

1372.8k7](/packages/amphp-http-client-psr7)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
