Laravel

Fixing cURL Error 28: Operation Timed Out in Laravel (Guzzle, Webhooks & Docker)


When your Laravel application makes an outbound HTTP request using Http::get(), Guzzle, or an integrated third-party SDK (such as Stripe, AWS, or Mailgun), your application might abruptly fail with:

cURL error 28: Operation timed out after 30001 milliseconds with 0 out of 0 bytes received
(see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://api.example.com/v1/endpoint

This error signifies that your PHP process initiated a network connection, but libcurl terminated it after waiting for the configured timeout limit (defaulting to 30 seconds) without receiving a valid response.


Root Causes at a Glance

  • External API Latency / Hangs: The destination server is experiencing high traffic, slow database processing, or is unreachable.
  • Firewall / Security Group Egress Rules: Your server or cloud instance (AWS EC2, DigitalOcean, Hetzner) allows inbound traffic on ports 80/443, but outbound traffic on port 443 or custom ports is dropped.
  • Docker Container DNS Resolution Delays: The Docker daemon attempts to resolve hostnames through local virtual interfaces or an unresponsive systemd-resolved socket before falling back.
  • IPv6 Routing Dead Ends: Your host machine or VPS advertises an IPv6 route that silently drops packets, causing cURL to hang until timeout before falling back to IPv4.
  • Synchronous Execution Inside Web Requests: Heavy API operations or batch calls are executing inside the synchronous controller cycle instead of an asynchronous queue worker.

Step 1: Extend HTTP Client & Connection Timeouts

If the third-party endpoint is legitimately slow (for example, generating a PDF or fetching historical reports), Laravel’s default 30-second ceiling may be insufficient. However, increasing the total timeout without setting a strict connection timeout is dangerous.

Configure explicit timeout() and connectTimeout() thresholds on the Laravel Http facade:

use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\ConnectionException;

$response = Http::timeout(60) // Maximum total time in seconds for response transfer
    ->connectTimeout(10)      // Maximum time waiting to establish the initial TCP handshake
    ->retry(3, 200, function ($exception) {
        return $exception instanceof ConnectionException;
    })
    ->get('https://api.example.com/v1/heavy-operation');
  • connectTimeout(10) ensures that if the destination IP is completely unreachable or dropping SYN packets, your PHP thread aborts in 10 seconds rather than hanging for 60 seconds.
  • retry(3, 200) automatically replays transient packet drops with a 200ms backoff only when a network-level ConnectionException occurs.

Step 2: Fix Docker Container DNS Resolution Delays

If cURL error 28 occurs specifically inside a containerized environment (such as Laravel Sail, Docker Compose, or WSL2), the timeout is frequently caused by broken container DNS forwarding.

To test this, open an interactive shell inside your running PHP container and run a verbose cURL check:

docker compose exec laravel.test curl -Iv https://api.example.com

If the terminal freezes on * Host api.example.com:443 was resolved or hangs for 5–15 seconds before showing the TLS handshake, your Docker bridge network is struggling to reach your host’s local DNS stub resolver.

Explicitly assign reliable upstream DNS resolvers inside your docker-compose.yml service block:

services:
  laravel.test:
    build:
      context: ./docker/8.3
    dns:
      - 8.8.8.8
      - 1.1.1.1

Or configure the Docker daemon globally on your Linux host in /etc/docker/daemon.json:

{
  "dns": ["8.8.8.8", "1.1.1.1"]
}

Restart your containers to apply the new networking rules:

docker compose down && docker compose up -d

Step 3: Force IPv4 Resolution (CURL_IPRESOLVE_V4)

Many cloud VPS providers and local ISPs assign partial IPv6 configurations that fail to route external traffic. When libcurl attempts to connect via IPv6 (AAAA record) first, it hangs until the connection timer expires before attempting IPv4 (A record).

You can verify if IPv6 is the culprit by forcing Guzzle and libcurl to resolve exclusively over IPv4:

use Illuminate\Support\Facades\Http;

$response = Http::withOptions([
    'curl' => [
        CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
    ],
])->get('https://api.example.com/v1/endpoint');

If adding CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4 makes the request return in milliseconds, you can register this globally inside your AppServiceProvider::boot() method using Http::globalOptions():

use Illuminate\Support\Facades\Http;

public function boot(): void
{
    Http::globalOptions([
        'curl' => [
            CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
        ],
    ]);
}

Step 4: Verify Outbound Firewall Rules (UFW / Cloud Security Groups)

If you recently hardened a production Ubuntu VPS or deployed to AWS/DigitalOcean, outbound traffic on custom webhook ports (like :8443 or :8080) or even standard HTTPS (:443) may be blocked.

Run this diagnostic command directly on your server via SSH to test raw TCP connectivity and measure lookup vs. connection timing:

curl -o /dev/null -s -w "DNS Lookup: %{time_namelookup}s\nTCP Connect: %{time_connect}s\nTLS Handshake: %{time_appconnect}s\nTotal: %{time_total}s\n" https://api.example.com
  • If DNS Lookup is fast (0.01s) but TCP Connect stays at 0.000s until the command times out, an outbound firewall (UFW, iptables, or Cloud Security Group) is dropping your outbound SYN packets, or the target server has rate-limited/blacklisted your server’s public IP.

Step 5: Offload Unreliable External Calls to Queued Jobs

Never execute slow or third-party HTTP requests synchronously inside a controller action. If an external webhook takes 25 seconds to time out, your PHP-FPM worker process remains locked for that entire duration. Under moderate traffic, this rapidly exhausts pm.max_children and brings down your entire Laravel site with a 502 Bad Gateway or 504 Gateway Timeout.

Always dispatch third-party HTTP integrations to a background queue worker:

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;

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

    public int $tries = 3;
    public int $timeout = 60;
    public array $backoff = [10, 30, 60];

    public function __construct(public array $payload) {}

    public function handle(): void
    {
        Http::timeout(30)
            ->connectTimeout(5)
            ->withOptions([
                'curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4],
            ])
            ->post('https://api.example.com/v1/webhooks', $this->payload)
            ->throw();
    }
}

Quick Diagnostic Checklist

Symptom Root Cause Fix
Fails after exactly 30s on large payloads Default Guzzle transfer limit Increase Http::timeout(60)->connectTimeout(10)
Hangs only inside Docker / Laravel Sail Broken container DNS stub resolver Add dns: [8.8.8.8, 1.1.1.1] to docker-compose.yml
Works via curl -4 in terminal, fails in PHP Broken IPv6 routing (AAAA lookup timeout) Set CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4
TCP Connect stays at 0.00s until timeout Outbound firewall or IP block Check UFW egress rules & cloud security groups
Entire site slows down when API is down Synchronous HTTP calls in controllers Offload Http::post() to queued background jobs