Resilient External API Calls: Retry Logic + Circuit Breakers

📖 1 minute read

When integrating with unreliable external APIs, implement retry logic with exponential backoff and circuit breaker patterns. Laravel’s HTTP client supports retries out of the box. For long-running failures, implement a circuit breaker to stop hitting a dead endpoint and avoid queue buildup. Log full HTTP context (status code, response body, headers) to debug external API issues effectively.

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

// Retry with exponential backoff (100ms, 200ms, 400ms)
$response = Http::retry(3, 100, throw: false)
    ->timeout(10)
    ->get('https://api.partner.com/data');

if ($response->failed()) {
    Log::error('Partner API failed', [
        'url' => $response->effectiveUri(),
        'status' => $response->status(),
        'body' => $response->body(),
        'headers' => $response->headers(),
    ]);
    
    throw new ExternalServiceException(
        'Partner API error: Failed to fetch data endpoint',
        ['response_status' => $response->status()]
    );
}

// For circuit breaker pattern, use package:
// composer require reshadman/laravel-circuit-breaker

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *