PHPackages                             philiprehberger/php-retry - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. philiprehberger/php-retry

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

philiprehberger/php-retry
=========================

Composable retry utility with exponential backoff, jitter, and exception filtering

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

Since Mar 15Pushed 1mo agoCompare

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

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

PHP Retry
=========

[](#php-retry)

[![Tests](https://github.com/philiprehberger/php-retry/actions/workflows/tests.yml/badge.svg)](https://github.com/philiprehberger/php-retry/actions/workflows/tests.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/89a9ec4fa3f7f9ac3cbde12960c946b32b2c3c50d06610d2c567150bf2266789/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7068696c69707265686265726765722f7068702d72657472792e737667)](https://packagist.org/packages/philiprehberger/php-retry)[![Last updated](https://camo.githubusercontent.com/97913aaaa86c7ff3d10b1e8f29eb88a46e46adfda7c561cd2b20822fe8752a8f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f7068696c69707265686265726765722f7068702d7265747279)](https://github.com/philiprehberger/php-retry/commits/main)

Composable retry utility with exponential backoff, jitter, and exception filtering.

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

[](#requirements)

- PHP 8.2+

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

[](#installation)

```
composer require philiprehberger/php-retry
```

Usage
-----

[](#usage)

### Basic retry

[](#basic-retry)

```
use PhilipRehberger\Retry\Retry;

$result = Retry::times(3)->run(function () {
    return file_get_contents('https://api.example.com/data');
});

echo $result->value;       // The response body
echo $result->attempts;    // Number of attempts made
echo $result->totalTimeMs; // Total time spent in milliseconds
```

### Exponential backoff with jitter

[](#exponential-backoff-with-jitter)

```
$result = Retry::times(5)
    ->backoff(baseMs: 100, maxMs: 5000)
    ->jitter()
    ->run(fn () => $httpClient->get('/unstable-endpoint'));
```

### Linear backoff

[](#linear-backoff)

```
$result = Retry::times(3)
    ->linear(delayMs: 200)
    ->run(fn () => $api->call());
```

### Constant delay

[](#constant-delay)

```
$result = Retry::times(4)
    ->constant(delayMs: 500)
    ->run(fn () => $service->fetch());
```

### Exception filtering

[](#exception-filtering)

Only retry on specific exceptions:

```
$result = Retry::times(5)
    ->onlyIf(fn (\Throwable $e) => $e instanceof ConnectionException)
    ->run(fn () => $db->query($sql));
```

Exclude specific exceptions from retrying:

```
$result = Retry::times(5)
    ->except(ValidationException::class, AuthenticationException::class)
    ->run(fn () => $api->submit($data));
```

### Conditional Retry

[](#conditional-retry)

Use `shouldRetry()` to provide a predicate that receives the exception and attempt number:

```
$retry = Retry::times(5)
    ->shouldRetry(function (\Throwable $e, int $attempt): bool {
        // Stop retrying after attempt 3 for rate-limit errors
        if ($e instanceof RateLimitException && $attempt >= 3) {
            return false;
        }
        return true;
    })
    ->run(fn () => $api->request());
```

Use `retryOnlyOn()` to retry only for specific exception types:

```
$result = Retry::times(5)
    ->retryOnlyOn(ConnectionException::class, TimeoutException::class)
    ->run(fn () => $httpClient->get('/endpoint'));
```

Retrieve the total number of attempts after execution with `getAttempts()`:

```
$retry = Retry::times(5);
$result = $retry->run(fn () => $service->call());

echo $retry->getAttempts(); // e.g. 3
```

### Time budget

[](#time-budget)

Stop retrying after a total time budget is exceeded:

```
$result = Retry::times(100)
    ->constant(delayMs: 50)
    ->maxDuration(ms: 2000)
    ->run(fn () => $service->call());
```

### Retry forever (with safety)

[](#retry-forever-with-safety)

```
$result = Retry::forever()
    ->backoff(baseMs: 100, maxMs: 30000)
    ->jitter()
    ->maxDuration(ms: 60000)
    ->run(fn () => $queue->consume());
```

### Callbacks

[](#callbacks)

```
$result = Retry::times(5)
    ->backoff(baseMs: 100)
    ->beforeRetry(function (int $attempt, \Throwable $e) {
        logger()->warning("Retry attempt {$attempt}: {$e->getMessage()}");
    })
    ->afterRetry(function (int $attempt, ?\Throwable $e) {
        if ($e === null) {
            logger()->info("Succeeded on attempt {$attempt}");
        }
    })
    ->run(fn () => $api->request());
```

### Success callback

[](#success-callback)

```
$result = Retry::times(5)
    ->backoff(baseMs: 100)
    ->onSuccess(function (RetryResult $r) {
        logger()->info("Succeeded after {$r->attempts} attempt(s)");
    })
    ->run(fn () => $api->request());
```

### Checking retry status

[](#checking-retry-status)

```
$result = Retry::times(3)->run(fn () => $service->call());

if ($result->wasRetried()) {
    logger()->warning("Operation required retries: {$result->attempts} attempts");
}

echo $result->totalDuration(); // Total elapsed time in milliseconds
```

API
---

[](#api)

MethodDescription`Retry::times(int $maxAttempts)`Create a retry builder with a maximum number of attempts`Retry::forever()`Create a retry builder that retries indefinitely`->backoff(bool $exponential = true, int $baseMs = 100, int $maxMs = 10000)`Configure exponential (or constant when `$exponential = false`) backoff`->onTimeout(callable $callback)`Callback invoked with the last exception (or null) when `maxDuration` is exceeded`->linear(int $delayMs)`Configure linear backoff`->constant(int $delayMs)`Configure constant delay`->jitter(bool $enabled)`Enable or disable jitter`->onlyIf(callable $predicate)`Only retry when predicate returns true`->except(string ...$exceptionClasses)`Exclude specific exception types from retrying`->shouldRetry(callable $predicate)`Predicate receiving exception and attempt number; return false to stop`->retryOnlyOn(string ...$exceptionClasses)`Only retry for the given exception types (sugar for `shouldRetry`)`->getAttempts()`Get the total number of attempts made after execution`->maxDuration(int $ms)`Set maximum total duration for all attempts`->beforeRetry(callable $callback)`Callback invoked before each retry`->afterRetry(callable $callback)`Callback invoked after each attempt`->onSuccess(callable $callback)`Callback invoked with `RetryResult` after successful execution`->run(callable $operation)`Execute the operation with retry logic`$result->wasRetried()`Returns `true` if more than one attempt was made`$result->totalDuration()`Total elapsed time across all attempts in millisecondsDevelopment
-----------

[](#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/php-retry)

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

💡 [Suggest features](https://github.com/philiprehberger/php-retry/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

42

—

FairBetter than 89% of packages

Maintenance88

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 92.9% 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 ~3 days

Total

8

Last Release

80d 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 (13 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

retryJitterbackoffexponentialresilience

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[eventsauce/backoff

Back-off strategy interface

70834.8k8](/packages/eventsauce-backoff)[yriveiro/php-backoff

Simple backoff / retry functionality

2679.3k1](/packages/yriveiro-php-backoff)[vkartaviy/retry

The library for repeatable and retryable operations

29229.5k2](/packages/vkartaviy-retry)[tobion/retry

A generic library to retry an operation in case of an error. You can configure the behavior like the exceptions to retry on.

15450.7k](/packages/tobion-retry)[gabrielanhaia/laravel-circuit-breaker

Laravel integration for PHP Circuit Breaker — multiple storage drivers, middleware, Artisan commands, and event system

491.6k](/packages/gabrielanhaia-laravel-circuit-breaker)

PHPackages © 2026

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