Start free trial
Start free trial Log in

14-day free trial. No credit card.

Track outgoing HTTP requests in Laravel

How to surface slow external API calls in Laravel with Http events, Guzzle middleware or an APM.

  • Guide
  • 3 min read

How do I track outgoing HTTP requests in Laravel?

Laravel's Http facade fires RequestSending and ResponseReceived events you can listen to. Log URL, method, status, and duration for each outbound call. For aggregation and per-host p95 trending, install an APM that records outgoing HTTP automatically. NightOwl's outgoing-requests dashboard groups by host with count, average and p95 duration, and 4xx and 5xx counts per destination. Each call also appears in the trace of the request or job that made it.

Updated

The calls your app makes to other people's APIs are the latency you can't fix by optimizing your own code, and the failures you can't prevent by writing correct code. Stripe has a slow afternoon, a shipping provider's API hangs, a third party you've never thought about quietly adds 400ms to checkout, and from your monitoring it just looks like "checkout got slower" with no obvious cause inside your app. Tracking outgoing HTTP turns "our app is slow" into "this specific downstream is slow," so you know whose problem it is.

Layer 1: Http facade events

Laravel's Http client fires three events you can listen to in a service provider:

  • RequestSending: before the request goes out
  • ResponseReceived: after a response arrives
  • ConnectionFailed: when the connection couldn't be established

app/Providers/AppServiceProvider.php

php
use Illuminate\Http\Client\Events\RequestSending;
use Illuminate\Http\Client\Events\ResponseReceived;
use Illuminate\Http\Client\Events\ConnectionFailed;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;

public function boot(): void
{
    Event::listen(function (ResponseReceived $event) {
        Log::info('Outgoing HTTP', [
            'url' => $event->request->url(),
            'method' => $event->request->method(),
            'status' => $event->response->status(),
            'duration_ms' => $event->response->transferStats?->getTransferTime() * 1000,
        ]);
    });

    Event::listen(function (ConnectionFailed $event) {
        Log::warning('HTTP connection failed', [
            'url' => $event->request->url(),
            'method' => $event->request->method(),
        ]);
    });
}

Good for audit trail. Missing: per-host aggregation. A single log line doesn't tell you Stripe is degraded. You need counts and percentiles over time.

Layer 2: Guzzle middleware

If you're on Guzzle directly (not Http::), use middleware:

php
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Illuminate\Support\Facades\Log;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

$stack = HandlerStack::create();
$stack->push(function (callable $handler) {
    return function (RequestInterface $request, array $options) use ($handler) {
        $start = microtime(true);

        // The handler returns a promise; log once the response arrives
        return $handler($request, $options)->then(
            function (ResponseInterface $response) use ($request, $start) {
                Log::info('Outgoing', [
                    'host' => $request->getUri()->getHost(),
                    'path' => $request->getUri()->getPath(),
                    'status' => $response->getStatusCode(),
                    'duration_ms' => round((microtime(true) - $start) * 1000, 2),
                ]);

                return $response;
            }
        );
    };
});

$client = new Client(['handler' => $stack]);

Layer 3: Per-host aggregation

The goal isn't logging every call. It's seeing which downstream services are hurting you. Aggregate by host:

  • Request count per host (which services do we depend on most?)
  • p95 duration per host (which service is slow?)
  • 4xx and 5xx counts per host (which service is failing?)
  • Failure-to-timeout ratio (is this connection issues or real errors?)

You can build this with an outgoing_requests table and a nightly rollup job, but then the table, the job and the charts are yours to maintain. An APM that records outgoing HTTP is usually the better tradeoff.

Set timeouts on every outgoing call

Raw Guzzle defaults to no timeout, so a hung downstream will hang your PHP worker indefinitely. Laravel's Http client sets 30 seconds (and a 10-second connect timeout) by default, which is still too long for most user-facing calls. Set your own:

php
// Set per-call (recommended for user-facing requests)
Http::timeout(5)
    ->connectTimeout(2)
    ->get('https://api.stripe.com/v1/charges');

// Set defaults for every call in AppServiceProvider::boot()
Http::globalOptions(['timeout' => 5, 'connect_timeout' => 2]);

// Always use ->throw() when you need to fail loudly
Http::timeout(5)->get($url)->throw();

Patterns that reduce outgoing HTTP pain

  1. Move to async jobs. If you can call an external API in a queued job instead of the request, do it. The user stops waiting on the third party's response time.
  2. Cache responses. Use Laravel's Cache facade with short TTLs for read-heavy external data (pricing tables, currency rates, etc.).
  3. Circuit break. When a downstream fails repeatedly, fail fast instead of waiting for every timeout. A simple cache-based failure counter works.
  4. Parallel calls. Http::pool() fires multiple requests concurrently, which turns three sequential 300ms calls into roughly one 300ms wait.
  5. Correlation IDs. Pass X-Request-Id on every outgoing call so downstream logs can be correlated back to the originating request.

Find the slow host behind a slow request

NightOwl does the per-host aggregation from Layer 3 without listener code, grouping every outbound call by host with its count, average and p95 duration, and 4xx and 5xx counts. Each call also appears in the trace timeline of the request or job that made it, so you can see which external API a slow endpoint was waiting on.

No credit card needed.

Terminal
composer require nightowl/agent
php artisan nightowl:install
php artisan nightowl:agent

Frequently asked questions

Anything else, write to support@usenightowl.com

How do I track outgoing HTTP requests in Laravel?

Laravel's Http facade fires RequestSending and ResponseReceived events. Listen to them in a service provider to log every outbound call with URL, method, status, and duration. For richer aggregation (grouping by host, p95 per host, 4xx and 5xx counts) use an APM like NightOwl that records outgoing HTTP automatically with full trace context.

What's the difference between Laravel's Http client and Guzzle?

Laravel's Http facade (since 7.x) is a wrapper around Guzzle that adds idiomatic helpers, a fake() testing API, and events (RequestSending, ResponseReceived, ConnectionFailed). Under the hood it's still Guzzle. If your code uses Guzzle directly, you won't get those events. Wrap calls in Http::send() or use Guzzle middleware for equivalent instrumentation.

How do I find which external API calls are slowing down my Laravel app?

Record every outgoing HTTP call's duration and group by host. You want to see p95 latency per downstream service: Stripe, Mailgun, your CRM webhook, etc. If your /checkout p95 is 2s and Stripe's API call p95 is 1.5s, you've found your bottleneck. NightOwl's outgoing-requests dashboard groups by host with average and p95 duration and 4xx and 5xx counts per destination.

How do I handle slow external APIs in Laravel?

Four mitigations in order of effectiveness: (1) Move the call off the request path: dispatch a job, poll for result, use webhooks. (2) Add a hard timeout: Http::timeout(5). Timeouts above your endpoint SLO are useless. (3) Use circuit-breaking (a cache-based failure counter works) to fail fast when a downstream is degraded. (4) Cache responses with TTL when the data is read-heavy.

Should I log every outgoing HTTP request body?

No. Request bodies often contain PII, API keys, or payment data. Log metadata (URL, method, status, duration, response size) but redact or omit bodies. If you need bodies for debugging, enable body logging conditionally (on errors only, or on a sample of requests) and scrub sensitive fields before storage.

How do I know if an external API call is failing silently?

You don't, unless you check the response status. Laravel's Http client doesn't throw on 4xx/5xx by default. You have to call throw(), throwIf(), or inspect $response->failed(). Define a macro per service that chains throw(), for example Http::macro('stripe', fn () => Http::baseUrl('https://api.stripe.com')->throw()), or listen to ResponseReceived and alert when status is >= 400. Silent failures on retry-in-background jobs are the worst offender.

Can I trace a Laravel request through all its outgoing HTTP calls?

Yes. Pass a correlation ID (X-Request-Id or W3C traceparent header) on every outgoing call and record it alongside the call metadata. Downstream services that log the header can be correlated back. Laravel's nightwatch package doesn't add that header for you, so set it yourself with Http::globalRequestMiddleware(). Inside your own app, both NightOwl and Nightwatch Cloud show outgoing calls per request in the trace view.

What's a reasonable timeout for outgoing HTTP in Laravel?

Depends on where you're calling from. From a user-facing request: 2-5 seconds max (your endpoint SLO bounds it). From a background job: 10-30 seconds with retries. From a webhook receiver: whatever your inbound timeout allows, minus processing overhead. Never call external APIs without a timeout you chose. Raw Guzzle defaults to no timeout, so a hung downstream can hang your PHP worker indefinitely. Laravel's Http client defaults to 30 seconds, which is still far too long for a user-facing request.

Flat pricing, whatever your traffic does

Every plan starts with a 14-day free trial. No credit card needed.

Hobby
$5 a month

One app for a side project. Issues and alerts, with a 14-day dashboard window.

Start my 14-day trial
TeamRecommended
$15 a month

Up to 3 apps and 5 people per team. Full history, the MCP server, data clearing and agent health.

Start my 14-day trial
Agency
$69 a month

Unlimited client apps and people, one overview of every app, and apps you can hand over.

Start my 14-day trial

Related

Find the slow API your app is waiting on

Every outgoing call is grouped by host with its p95, on your own traffic. No credit card needed.