PHPackages                             hammerstone/flaky - 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. hammerstone/flaky

Abandoned → [aaronfrancis/flaky](/?search=aaronfrancis%2Fflaky)Library[Utility &amp; Helpers](/categories/utility)

hammerstone/flaky
=================

A Laravel package to elegantly handle flaky operations.

v1.0.0(1y ago)41441.2k9MITPHPPHP ^8.0CI passing

Since Mar 3Pushed 5mo ago5 watchersCompare

[ Source](https://github.com/aarondfrancis/flaky)[ Packagist](https://packagist.org/packages/hammerstone/flaky)[ RSS](/packages/hammerstone-flaky/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (7)Dependencies (6)Versions (9)Used By (0)

Flaky for Laravel
=================

[](#flaky-for-laravel)

Flaky for Laravel is a package that helps you handle operations that may have intermittent failures due to unreliable third-parties.

[![Latest Version on Packagist](https://camo.githubusercontent.com/592fce12da3b337e03d8ca046687408c068762626bdaaa0f13b913557db14c5e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6161726f6e6672616e6369732f666c616b79)](https://packagist.org/packages/aaronfrancis/flaky)[![Total Downloads](https://camo.githubusercontent.com/9b069442e667ea933155e77151ce801ea8fb27c52cb9c66bea42d0b795300af1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6161726f6e6672616e6369732f666c616b79)](https://packagist.org/packages/aaronfrancis/flaky)[![License](https://camo.githubusercontent.com/352add5041041fcd66dbf5ee55c1d2de11fc948c48121fb2e2786782f569fff1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6161726f6e6672616e6369732f666c616b79)](https://packagist.org/packages/aaronfrancis/flaky)

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

[](#requirements)

- PHP 8.1+
- Laravel 10, 11, or 12

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

[](#installation)

You can install the package via Composer:

```
composer require aaronfrancis/flaky
```

Usage
-----

[](#usage)

Let's say you have a flaky piece of code that fails 20% of the time:

```
if (Lottery::odds(1 / 5)->choose()) {
    throw new Exception("Oops");
}
```

But you don't care if it fails, as long as it doesn't fail for more than an hour. Then you could wrap that code up in Flaky protections.

```
Flaky::make('my-flaky-code')
    ->allowFailuresForAnHour()
    ->run(function() {
        if (Lottery::odds(1 / 5)->choose()) {
            throw new Exception("Oops");
        }
    })
```

Now, exceptions will be silenced unless the operation hasn't succeeded in an hour.

Each instance of flaky code requires a unique ID passed through to the `make` method. This is how we keep track of failures over time. You can make up whatever you want, it's just a cache key.

Flaky uses your default cache store. That may need to be configurable in the future.

Throwing Exceptions
-------------------

[](#throwing-exceptions)

You have several different ways to control when exceptions are thrown:

### Time Based

[](#time-based)

If you want to throw an exception after a certain period of time, you have several methods available to you.

- `allowFailuresForAMinute()`
- `allowFailuresForMinutes($minutes)`
- `allowFailuresForAnHour()`
- `allowFailuresForHours($hours)`
- `allowFailuresForADay()`
- `allowFailuresForDays($days)`
- `allowFailuresFor($seconds = 0, $minutes = 0, $hours = 0, $days = 0)`

If your callback throws an exception, Flaky will check to see if it's still within the grace period. If it is, the exception will be captured.

If your callback succeeds, the deadline will be reset.

### Consecutive Failures

[](#consecutive-failures)

If you'd prefer to take a numeric approach instead of a time-based approach, you can use the `allowConsecutiveFailures`method.

```
Flaky::make('my-flaky-code')
    // It can fail ten times in a row.
    ->allowConsecutiveFailures(10)
    ->run(function() {
        //
    })
```

Now your function can fail 10 times in a row without alerting you, but on the 11th failure the exception will be thrown. If the callback succeeds, the consecutive failure counter will be reset.

### Total Failures

[](#total-failures)

If you want to throw an exception after a total number of failures, regardless of successes, you can use the `allowTotalFailures` method.

```
Flaky::make('my-flaky-code')
    // It can fail ten times total.
    ->allowTotalFailures(10)
    ->run(function() {
        //
    })
```

On the 11th failure, the exception will be thrown. The counter will be reset only after the exception has been thrown, but not for successful invocations. You can think of this as "Throw every 11th exception, regardless of successes."

### Combining

[](#combining)

You can combine the three methods in any way you like.

```
Flaky::make('my-flaky-code')
    // Alert after an hour.
    ->allowFailuresForAnHour()
    // Alert after the third consecutive failure.
    ->allowConsecutiveFailures(3)
    // Alert after the tenth failure.
    ->allowTotalFailures(10)
    ->run(function() {
        //
    })
```

Filtering by Exception Type
---------------------------

[](#filtering-by-exception-type)

If you only want Flaky to handle certain types of exceptions, use `forExceptions()`. Any other exception types will be thrown immediately.

```
Flaky::make('my-flaky-code')
    ->allowFailuresForAnHour()
    // Only handle TimeoutExceptions with flaky protection
    ->forExceptions([TimeoutException::class])
    ->run(function() {
        // TimeoutException will be handled by Flaky
        // Any other exception will be thrown immediately
    })
```

Handling Failures
-----------------

[](#handling-failures)

By default, Flaky will `throw` the exception when it occurs outside of your defined bounds. You have several options for customizing this behavior.

### Reporting instead of throwing

[](#reporting-instead-of-throwing)

You can choose to `report` that exception instead of throwing it, using Laravel's `report` method.

```
Flaky::make('my-flaky-code')
    ->allowFailuresForAnHour()
    // Don't throw, but use `report()` instead.
    ->reportFailures()
    ->run(function() {
        //
    })
```

This allows you to still get the alert, but carry on processing if you need to. (This is helpful for loops or long-running processes.)

### Custom Failure Handler

[](#custom-failure-handler)

For complete control over what happens when bounds are exceeded, use `handleFailures()`:

```
Flaky::make('my-flaky-code')
    ->allowFailuresForAnHour()
    ->handleFailures(function($exception) {
        // Log it, notify Slack, send an email, etc.
        Log::error('Flaky operation failed', ['exception' => $exception]);
    })
    ->run(function() {
        //
    })
```

Retrying
--------

[](#retrying)

If you want to immediately retry a bit of flaky code, you can use the `retry` method, which uses Laravel's `retry`helper under the hood. Any failures that happen as a part of the retry process don't count toward the total or consecutive failures. If your function is retried the maximum times and does not succeed, then that counts as one failure.

```
Flaky::make('my-flaky-code')
    ->allowFailuresForAnHour()
    // Retry 3 times, with 500ms between.
    ->retry(3, 500)
    ->run(function() {
        //
    })
```

You can also choose to retry a *single type* of exception

```
Flaky::make('my-flaky-code')
    ->allowFailuresForAnHour()
    // Only retry TimeoutExceptions
    ->retry(3, 500, TimeoutException::class)
    ->run(function() {
        //
    })
```

Or multiple types of exceptions

```
Flaky::make('my-flaky-code')
    ->allowFailuresForAnHour()
    // Only retry TimeoutExceptions and FooBarExceptions
    ->retry(3, 500, [TimeoutException::class, FooBarException::class])
    ->run(function() {
        //
    })
```

Or pass through your own method:

```
Flaky::make('my-flaky-code')
    ->allowFailuresForAnHour()
    // Pass through your own $when callback
    ->retry(3, 500, function($exception) {
        //
    })
    ->run(function() {
        //
    })
```

Accessing the result
--------------------

[](#accessing-the-result)

Flaky will return a `Result` class for your use.

```
$result = Flaky::make('my-flaky-code')
    ->allowFailuresForAnHour()
    ->run(function() {
        return 1;
    });

$result->value; // 1
$result->failed; // false
$result->succeeded; // true
$result->exception; // null. Would be populated if an exception was thrown.
$result->throw(); // Throws the exception if present, returns $this if not (for chaining).
```

Handling Exceptions Yourself
----------------------------

[](#handling-exceptions-yourself)

If you're catching exceptions yourself and want to pass them to Flaky, use the `handle()` method:

```
try {
    $this->riskyOperation();
} catch (Exception $e) {
    // Let Flaky decide whether to throw or suppress
    Flaky::make('my-flaky-code')
        ->allowFailuresForAnHour()
        ->handle($e);
}
```

Disabling Flaky Protection
--------------------------

[](#disabling-flaky-protection)

### Per-Instance

[](#per-instance)

You can disable Flaky protection for a specific instance:

```
Flaky::make('my-flaky-code')
    ->allowFailuresForAnHour()
    ->disableFlakyProtection()
    ->run(function() {
        // Exceptions will be thrown immediately
    });
```

### Local Environment Only

[](#local-environment-only)

To disable protection only in your local environment:

```
Flaky::make('my-flaky-code')
    ->allowFailuresForAnHour()
    ->disableLocally() // Only disables when app()->environment('local')
    ->run(function() {
        //
    });
```

### Globally

[](#globally)

To disable all Flaky protection across your application:

```
// Disable all Flaky protection
Flaky::globallyDisable();

// Re-enable all Flaky protection
Flaky::globallyEnable();
```

This is useful for testing or debugging when you want all exceptions to surface immediately.

Flaky Commands
--------------

[](#flaky-commands)

If you have entire commands that are Flaky, you can use the `FlakyCommand` class as a convenience.

```
class FlakyTestCommand extends Command
{
    protected $signature = 'flaky {--arg=} {--flag}';

    public function handle()
    {
        FlakyCommand::make($this)
            ->allowFailuresForAnHour()
            ->run([$this, 'process']);
    }

    public function process()
    {
        throw new Exception('oops');
    }
}
```

This command will now have Flaky protections, but *only* when invoked by the scheduler. If you run this command manually, Flaky is not engaged and you'll get all the exceptions as you would have otherwise.

### Flaky Command IDs

[](#flaky-command-ids)

The `FlakyCommand::make($this)` call will set the unique Flaky ID for you, based on the command's signature. By default, every invocation of an command is treated under the same key. If you want to vary that based on user input, you can use the `varyOnInput` method.

```
class FlakyTestCommand extends Command
{
    protected $signature = 'flaky {--arg=} {--flag}';

    public function handle()
    {
        FlakyCommand::make($this)
            ->allowFailuresForAnHour()
            // Consider the `arg` and `flag` input when creating the unique ID.
            ->varyOnInput()
            ->run([$this, 'process']);
    }
}
```

If you want to vary on particular input instead of all the input, you can pass an array of keys. This is useful for when each `--arg` should have its own flaky protections, but varying the `--flag` shouldn't create a unique set of protections.

```
class FlakyTestCommand extends Command
{
    protected $signature = 'flaky {--arg=} {--flag}';

    public function handle()
    {
        FlakyCommand::make($this)
            ->allowFailuresForAnHour()
            // Consider only the `arg` input when creating the unique ID.
            ->varyOnInput(['arg'])
            ->run([$this, 'process']);
    }
}
```

License
-------

[](#license)

The MIT License (MIT).

Support
-------

[](#support)

This is free! If you want to support me:

- Sponsor my open source work: [aaronfrancis.com/backstage](https://aaronfrancis.com/backstage)
- Check out my courses:
    - [Mastering Postgres](https://masteringpostgres.com)
    - [High Performance SQLite](https://highperformancesqlite.com)
    - [Screencasting](https://screencasting.com)
- Help spread the word about things I make

Credits
-------

[](#credits)

Flaky was developed by Aaron Francis. If you like it, please let me know!

- Twitter:
- Website:
- YouTube:
- GitHub:

###  Health Score

46

—

FairBetter than 93% of packages

Maintenance58

Moderate activity, may be stable

Popularity43

Moderate usage in the ecosystem

Community17

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 73.7% 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 ~120 days

Recently: every ~180 days

Total

7

Last Release

447d ago

Major Versions

v0.1.5 → v1.0.02025-02-25

### Community

Maintainers

![](https://www.gravatar.com/avatar/033238953a59b9223a1bde703b5e4254e63c7412195da1cb9de5af44bf53fc0a?d=identicon)[aarondfrancis](/maintainers/aarondfrancis)

---

Top Contributors

[![aarondfrancis](https://avatars.githubusercontent.com/u/881931?v=4)](https://github.com/aarondfrancis "aarondfrancis (42 commits)")[![mateusjatenee](https://avatars.githubusercontent.com/u/10816999?v=4)](https://github.com/mateusjatenee "mateusjatenee (11 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (3 commits)")[![spaantje](https://avatars.githubusercontent.com/u/477362?v=4)](https://github.com/spaantje "spaantje (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/hammerstone-flaky/health.svg)

```
[![Health](https://phpackages.com/badges/hammerstone-flaky/health.svg)](https://phpackages.com/packages/hammerstone-flaky)
```

###  Alternatives

[barryvdh/laravel-ide-helper

Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.

14.9k123.0M687](/packages/barryvdh-laravel-ide-helper)[wnx/laravel-stats

Get insights about your Laravel Project

1.8k1.8M7](/packages/wnx-laravel-stats)[orchestra/canvas

Code Generators for Laravel Applications and Packages

20917.2M158](/packages/orchestra-canvas)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)[flarum/core

Delightfully simple forum software.

211.3M1.9k](/packages/flarum-core)[interaction-design-foundation/laravel-geoip

Support for multiple Geographical Location services.

17221.0k3](/packages/interaction-design-foundation-laravel-geoip)

PHPackages © 2026

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