How do I set retry and backoff strategies for jobs that hit external APIs?
In Laravel, job retry and backoff for external APIs work in two layers. The job class controls how many attempts the job gets and how long the queue waits between them, using attributes such as #[Tries] and #[Backoff]. The HTTP client can add a few quick retries inside a single attempt, but only if you call Http::retry(). The decision that matters most is which failures deserve a retry at all, because a 429 needs a pause and a 422 will keep failing until the data changes.
Quick answer
Set a finite attempt limit with #[Tries], add increasing delays with #[Backoff], and keep Http::retry() to a few quick attempts for connection errors. On a 429, release the job for the Retry-After value (seconds or an HTTP date, with a fallback), retry 408 and 5xx errors, and fail on errors a retry cannot fix, such as 400 and 422. Decide 401 and 409 by the provider’s rules. Keep HTTP attempts and delays under the job timeout, and the job timeout under the queue’s retry_after.
How to set retry and backoff for a Laravel job that calls an external API
1. Cap attempts and exceptions
Set a maximum number of attempts on the job. The Laravel 13 queue documentation uses the #[Tries] attribute for this. A value on the job takes precedence over the --tries flag on queue:work, and --tries=0 retries forever, which is rarely safe against a third-party API. If you run an earlier Laravel version, the same settings live in public properties such as $tries.
#[MaxExceptions] fails the job after a set number of unhandled exceptions. A manual release() does not count toward that limit, but it does use up one attempt. Releases and exceptions therefore draw on the same #[Tries] budget.
namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Response;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\MaxExceptions;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\RateLimited;
use Illuminate\Queue\Middleware\ThrottlesExceptions;
use Illuminate\Support\Facades\Http;
use Throwable;
#[Tries(8)]
#[MaxExceptions(3)]
#[Timeout(30)]
class SyncCustomerToApi implements ShouldQueue
{
use InteractsWithQueue, Queueable;
public function __construct(
public string $url,
public array $payload,
) {}
}
This matters most for 429 responses. Each rate-limited release uses one attempt. If the provider stays rate limited for a while, a fixed #[Tries(8)] can run out before the API recovers, and the job fails even though nothing was wrong with it.
When release times are unpredictable, a time window fits better than an attempt count. Add a retryUntil() method and the job keeps retrying until that moment, however many attempts it takes. Laravel gives retryUntil() precedence when both are defined, so remove #[Tries] if you switch.
use DateTime;
public function retryUntil(): DateTime
{
return now()->plus(minutes: 30);
}
2. Add exponential backoff with jitter
By default, a job that throws an exception returns to the queue for immediate processing, so a worker hammers an API that is already struggling. The #[Backoff] attribute sets the wait in seconds. Pass an array for increasing delays. Laravel uses each value in turn and repeats the last one for later retries. The values below are examples only. Choose delays that match how quickly the provider recovers.
#[Backoff([10, 30, 90, 300, 900])]
class SyncCustomerToApi implements ShouldQueue
{
// ...
}
The attribute gives every job the same delays. If many jobs fail together, they all return together. To spread them out, replace the attribute with a backoff() method that adds a small random number of seconds.
public function backoff(): array
{
return array_map(
fn (int $seconds) => $seconds + random_int(0, 10),
[10, 30, 90, 300, 900]
);
}
A fixed delay also works. Use #[Backoff(30)] on the job, or --backoff=30 on the worker. Backoff applies to retries after an exception. A job you release yourself waits for the delay you pass to release(), or for its configured backoff if you call releaseUsingBackoff().
3. Keep in-request retries short
Laravel does not retry HTTP requests unless you call retry(). The Laravel 13 HTTP client documentation describes how it works:
- The first argument is the maximum number of attempts, including the first request.
retry(2, 200)means one initial request and at most one retry. - The second argument is the wait between attempts, in milliseconds.
- The optional third argument is a callback that decides whether a retry should happen at all.
- With
throw: false, you get the last response back instead of aRequestException. AConnectionExceptionis still thrown for connection failures.
These retries happen inside the current job run, so the worker stays busy while it waits. A queue retry is different: it runs the whole job again, including every HTTP attempt inside it. The two layers multiply. Three job attempts with three HTTP attempts each can send nine requests. Keep one layer conservative.
public function handle(): void
{
$response = Http::connectTimeout(5)
->timeout(10)
->retry(2, 200, fn (Throwable $e) => $e instanceof ConnectionException, throw: false)
->post($this->url, $this->payload);
$this->handleResponse($response);
}
4. Treat each status code differently
Not every failure should retry, and not every failure should stop the job. What each status means depends on the provider, so check its documentation before you copy these defaults.
| Status | Usual meaning | What the job usually does |
|---|---|---|
| 400 | Malformed request or failed validation | Fail the job. Fix the request, because a retry sends the same bad data. |
| 401 | Missing or expired credentials | Refresh the token if the provider supports it, then retry. Otherwise fail. |
| 403 | Usually a permission problem | Fail and alert. A retry will not grant access. |
| 408 | Request timed out, often temporary | Retry with backoff. |
| 409 | Conflict, handled differently by each API | Check the provider’s rules. Some use it for “already done”, others for races worth retrying. |
| 422 | Submitted data failed validation | Fail the job and correct the data. |
| 429 | Rate limit reached | Release the job for the Retry-After time. |
| 5xx | Server-side problem, usually temporary | Retry with backoff. The attempt limit still stops a permanent failure. |
private function handleResponse(Response $response): void
{
$status = $response->status();
if ($status === 429) {
$this->release($this->retryAfterSeconds($response));
return;
}
if ($status === 408 || $response->serverError()) {
$response->throw(); // counts as an exception, so the backoff delays apply
}
// Add provider-specific branches for 401 and 409 above this line.
if ($response->clientError()) {
$this->fail('API rejected the request with HTTP '.$status);
}
}
private function retryAfterSeconds(Response $response): int
{
$header = trim((string) $response->header('Retry-After'));
if (ctype_digit($header)) {
$seconds = (int) $header; // delay in seconds
} elseif (($timestamp = strtotime($header)) !== false) {
$seconds = $timestamp - time(); // HTTP date
} else {
$seconds = 60; // header missing or invalid
}
return max(1, min($seconds, 3600)); // example ceiling, adjust for your job
}
Retry-After can hold a number of seconds or an HTTP date. The code reads both, falls back to 60 seconds when the header is missing or invalid, and clamps the result so one odd value cannot park the job for hours. Pick a fallback and ceiling that fit your retry window. Every release() still uses one attempt, so cover the pauses you expect with enough attempts or a retryUntil() window.
5. Protect the API when it is down
Per-job backoff does not stop fifty queued jobs from hitting a struggling API one after another. Laravel ships two job middleware that help.
ThrottlesExceptions is exception-throttling middleware, not a full circuit breaker. The first constructor argument is the number of consecutive exceptions a job may throw before it is throttled. The second is how many seconds the job waits before its next attempt once throttled. Below the threshold, a failed job retries immediately unless you call backoff(), which delays it by a number of minutes. With (10, 5 * 60) and backoff(5), each failure before the threshold is delayed five minutes, and once ten consecutive exceptions have happened, the job waits 300 seconds before its next attempt. By default the throttling key is the job class name, so jobs of the same class share one count. Call by('key') to share a bucket between different jobs that call the same service. The Laravel documentation says to pair this middleware with time-based attempts, so use retryUntil() instead of #[Tries] on jobs that carry it.
RateLimited keeps your outbound calls under a limit. You define the limiter once, then attach it to the job. Base the limit on the provider’s real policy, including what it counts (per account, per API key, per IP) and over what time window. The number below is a placeholder.
// app/Providers/AppServiceProvider.php
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
public function boot(): void
{
RateLimiter::for('partner-api', function (object $job) {
return Limit::perMinute(60); // replace with the provider's actual limit
});
}
// in the job class (with ThrottlesExceptions, define retryUntil() as in step 1)
public function middleware(): array
{
return [
new RateLimited('partner-api'),
(new ThrottlesExceptions(10, 5 * 60))->backoff(5),
];
}
A job that exceeds the limit goes back to the queue with a delay based on the limit window, and that release uses an attempt. Add ->by() to the limit when the provider counts per account or key, and use dontRelease() if a rate-limited job should not be retried.
6. Align the three timeouts
Three timers run at once, and they must nest in the right order: all HTTP attempts and delays must finish before the job timeout, and the job timeout must end before the queue retries the job.
At the HTTP level, connectTimeout() limits how long Laravel waits to connect (10 seconds by default), and timeout() limits how long it waits for a response (30 seconds by default). Each attempt can use the full timeout(), so the worst case is roughly the number of attempts times the timeout, plus the delays between them. In the example above, two attempts of up to 10 seconds plus a 200 ms wait take about 20 seconds, which fits inside #[Timeout(30)].
The job timeout comes from #[Timeout] or the worker’s --timeout option, and a value on the job wins. Above both sits the queue’s own retry timer. Each connection in config/queue.php has a retry_after value, so the right number depends on your configuration. Amazon SQS has no retry_after. It uses the Default Visibility Timeout set in the AWS console. Keep the job timeout several seconds below that value. Otherwise the queue can hand the same job to a second worker while the first is still running, and the API call runs twice.
7. Make API operations safe to retry
A retry does not prove the first request failed. Say your job sends a payment request. The provider processes it, but the response is lost in a network interruption. Laravel retries the job and the customer is charged twice.
- Send an idempotency key when the API supports one, and build it from your own record ID rather than the attempt number.
- Give every operation a unique reference your system controls.
- Where the API allows it, check the status of an uncertain operation before you repeat it.
- Store each operation’s state (pending, succeeded, failed) in your own database so a retry can see what already happened.
This matters most for payments, orders, and emails, where a duplicate has real consequences.
8. Handle and monitor the final failure
Add a failed() method for alerts and cleanup. Laravel creates a new job instance before calling it, so any property changes made inside handle() are lost. Anything failed() needs to know, such as the last error or the state of the operation, should live in the database. Write it from handle(), then read it back in failed().
public function failed(?Throwable $exception): void
{
// Runs on a fresh job instance. Load state from the database,
// then alert the team, flag the record, or write a log entry.
}
Run php artisan queue:failed to list jobs that ran out of attempts. After you fix the cause, run php artisan queue:retry with the failed job ID.
Where to start
Start with a finite attempt limit, a short #[Backoff] array, and a clear rule for each status code the provider can return. Treat every number in this answer as an example and adjust it to the provider’s rate limits and response times. Add idempotency before the job touches money or customer email. If you want a second pair of eyes on queue reliability for an integration-heavy app, our Laravel development team works on exactly this kind of problem.
Related Answers
Still need help?
Questions about retries and queue reliability in Laravel?
If you're tuning retries, backoff, or rate limits for jobs that call external APIs, we're happy to walk through what you're seeing and what your options are.
