Start free trial
Start free trial Log in

14-day free trial. No credit card.

What is a correlation ID?

  • Glossary
  • 3 minute read

What is a correlation ID and how do I add one to Laravel?

A correlation ID is a unique identifier attached to every log, span, and downstream request for a single user action, so you can reconstruct what happened end-to-end. In Laravel, add a middleware that generates an ID (or reuses the client's X-Request-Id header), add it to Laravel's Context so every log line carries it, and propagate it on outbound HTTP calls. When paired with a trace ID (from nightwatch or OpenTelemetry), you get log-trace correlation in every incident postmortem.

Updated

A correlation ID is the cheapest piece of observability you can add, and one of the highest-leverage. It's a string you generate once per request and attach to everything that request touches. That's the whole idea. The payoff shows up the first time you have to answer "what happened to this one user at 14:23" and you can pull the entire story with a single filter instead of stitching it together from timestamps.

The 3am incident use case

A customer reports their checkout failed at 14:23. Without a correlation ID, you grep logs by timestamp + user ID, miss half the story because cross-service logs don't share keys, and reconstruct the flow by guessing. With a correlation ID: one grep '5c1d9e2a-...' across every log source and you have the full timeline.

Implementing in Laravel

app/Http/Middleware/AssignRequestId.php
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Str;

class AssignRequestId
{
    public function handle(Request $request, Closure $next)
    {
        $id = $request->header('X-Request-Id') ?: Str::uuid()->toString();

        Context::add([
            'request_id' => $id,
            'user_id' => auth()->id(),
            'route' => $request->route()?->uri(),
        ]);

        $response = $next($request);
        $response->headers->set('X-Request-Id', $id);

        return $response;
    }
}

Append it to the web and api groups in bootstrap/app.php with $middleware->web(append: [AssignRequestId::class]) and the same for api. Global middleware runs before routing and before the session starts, so there the route and the user aren't known yet. Laravel adds Context values to every log line written after this point, so each one carries request_id. The response header lets clients report the ID when filing bug reports.

Propagating to outbound HTTP

app/Providers/AppServiceProvider.php
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Facades\Http;
use Psr\Http\Message\RequestInterface;

public function boot(): void
{
    Http::globalRequestMiddleware(function (RequestInterface $request) {
        $id = Context::get('request_id');

        return $id ? $request->withHeader('X-Request-Id', $id) : $request;
    });
}

This adds the header to every call made through the Http facade. Read the ID from Context, not from the incoming request: if the client didn't send X-Request-Id, the incoming header is empty and only Context holds the ID you generated. If you use OpenTelemetry, don't copy the incoming traceparent onto outbound calls either. Let the OTel propagator inject it, so the header names your outbound span as the parent rather than the upstream caller's.

Correlation ID vs trace ID

Pre-OpenTelemetry era: X-Request-Id was the common header, implementations varied. Post-OTel: use W3C traceparent. It encodes trace_id + span_id + sampling flag in one header, and every OTel-instrumented service understands it natively.

For interoperability, send both. X-Request-Id for simple log correlation, traceparent for tracing tooling. They can carry the same value if you want: use the 32-character trace ID as your request ID.

What to include in log context

Beyond the correlation ID itself:

  • user_id (hashed or numeric, not PII)
  • route or controller
  • deploy_sha (git SHA of the running build)
  • env (production, staging)

Don't lose it at the queue boundary

The place correlation IDs quietly break is the queue. A request dispatches a job and returns; the job runs seconds later in a different process, and unless you carried the ID across, its logs have no link to the request that caused them. Laravel's Context handles this for you: values added with Context::add() are stored with every job the request dispatches and restored when the job runs, so the job's logs carry the same request_id. Scheduled commands don't start from a request, so add your own ID with Context::add() at the start of the command. The ID is only as useful as the boundaries it survives.

See everything one request caused

Inside one Laravel app, NightOwl ties a request's queries, outgoing HTTP calls, dispatched jobs and exceptions to its trace ID and shows them on one timeline. You get that link without writing any header middleware.

No credit card needed.

Frequently asked questions

Anything else, write to support@usenightowl.com

What is a correlation ID?

A unique identifier attached to every log line, span, and downstream request associated with a single user action or request. It lets you reconstruct 'what happened' for that request across logs, traces, and downstream services. Often called a request ID, trace ID, or transaction ID depending on context. The terms overlap, and in many systems they name the same value.

How do I add a correlation ID in Laravel?

Generate one in a middleware (or reuse the client's X-Request-Id header if they sent one), add it to Laravel's Context with Context::add(), and propagate it on outbound HTTP calls. Every log line for that request will carry the ID, and so will any job it dispatches. Combine with a trace ID from OTel or Nightwatch to correlate logs with traces.

What's the difference between a correlation ID and a trace ID?

Often they're the same thing. OpenTelemetry uses trace_id as the 16-byte correlation ID propagated across services. Older systems invented their own (X-Request-Id, X-Correlation-ID). When in doubt, use OTel's trace_id. It's the de facto standard and tools understand it natively.

Should I log the correlation ID on every log line?

Yes, unconditionally. It's the single most valuable piece of metadata for incident response: you can pull every log line for a broken request in a single query. In Laravel, Context::add('request_id', $id) in a middleware handles this for all downstream logs, including those written by queued jobs the request dispatched.

How do I propagate a correlation ID to external APIs?

Pass it as a header on every outbound request. The W3C standard is traceparent (which encodes trace_id, span_id, and sampling flag). A simpler per-request header is X-Request-Id, and many APIs echo it back in their logs so you can cross-reference. With Laravel's Http facade, register Http::globalRequestMiddleware() once in AppServiceProvider::boot() to add X-Request-Id from Context::get('request_id') to every outbound call.

Does Laravel generate a correlation ID automatically?

Not in the framework core. Laravel's nightwatch package generates one per request for internal tracing. Otherwise add a simple middleware: if the client sent X-Request-Id use it, else Str::uuid()->toString(). Add it to Context, propagate on outbound calls.

Keep reading

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