Navigation

Laravel

How to Handle Timeouts in an HTTP Request

Configure and handle HTTP request timeouts in Laravel to prevent hanging requests and improve application reliability with proper error handling.

Ever had your Laravel app freeze because an external API decided to take a coffee break? Here's how to prevent those awkward moments:

Use Laravel's HTTP client timeout methods to set appropriate limits:

use Illuminate\Support\Facades\Http;

// Set timeout for single request
$response = Http::timeout(30) // 30 seconds
    ->get('https://api.slow-service.com/data');

// Connection timeout (separate from read timeout)
$response = Http::connectTimeout(5) // 5 seconds to connect
    ->timeout(30) // 30 seconds total
    ->get('https://api.example.com/data');

// Handle timeout exceptions
try {
    $response = Http::timeout(10)
        ->get('https://api.external.com/users');
        
    if ($response->successful()) {
        return $response->json();
    }
} catch (\Illuminate\Http\Client\ConnectionException $e) {
    // Connection failed or timeout
    Log::error('API request timeout: ' . $e->getMessage());
    return []; // Fallback response
}

Advanced timeout handling with retries:

class ExternalApiService
{
    public function fetchData($url)
    {
        try {
            return Http::timeout(15)
                ->connectTimeout(5)
                ->retry(3, 1000) // 3 retries with 1 second delay
                ->get($url)
                ->throw()
                ->json();
                
        } catch (\Illuminate\Http\Client\RequestException $e) {
            if ($e->getCode() === CURLE_OPERATION_TIMEOUTED) {
                Log::warning("Request timeout for URL: {$url}");
                throw new ApiTimeoutException('External service timeout');
            }
            
            throw $e;
        }
    }
}

Table Of Contents

The Magic Behind Timeouts

Timeouts are your safety net against unreliable external services. Laravel's HTTP client (powered by Guzzle) gives you two types: connection timeouts (how long to wait for initial connection) and read timeouts (how long to wait for the response).

Configuration for different scenarios:

// Quick health checks
$response = Http::timeout(5)->get('https://api.example.com/health');

// File uploads (longer timeout)
$response = Http::timeout(120)
    ->attach('file', $fileContent, 'document.pdf')
    ->post('https://api.example.com/upload');

// Bulk operations
$response = Http::timeout(300) // 5 minutes
    ->post('https://api.example.com/bulk-import', $largeDataset);

// Global timeout configuration
// In a service provider or base service class
Http::macro('apiClient', function () {
    return Http::timeout(30)
        ->connectTimeout(10)
        ->retry(2, 500)
        ->withHeaders(['User-Agent' => 'MyApp/1.0']);
});

// Usage
$response = Http::apiClient()->get('https://api.example.com/data');

Related: Laravel Collections: Beyond Basic Array Operations | Laravel Events and Listeners: Building Decoupled Applications | Building Multi-tenant Applications with Laravel: A Comprehensive Guide | Performance Optimization: Speed in Web Applications | Error Handling & Exception Management 2025: Complete Guide

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Laravel