php - try, catch, and retry

php - try, catch, and retry

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Handling Transient Failures Without Boilerplate Code

When your application encounters an error that isn't caused by logic bugs—like a database connection timeout, a network hiccup, or a third-party API returning a 503 Service Unavailable—the immediate instinct is often to retry. The standard try-catch block handles the immediate crash, but simply logging the error and exiting leaves the user with a broken experience. To persist data or complete a transaction, you need to catch the exception, wait briefly, and attempt the operation again.

The challenge arises when you want to implement this pattern without bloating your code with nested try-catch blocks or extracting logic into a new function just for the sake of it. Since your entire workflow fits within a single function, you likely want to keep that cohesion while still managing retries effectively.

The Mechanics of Retry Logic

A naive retry loop looks like this:

$maxAttempts = 3;
$attempt = 0;

while ($attempt < $maxAttempts) {
    try {
        // do my stuff
        return processData(); 
    } catch (\Throwable $e) {
        $attempt++;
        
        if ($attempt === $maxAttempts) {
            throw $e; // Give up after the last attempt
        }
        
        // Sleep and try again
        usleep(100000); // 100ms delay
    }
}

This approach works, but it lacks nuance. Not every error deserves a retry. If your code fails because of a typo in a string literal or an invalid database schema, retrying won't fix that; it will just waste CPU cycles and delay the inevitable failure. You must distinguish between transient errors (network blips, rate limits) and permanent errors (logic bugs, bad data).

In Laravel, you can leverage the built-in exception handling to inspect the error type before deciding to retry. A common strategy is to catch only specific exceptions or check for generic network-related keywords in the message, though checking the HTTP status code or exception class is more robust if possible.

Implementing Exponential Backoff

One of the most critical trade-offs in retry logic is how long to wait between attempts. Linear backoff (waiting 100ms, then 200ms, then 300ms) often isn't aggressive enough to avoid hammering a failing service. Instead, exponential backoff is preferred. This means waiting 100ms, then 200ms, then 400ms, and so on.

You can implement this simply by calculating the sleep duration based on the attempt number:

$baseDelay = 100; // in milliseconds
$maxAttempts = 3;

for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
    try {
        return processData(); 
    } catch (\Throwable $e) {
        if ($attempt === $maxAttempts) {
            throw $e; // Final attempt exhausted
        }
        
        $delay = $baseDelay * pow(2, $attempt - 1);
        usleep($delay * 1000);
    }
}

However, there is a significant pitfall here: indefinite loops. If your retry logic retries forever until the process is killed by an external signal (like Ctrl+C or a timeout), it can cause issues in long-running scripts or queue workers. Always ensure there is a hard limit on attempts and consider setting a maximum total execution time for the retry block using Laravel's sleep or setTimeout mechanisms if available in your environment.

Keeping Code DRY Without Extracting Functions

You mentioned not wanting to extract logic into a separate function just to handle retries. While keeping code in one place seems appealing, repeating the retry loop structure across multiple functions violates the DRY (Don't Repeat Yourself) principle and makes maintenance harder. If you need to change the backoff strategy later, you'd have to edit every single function that uses it.

If your codebase is small and this pattern appears only once or twice, a local helper variable approach is acceptable. However, as complexity grows, even a small internal method like handleWithRetry() becomes preferable. It allows you to inject dependencies (like a logger or queue driver) without passing them through the function signature of your main business logic.

The key is balancing readability with maintainability. If the retry logic becomes complex—handling different exceptions for different retries, logging specific stack traces, or resetting connections—it is almost certainly time to encapsulate it. For simple cases, a tight loop within the existing function is perfectly fine, provided you clearly comment on why retries are being attempted and what constitutes a "success" vs. a "fatal error."

Final Considerations

Before deploying retry logic, ensure you have monitoring in place. If your application starts retrying operations constantly due to flaky infrastructure, you might need to alert on the frequency of these failures rather than just the final success or failure rate. Tools like Laravel Telescope or external APM solutions can help visualize how often your code enters the catch block and whether the exponential backoff is actually helping stabilize the system.

Our network