Flaky for Laravel

March 6th, 2023

Flaky for Laravel

Flaky is a Laravel package by Aaron Francis to help you handle intermittent failures caused by unreliable third parties.

In some cases, you don't care if the third-party code fails; you can wrap it in a Flaky call like so:

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

In the readme example, exceptions will be silenced unless the operation hasn't succeeded in an hour. The code uses the my-flaky-code passed to the make() method used as a cache key. At the time of writing, Flaky uses the default cache driver in your Laravel app to cache tracking of flaky code.

In the above example, if the call succeeds, the deadline for an hour will be rest. To say it another way, each subsequent success will push the failure counter back a full hour in the example above.

The Flaky package has various time-based methods you can use to configure the timeframe for your specific needs:

// Full custom
seconds: $seconds,
minutes: $minutes,
hours: $hours,
days: $days

This package also allows you to do count-based consecutive failures or a total count of failures. You can also combine the time-based counters with count-based counters:

$flaky->allowConsecutiveFailures(10)->run(/* ... */);
$flaky->totalFailures(10)->run(/* ... */);
->run(fn () => doStuff());

Other nifty features of this package include the following:

  • Immediate Retries
  • Reporting failures instead of throwing an exception
  • Access the result of the flaky code execution
  • Use flaky in Artisan with FlakyCommand

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.