The Right Way to Handle Retries and Backoff in Laravel

The Right Way to Handle Retries and Backoff in Laravel

Modern applications are often relies on external services, APIs or databases. These resources are integral parts of your application, but the communications with them can be unreliable.

There are many possible reasons for such failures — unstable networks, overloaded services, rate limits and many others. In short, there are various unexpected failures that may occur.

The most straightforward way to deal with such failures is to retry the operation. It may be tempting to simply use a while or for loop and keep trying until success, but such a solution can have some drawbacks.

In this article, we will discuss why such a solution is not always obvious and safe, and what alternatives Laravel provides. We will also talk about handling retryable failures, API and network issues, configuring the number of retries and delays between them, exponential delays and the all-important concept of idempotency.

The Problem with Manual Retries

Let's say you're making an API call to an external service. When it fails, your first thought might be something like this:

$success = false;
$attempts = 0;
while (!$success && $attempts < 3) {
    try {
        // Make API call
        $response = Http::get('https://external-api.com/data');
        if ($response->successful()) {
            $success = true;
            // Process data
        } else {
            // Log error, maybe wait a bit
            sleep(1);
        }
    } catch (\Exception $e) {
        // Log exception, maybe wait a bit
        sleep(1);
    }
    $attempts++;
}

if (!$success) {
    // Handle final failure
    Log::error('External API call failed after multiple retries.');
}

While this might work for the simplest of cases, there are several problems with this approach:

  • Your application thread will be blocked on the sleep() calls, needlessly consuming resources.
  • It uses a constant time interval between retries, which is not optimal. You should use exponential backoff, which waits progressively longer intervals between retries.
  • It doesn't handle idempotency. If the API call being retried is creating a resource or charging a card, simply retrying it will cause you to attempt to create a second resource or charge the card a second time.
  • Repetitive code. You would have to write this kind of logic everywhere you make an API call that requires retrying.

Fortunately, Laravel provides us with a better solution.

Introducing Laravel's retry() Helper

The Laravel framework provides a powerful function called retry(). The retry() helper method is used to call a given callback a certain number of times until it returns a result or the limit of attempts has been reached. It can be handy for making network requests and other operations that may result in a temporary failure.

Basic Syntax and Usage

The basic syntax is straightforward:

$result = retry($times, $callback, $sleepMilliseconds = 0, $when = null);
  • $times The maximum number of attempts to try the callback.
  • $callback The closure or callable to execute.
  • $sleepMilliseconds (optional) The number of milliseconds to wait between retries. This can be an integer for a fixed interval or an array for exponential backoff.
  • $when (optional) A boolean or a closure that determines whether to retry. By default, it will retry on any exception.

Let's refactor our previous API call example using the retry() helper:

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

try {
    $data = retry(3, function () {
        $response = Http::timeout(5)->get('https://external-api.com/data');

        if ($response->successful()) {
            return $response->json();
        }

        // If not successful, an exception will be thrown, triggering a retry
        // Or you can throw a specific exception if the service returns an error that might be transient.
        $response->throw(); // This will throw an HttpResponseException if not successful
    }, 1000); // Wait 1 second (1000 milliseconds) between retries

    // Process $data here
    Log::info('Successfully fetched data from external API.', ['data' => $data]);

} catch (\Exception $e) {
    Log::error('External API call failed after multiple retries.', ['error' => $e->getMessage()]);
    // Handle the final failure, maybe notify an admin or show a user-friendly error
}

As you can see, this is much cleaner. The retry() helper hides the loop, the exception handling, and the delay logic.

Exponential Backoff with retry()

For more involved retry scenarios, you often want to implement "exponential backoff", where you double the sleep duration with every retry, so as not to overwhelm a struggling service.

You can do that by passing an array of milliseconds to the $sleepMilliseconds parameter:

try {
    $data = retry(
        5, // Up to 5 attempts
        function () {
            $response = Http::timeout(5)->get('https://flaky-external-api.com/data');
            $response->throw(); // Throws an exception if status is 4xx or 5xx
            return $response->json();
        },
        [1000, 3000, 5000, 10000] // Wait 1s, then 3s, then 5s, then 10s
    );
    Log::info('Data fetched successfully with retries.', ['data' => $data]);
} catch (\Exception $e) {
    Log::error('Failed to fetch data after multiple attempts with exponential backoff.', ['error' => $e->getMessage()]);
}

If the array of delays is shorter than the number of attempts, the last delay in the array will be used for subsequent retries.

Custom Retry Conditions

Sometimes you want to retry only on certain exceptions or responses. The $when parameter can be used to define the custom retry conditions:

use Illuminate\Http\Client\ConnectionException;

try {
    $data = retry(
        3,
        function () {
            $response = Http::timeout(5)->get('https://example.com/sometimes-fails');
            $response->throw();
            return $response->json();
        },
        1000, // 1-second delay
        function (\Exception $e) {
            // Only retry if it's a connection error or a 503 Service Unavailable
            return $e instanceof ConnectionException ||
                   ($e instanceof \Illuminate\Http\Client\RequestException && $e->response->status() === 503);
        }
    );
    Log::info('Operation successful.');
} catch (\Exception $e) {
    Log::error('Operation failed completely.', ['error' => $e->getMessage()]);
}

It is useful when specific errors (like a 401 Unauthorized or a 404 Not Found) represent something that cannot be retried, and thus should cause immediate job termination.

Retries in Laravel Queues

For heavy, long-running, or vital processes that involve and rely upon external services, Laravel queues make life easier by deferring the execution of the task to the background. In addition, they provide a retry mechanism that is more versatile than the retry() helper for specific cases.

Configuring Basic Retries

Laravel can automatically retry failed queued jobs. You define the number of attempts and the retry delay in your job class.

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class ProcessExternalApiCall implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * The number of times the job may be attempted.
     *
     * @var int
     */
    public $tries = 5; // Attempt the job up to 5 times

    /**
     * The number of seconds to wait before retrying the job.
     *
     * @var int
     */
    public $retryAfter = 60; // Wait 60 seconds before retrying

    protected $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function handle(): void
    {
        try {
            $response = Http::timeout(10)->post('https://external-service.com/process', $this->data);

            if ($response->successful()) {
                Log::info('External service call successful.', ['data' => $this->data]);
                // Handle successful response
            } else {
                // If the response is not successful, we might throw an exception
                // Laravel will then retry the job if tries limit is not reached
                $response->throw();
            }
        } catch (\Exception $e) {
            Log::error('Failed to process external API call.', [
                'data' => $this->data,
                'error' => $e->getMessage(),
                'attempt' => $this->attempts(), // current attempt number
            ]);
            // Re-throw the exception to trigger a retry by the queue worker
            throw $e;
        }
    }
}

In this example, if the handle() method throws an exception, the job will be released back to the queue and attempted again after 60 seconds, up to 5 attempts. After 5 failed attempts, the job will be moved to the failed jobs table.

Exponential Backoff for Queued Jobs

You may also use exponential backoff for queued jobs by defining a backoff() method on your job class:

<?php

namespace App\Jobs;

// ... other uses ...

class ProcessExternalApiCall implements ShouldQueue
{
    // ... traits and constructor ...
public $tries = 5; public function backoff(): array { return [1, 5, 10, 30, 60]; // Wait 1s, 5s, 10s, 30s, 60s } public function handle(): void { // ... same handle logic as before ... } }

The backoff() method returns an array of delays, in seconds, that should be used for retrying the job. The first time the job is attempted, it will wait 1 second before retrying. The second time, it will wait 5 seconds, and so on. If the number of retries exceeds the number of elements in the array, the last element's value will be used.

Handling Failed Jobs

When a job exhausts all its retries, it will be moved to the failed_jobs table. You may use a failed() method on the job to perform any cleanup or other action needed when a job fails permanently:

<?php

namespace App\Jobs;

// ... other uses ...

class ProcessExternalApiCall implements ShouldQueue
{
    // ... tries, backoff, constructor ...

    public function handle(): void
    {
        // ... job processing logic ...
    }

    /**
     * Handle a job that failed to process.
     */
    public function failed(\Throwable $exception): void
    {
        // Send notification to admin, log final error, revert changes etc.
        Log::critical('ProcessExternalApiCall job permanently failed.', [
            'data' => $this->data,
            'exception' => $exception->getMessage(),
        ]);
        // For example, notify via Slack:
        // Notification::route('slack', config('services.slack.failed_jobs_webhook'))
        //             ->notify(new JobFailedNotification($this->data, $exception));
    }
}

The Critical Consideration: Idempotency

Now, let's discuss the most critical consideration when designing retry logic: idempotency. An operation is considered "idempotent" if repeating the same operation has the same effect as performing it once. In other words, performing an idempotent operation multiple times will not create any unintended side effects.

This consideration is essential because if you are retrying an operation that is not idempotent, you may end up with unintended side effects. For example, imagine that you are processing a payment, and your API call to the payment gateway succeeds, but your application fails to record the success in your database due to a database issue. If you retry the payment, and the operation of charging the payment gateway is NOT idempotent, you could end up charging the customer twice!

Examples of Idempotent vs. Non-Idempotent Operations

  • Idempotent Operations:
    • Set a user’s status to “active.” The second identical request will have the same effect as the first one.
    • Delete some resource. Deleting the same resource more than once will have the same effect as doing it once.
    • Set a resource to a particular state, e.g., set an order to “shipped.”

  • Non-Idempotent Operations:
    • Charge a customer’s credit card. The second identical request will make the customer pay twice.
    • Create a new record in the database that does not have a unique constraint or an idempotency key.
    • Send an email or an SMS. The second identical request will send the same message a second time. Increment a counter.

Making Operations Idempotent

Many external APIs, notably payment gateways, provide mechanisms for idempotency. They usually require a caller to send an additional "idempotency key", such as a UUID, in the request. The API then uses this key to ensure that a particular operation is not performed more than once in a given time window.

Always generate and save an idempotency key in cases when you are performing an operation that is not idempotent itself. The key must be added to an external request in order to make the whole operation idempotent.

use Illuminate\Support\Str;
use Illuminate\Support\Facades\Http;
use App\Models\Order;

class ProcessPaymentJob implements ShouldQueue
{
    // ...

    public function handle(): void
    {
        $order = Order::find($this->orderId);

        // Check if an idempotency key already exists for this order/payment attempt
        // Or generate a new one if it's the first attempt
        $idempotencyKey = $order->idempotency_key ?: (string) Str::uuid();
        $order->idempotency_key = $idempotencyKey;
        $order->save(); // Save the key for future retries

        try {
            $response = retry(
                3,
                function () use ($order, $idempotencyKey) {
                    $paymentData = [
                        'amount' => $order->amount,
                        'currency' => $order->currency,
                        'payment_method_id' => $order->payment_method_id,
                        // ... other payment details
                    ];

                    $response = Http::withHeaders([
                        'Idempotency-Key' => $idempotencyKey, // Important!
                    ])->post('https://payment-gateway.com/charge', $paymentData);

                    $response->throw(); // Throws on 4xx/5xx errors
                    return $response->json();
                },
                [1000, 3000, 5000]
            );

            // If we reached here, the payment was successful (or the gateway handled idempotency)
            $order->status = 'paid';
            $order->transaction_id = $response['transaction_id']; // Store transaction ID
            $order->save();

            Log::info("Order {$order->id} successfully paid.");

        } catch (\Exception $e) {
            // Payment failed after all retries, update order status and log
            $order->status = 'payment_failed';
            $order->error_message = $e->getMessage();
            $order->save();
            Log::error("Payment for order {$order->id} failed after retries.", ['error' => $e->getMessage()]);
            throw $e; // Re-throw to mark job as failed
        }
    }
}

This approach guarantees that in case of a network failure after the payment gateway processed the payment, the subsequent calls to the payment gateway that share the same idempotent key will not create a second charge. Instead, it will return the result of the successfully processed transaction.

When NOT to Retry (or Retry Carefully)

This is where the blind retries of database writes or payment operations can make things worse part comes in. While retries are generally good for transient failures, they are problematic for the following:

  • Non-Idempotent External Operations: As discussed, if an external API does not support idempotency and its operations have side effects (charge, send, create), then retries can result in duplicates; in that case it's better to implement a proper idempotency layer yourself or do not retry automatically but instead re-try manually.
  • Database Writes (especially without careful design):
    • If you are creating a new record with, say, User::create() and your retry logic does not check if the record was created before (say, by unique email), then you can have duplicates.
    • If your database write is part of a bigger transaction and the retry happens outside of it, then you can have database inconsistency.
    • Always make sure that any retriable database operation either has unique constraints to avoid duplicates or check first if the record to be created already exists.
  • Permanent Failures: If there is a mistake in logic (e.g., 401 Unauthorized, 404 Not Found, invalid input validation), retries will never succeed and will waste resources. To retry only on transient errors, use custom retry conditions with the retry() helper or your job's `handle()` method.
  • User-Facing Destructive Actions: Imagine a "delete account" operation. If the first attempt failed, you probably don't want the system to automatically retry and succeed without the user's explicit confirmation again.

For operations, which cannot be made idempotent or are too risky to automatically retry, it is often preferable to log the failure and alert an administrator to take manual action rather than risk corrupting data or losing money.

Best Practices

  • Embrace Queues for Critical Operations: In any process that requires the involvement or execution of other parties, or where the task is not instantaneous, defer the process to a queue. This will improve the process, enable proper retries, and provide a much better user experience.
  • Always Consider Idempotency: Before you do any retry logic, ask yourself, "is this operation idempotent?" if not, move on to ask, "how can I make it idempotent?" or "what are the risks of retrying this operation?"
  • Exponential Backoff: Whether in retry() or in your queued jobs, exponential backoff is generally better than linear delays when it comes to retrying failed operations. It gives the failed service time to recover.
  • Limited Retry Attempts: Don't retry forever, there should be a limit to the number of attempts made to retry a failed operation.
  • Log Everything: Logging is often key in debugging why things are failing, and why retries are not working. With queued jobs, you can log the current number of attempts being made using attempts() method.
  • Keep an Eye on Failed Jobs Table: The failed jobs table should be at the top of your dashboard. Anything that is going to be a recurring problem with your external services or within your application logic will be reflected in this table. Use it to your advantage.
  • Be Specific About What Can be Retried: Not every exception can or should be retried. Use $when in your retry() statement or logic in your handle() function to catch specific exceptions that warrant a retry.

Conclusion

Laravel has great tools to implement resilient apps. The retry() helper, plus the robust queue retry mechanisms, allow you to gracefully recover from various failures, without having to write error-prone, blocking and potentially unsafe loops yourself.

But with great power comes great responsibility. That is, if you're going to use retries, you must understand and be able to address the important concept of idempotency. Blind retries, especially of potentially expensive or dangerous operations such as database writes, can easily result in all sorts of mayhem. By appropriately applying Laravel's built-in tools, and understanding the idempotency of the operations performed, you can make sure that your application is robust, but also safe.

Thank you for reading this article 😊

For any query, do not hesitate to comment 💬









Previous Post Next Post

Contact Form