- Introduction
- Installation
- Making Attempts
- Retry Configuration
- Fallback Handlers
- Exception Handling
- Lifecycle Hooks
- Conditional Execution
- Pipeline Integration
- Concurrent Execution
- Async Execution
- Laravel AI Integration
- Working with Results
- Events
- Testing
- Configuration
While building your application, you may encounter operations that can fail due to transient issues like network timeouts, API rate limits, or temporary service unavailability. Rather than letting these failures crash your application or writing repetitive try-catch blocks, Laravel Attempt provides a fluent, composable system for handling retries, fallbacks, and error recovery.
Attempt treats error handling as a first-class pipeline concern, allowing you to declaratively define how your application should respond when things go wrong. Whether you need simple retry logic with exponential backoff, complex fallback chains, or integration with Laravel’s native Pipeline, Attempt provides an expressive API that reads like natural language.
Attempt supports PHP 8.4 or newer and Laravel 12 or 13.
You may install Attempt into your project using the Composer package manager:
composer require yannelli/attemptGlobal behavior is configured with static methods called from a service provider, as described in the configuration documentation. The package's service provider is deferred, so it is only loaded when an attempt is actually made.
The simplest way to use Attempt is to wrap a potentially failing operation with the try method. To execute the attempt and retrieve the result, you may call the thenReturn method:
use Yannelli\Attempt\Facades\Attempt;
$result = Attempt::try(fn() => $api->call())->thenReturn();If you need to pass input to your callable, you may provide additional arguments to the try method:
$result = Attempt::try(MyAction::class, $order, $user)->thenReturn();You may also pass an array of callables to the try method. When an array is provided, each callable will be executed in order as a fallback chain. If the first callable fails, the second will be attempted, and so on:
$result = Attempt::try([
PrimaryProvider::class,
BackupProvider::class,
CachedResponse::class,
], $payload)->thenReturn();Attempt provides several methods for executing your attempt and retrieving the result:
| Method | Behavior |
|---|---|
then(Closure $callback) |
Transform and return the final result |
thenReturn() |
Return the processed value directly |
thenReturnOrFail() |
Return the value or throw on failure |
run() |
Return an AttemptResult object with metadata |
get() |
Alias for thenReturn() |
value() |
Alias for thenReturn() |
For more complex operations, you may create dedicated attemptable classes. These classes should implement the Attemptable interface and define a handle method that receives the input and returns a result:
use Yannelli\Attempt\Contracts\Attemptable;
class FetchUserData implements Attemptable
{
public function handle(mixed ...$input): mixed
{
[$userId] = $input;
return Http::get("https://api.example.com/users/{$userId}")->json();
}
}Once you have defined your attemptable class, you may pass its class name to the try method:
$userData = Attempt::try(FetchUserData::class, $userId)
->retry(3)
->thenReturn();Sometimes you may want a class to define its own retry and fallback configuration. To accomplish this, your class may implement both the Attemptable and ConfiguresAttempt interfaces. The configureAttempt method receives an AttemptBuilder instance that you may use to define your preferred configuration:
use Yannelli\Attempt\Contracts\Attemptable;
use Yannelli\Attempt\Contracts\ConfiguresAttempt;
use Yannelli\Attempt\AttemptBuilder;
class ResilientApiCall implements Attemptable, ConfiguresAttempt
{
public function configureAttempt(AttemptBuilder $attempt): void
{
$attempt
->retry(3)
->exponentialBackoff(base: 100, max: 5000)
->withJitter(0.1);
}
public function handle(mixed ...$input): mixed
{
return Http::get('https://api.example.com/data')->json();
}
}When using a self-configuring class, the configuration is automatically applied:
$result = Attempt::try(ResilientApiCall::class)->thenReturn();By default, Attempt will not retry a failed operation. To enable retries, call the retry method and specify how many retries are allowed in addition to the initial attempt. For example, retry(3) permits up to four total executions:
Attempt::try($callable)
->retry(3)
->thenReturn();Often, you will want to wait between retry attempts to give transient issues time to resolve. Attempt provides several strategies for configuring delays between retries.
To wait a fixed number of milliseconds between all retries, pass an integer to the delay method:
Attempt::try($callable)
->retry(3)
->delay(100) // Wait 100ms between retries
->thenReturn();If you need different delays for each retry attempt, you may pass an array of millisecond values:
Attempt::try($callable)
->retry(3)
->delay([1000, 5000, 15000]) // 1s, 5s, 15s
->thenReturn();Exponential backoff progressively increases the delay between retries. This strategy is particularly useful when interacting with rate-limited APIs or overloaded services. The exponentialBackoff method accepts a base delay and an optional maximum delay:
Attempt::try($callable)
->retry(5)
->exponentialBackoff(base: 100, max: 30000) // 100ms, 200ms, 400ms, 800ms...
->thenReturn();Linear backoff increases the delay by a fixed increment with each retry:
Attempt::try($callable)
->retry(3)
->linearBackoff(base: 100, increment: 100) // 100ms, 200ms, 300ms
->thenReturn();To prevent multiple failing operations from retrying in lockstep (known as the “thundering herd” problem), you may add randomized jitter to your delays. The withJitter method accepts a percentage value that determines how much variance to apply:
Attempt::try($callable)
->retry(3)
->delay([1000, 5000, 10000])
->withJitter(0.2) // +/- 20% randomization
->thenReturn();For complete control over delay calculation, you may use the delayUsing method with a closure that receives the current attempt number and the exception that triggered the retry:
Attempt::try($callable)
->retry(5)
->delayUsing(fn(int $attempt, ?Throwable $e) => $attempt * 1000)
->thenReturn();If the closure returns null, the delay falls back to any delay or backoff strategy configured on the attempt.
You may also select a strategy by name using the backoff method. Any additional arguments are passed to the strategy's constructor. The built-in names are exponential, linear, fibonacci, decorrelated_jitter, and fixed; you may register your own names globally:
Attempt::try($callable)
->retry(5)
->backoff('exponential', base: 250, maxDelay: 10000)
->thenReturn();Delays are performed using Laravel's Sleep helper, so you may call Sleep::fake() in your tests to skip them.
Sometimes you may only want to retry an operation for specific types of failures. The retryIf method accepts a closure that receives the thrown exception and returns a boolean indicating whether the operation should be retried:
Attempt::try($callable)
->retry(3)
->retryIf(fn(Throwable $e) => $e instanceof ConnectionException)
->thenReturn();When an operation fails after exhausting all retries, you may want to execute a fallback operation instead of throwing an exception. Use the fallback method to define an alternative callable:
Attempt::try(PrimaryApi::class)
->fallback(BackupApi::class)
->thenReturn();You may define multiple fallbacks that will be tried in order. The first successful fallback wins:
Attempt::try(PrimaryApi::class)
->fallback([
SecondaryApi::class,
TertiaryApi::class,
fn() => Cache::get('fallback_value'),
])
->thenReturn();For a more expressive syntax, you may chain multiple orFallback calls:
Attempt::try(PrimaryApi::class)
->orFallback(SecondaryApi::class)
->orFallback(fn() => 'default')
->thenReturn();For fallback classes that need access to the original exception, implement the Fallbackable interface. This interface defines a handleFallback method that receives both the exception and the original input:
use Yannelli\Attempt\Contracts\Fallbackable;
class ApiErrorFallback implements Fallbackable
{
public function handleFallback(Throwable $e, mixed ...$input): mixed
{
Log::warning('Using fallback due to: ' . $e->getMessage());
return Cache::get('cached_response');
}
public function shouldSkip(Throwable $e): bool
{
// Skip this fallback for certain exceptions
return $e instanceof ValidationException;
}
}Attempt allows you to register exception handlers that will be invoked when specific exceptions occur. You may catch specific exception types or all exceptions:
// Catch specific exceptions
Attempt::try($callable)
->catch(ConnectionException::class, fn($e) => Log::error($e))
->catch(TimeoutException::class, fn($e) => Metrics::timeout())
->thenReturn();
// Catch all exceptions
Attempt::try($callable)
->catch(fn(Throwable $e) => Log::error($e))
->thenReturn();If you want to execute a handler but still throw the exception afterward, chain the throw method:
Attempt::try($callable)
->catch(fn($e) => Log::error($e))
->throw()
->thenReturn();To suppress all exceptions and return null on failure, use the quiet method:
Attempt::try($callable)
->quiet()
->thenReturn(); // Returns null on failureAttempt provides several hooks that allow you to execute code at specific points during the attempt lifecycle:
Attempt::try($callable)
->finally(fn($context) => Log::info('Attempt completed'))
->defer(fn($context) => Metrics::record($context->elapsed()))
->onRetry(fn($context, $e) => Log::warning("Retry {$context->attemptNumber}"))
->onSuccess(fn($context, $result) => Cache::put('last_result', $result))
->onFailure(fn($context, $e) => Alert::send($e))
->thenReturn();You may conditionally execute an attempt using the when and unless methods:
// Only execute if condition is true
Attempt::try($callable)
->when($shouldRun)
->thenReturn();
// Only execute if condition is false
Attempt::try($callable)
->unless($shouldSkip)
->thenReturn();
// With closure conditions
Attempt::try($callable)
->when(fn() => Feature::active('new-api'))
->thenReturn();Attempt integrates seamlessly with Laravel’s Pipeline. Use the pipeline method to execute a series of stages with built-in retry and fallback capabilities:
$result = Attempt::pipeline([
ValidateInput::class,
ProcessData::class,
SaveToDatabase::class,
])
->send($data)
->retry(2)
->thenReturn();You may also use AttemptPipe within a native Laravel Pipeline to wrap individual stages with retry logic:
use Illuminate\Support\Facades\Pipeline;
use Yannelli\Attempt\Pipes\AttemptPipe;
$result = Pipeline::send($data)
->through([
AttemptPipe::wrap(ExternalApiCall::class)
->retry(3)
->delay([100, 500, 1000]),
ProcessResponse::class,
])
->thenReturn();Use the concurrent method to execute a group of independent attempts and receive an array of results. Attempts currently execute in declaration order in the same process; this API groups results but does not provide parallel execution:
$concurrent = Attempt::concurrent([
fn() => Http::get('https://api1.example.com'),
fn() => Http::get('https://api2.example.com'),
fn() => Http::get('https://api3.example.com'),
]);
// Run all and get array of AttemptResult objects
$results = $concurrent->run();
// Get only successful results
$successful = Attempt::concurrent([...])->successful();
// Get only failed results
$failed = Attempt::concurrent([...])->failed();
// Get values directly
$values = Attempt::concurrent([...])->thenReturn();Use the race method to try operations in declaration order until one succeeds. Remaining operations are skipped after the first success:
$result = Attempt::race([
PrimaryProvider::class,
SecondaryProvider::class,
TertiaryProvider::class,
])->thenReturn();For long-running operations, you may dispatch an attempt to run asynchronously on the queue. The attempt is dispatched as a Yannelli\Attempt\Builders\AsyncAttemptJob through Laravel's bus, so Bus::fake() and Queue::fake() work as expected:
Attempt::try(LongRunningTask::class, $data)
->retry(3)
->async()
->onQueue('processing')
->then(fn ($value) => Log::info('Completed', ['value' => $value]))
->catch(fn (Throwable $e) => Log::error('Failed', ['error' => $e->getMessage()]))
->dispatch();When no connection or queue is given, the job uses your application's queue defaults. On Laravel 13, you may route every async attempt to a specific connection and queue using Laravel's queue routing in a service provider's boot method:
use Illuminate\Support\Facades\Queue;
use Yannelli\Attempt\Builders\AsyncAttemptJob;
Queue::route(AsyncAttemptJob::class, connection: 'redis', queue: 'attempts');For settings that queue routing cannot express, or on Laravel 12, you may extend the job and register your subclass. Because it is an ordinary Laravel job, you may define any job property or method, such as $timeout or middleware:
use Yannelli\Attempt\Builders\AsyncAttemptJob;
class ProcessAttempt extends AsyncAttemptJob
{
public $connection = 'redis';
public $queue = 'attempts';
public ?int $timeout = 120;
}use App\Jobs\ProcessAttempt;
use Yannelli\Attempt\Facades\Attempt;
Attempt::useAsyncJob(ProcessAttempt::class);The onConnection, onQueue, and timeout methods take precedence over the job's own defaults when dispatching.
If you need to execute the attempt synchronously instead (bypassing the queue), you may use the await method:
$result = Attempt::try(LongRunningTask::class, $data)
->retry(3)
->async()
->await(); // Runs synchronously, returns AttemptResultAttempt provides first-class integration with the official Laravel AI SDK. The SDK offers provider failover out of the box, but it only retries a request once, and only when a rate-limited or overloaded provider sends a short Retry-After header. Attempt fills this gap with retry policies tuned specifically for AI workloads, giving you three composable layers of resilience: retry each provider with backoff, fail over across providers, and finally fall back to a cached or canned value.
To get started, install the Laravel AI SDK alongside Attempt:
composer require laravel/aiThe ai method creates an attempt that is pre-configured for AI requests. Only transient failures will be retried: rate limits, provider overloads, provider connection errors, and retryable HTTP statuses (408, 429, and 5xx). Permanent failures such as insufficient credits, unknown tools, invalid requests, and malformed responses fail immediately:
use Yannelli\Attempt\Facades\Attempt;
$response = Attempt::ai(fn () => SupportAgent::make()->prompt($question))
->retry(3)
->thenReturn();When a provider supplies a Retry-After header with a rate limit response, Attempt will honor it (capped at 30 seconds). Otherwise, delays are calculated using decorrelated jitter starting at 500 milliseconds. You may replace that strategy with any backoff method while still honoring Retry-After hints:
Attempt::ai(fn () => SupportAgent::make()->prompt($question))
->retry(3)
->exponentialBackoff(base: 1000, max: 20000)
->thenReturn();To take full control of delays, including ignoring Retry-After hints, use the delayUsing method:
Attempt::ai(fn () => SupportAgent::make()->prompt($question))
->retry(3)
->delayUsing(fn (int $attempt) => $attempt * 1000)
->thenReturn();Because ai returns a standard attempt builder, the full Attempt API remains available. For example, you may combine AI retries with the SDK's provider failover and a non-AI fallback:
$response = Attempt::ai(fn () => SupportAgent::make()->prompt(
$question,
provider: ['openai-primary', 'anthropic-backup'],
))
->retry(2)
->fallback(fn () => CannedResponse::for($question))
->thenReturn();The ai method works equally well for the SDK's other operations, such as image generation and embeddings, since they throw the same transient exception types:
use Laravel\Ai\Embeddings;
$embeddings = Attempt::ai(fn () => Embeddings::for($chunks)->generate())
->retry(3)
->thenReturn();If you need to customize retry classification, the underlying policy is exposed as Yannelli\Attempt\Ai\AiRetryPolicy, and the standard retryIf method may be used to replace it entirely.
The SDK's provider failover moves to the next provider on the first failure. If you would rather retry each provider before failing over, add the RetryAiRequests middleware to your agent. Since agent middleware wraps each generation step and the SDK runs every step once per provider in the failover list, each provider will be retried independently:
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\HasMiddleware;
use Laravel\Ai\Promptable;
use Yannelli\Attempt\Ai\RetryAiRequests;
class SupportAgent implements Agent, HasMiddleware
{
use Promptable;
public function instructions(): string
{
return 'Answer questions about our product accurately and concisely.';
}
public function middleware(): array
{
return [
RetryAiRequests::times(2),
];
}
}After exhausting its retries, the middleware re-throws the original exception so the SDK's failover proceeds normally. You may customize the underlying attempt using the configureUsing method:
RetryAiRequests::times(2)->configureUsing(
fn ($attempt) => $attempt
->exponentialBackoff(base: 250, max: 10000)
->onRetry(fn ($context, $e) => Log::warning('Retrying AI request', [
'attempt' => $context->attemptNumber,
]))
);A few caveats apply when retrying AI operations:
- Streaming: streamed responses are lazy, so failures that occur while iterating a stream happen outside the attempt and will not be retried. Never re-issue a streamed request after output has reached the user, as this may duplicate or change previously delivered content.
- Tool-using agents: a failed prompt may have already executed tools during earlier generation steps. Retrying the prompt will run those tools again, so ensure your tools are idempotent before enabling retries on tool-using agents.
- Insufficient credits: the SDK treats insufficient credits as a failover condition, but retrying the same provider will not resolve it, so Attempt never retries these failures. Provider failover remains the correct remedy.
When you call the run method instead of thenReturn, you receive an AttemptResult object that provides detailed information about the attempt:
$result = Attempt::try($callable)->run();
// Check status
$result->succeeded(); // bool
$result->failed(); // bool
// Get values
$result->value(); // mixed - the result value
$result->exception(); // ?Throwable - the exception if failed
$result->attempts(); // int - number of attempts made
$result->resolvedBy(); // string - 'primary', 'retry:2', 'fallback:ClassName'The AttemptResult object supports monadic operations for functional-style programming:
$result->map(fn($value) => transform($value));
$result->getOrElse('default');
$result->getOrThrow();
$result->onSuccess(fn($value) => doSomething($value));
$result->onFailure(fn($e) => handleError($e));Attempt dispatches events throughout the attempt lifecycle, allowing you to hook into various stages for logging, monitoring, or other purposes:
| Event | When Fired |
|---|---|
AttemptStarted |
When the attempt begins |
AttemptSucceeded |
On successful completion |
AttemptFailed |
On each failure (before retry) |
RetryAttempted |
When a retry is initiated |
FallbackTriggered |
When a fallback is tried |
AllAttemptsFailed |
When all attempts and fallbacks fail |
If you need to disable events for a specific attempt, use the withoutEvents method:
Attempt::try($callable)
->withoutEvents()
->thenReturn();To disable events for every attempt, see the configuration documentation.
Attempt includes a convenient fake implementation for testing. Use the fake method to replace the Attempt facade with a test double:
use Yannelli\Attempt\Facades\Attempt;
it('retries on failure', function () {
Attempt::fake()->sequence([
new ConnectionException('Failed'),
new ConnectionException('Failed'),
['success' => true],
]);
$result = Attempt::try(MyApiCall::class)
->retry(3)
->run();
expect($result->succeeded())->toBeTrue();
expect($result->attempts())->toBe(3);
Attempt::assertAttemptedTimes(MyApiCall::class, 3);
});
it('uses fallback when all retries fail', function () {
Attempt::fake()->failFor(PrimaryApi::class, times: 5);
$result = Attempt::try(PrimaryApi::class)
->retry(3)
->fallback(BackupApi::class)
->run();
Attempt::assertFallbackUsed(BackupApi::class);
});Global configuration is stored statically. If your tests change it, call Attempt::flushState() in your test case's tearDown method to reset it.
To run the package’s test suite:
composer testGlobal behavior is configured with static methods on the Attempt facade, typically from the boot method of your application's AppServiceProvider. These methods never resolve the underlying manager, so they do not force the package's deferred service provider to load:
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Validation\ValidationException;
use Yannelli\Attempt\Facades\Attempt;
use Yannelli\Attempt\Strategies\ExponentialBackoff;
public function boot(): void
{
// Exceptions that are never retried, regardless of per-attempt rules...
Attempt::neverRetry([
ValidationException::class,
AuthorizationException::class,
]);
// Exceptions that are always retried while retries remain...
Attempt::alwaysRetry([
ConnectionException::class,
]);
// Named strategies for the backoff method; a built-in name may be replaced...
Attempt::defineBackoff('aggressive', fn () => new ExponentialBackoff(base: 50, multiplier: 3.0, maxDelay: 5000));
// Disable event dispatching for every attempt...
Attempt::disableEvents();
// Run async attempts with your own job subclass...
Attempt::useAsyncJob(ProcessAttempt::class);
}Global retry rules take precedence over retryIf, retryUnless, and strategy decisions, with never-retry rules checked first. Calling neverRetry or alwaysRetry again replaces the previously configured exceptions. A backoff strategy may be registered as a class name or as a closure that receives any arguments passed to backoff:
Attempt::try($callable)->retry(3)->backoff('aggressive')->thenReturn();To configure where async attempts are queued, use Laravel's queue routing or a custom job class as described in the async documentation.
The config/attempt.php file is deprecated and will be removed in 2.0. Until then, any setting that has not been configured statically falls back to the configuration file, so existing applications keep working. To convert a published configuration file, run the following command in your development environment:
php artisan attempt:migrate-configThe command writes the customized settings to app/Providers/AttemptServiceProvider.php, registers that provider in bootstrap/providers.php, and offers to delete config/attempt.php. Async settings become a Queue::route call on Laravel 13, or a generated app/Jobs/ProcessAttempt.php job when queue routing cannot express them. If a setting cannot be migrated, such as a queue connection read from an environment variable, the command explains why and keeps the configuration file. It asks for confirmation before running in production. See UPGRADING for details.
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.
