In this lesson, you will learn how to maintain a request’s identity as it traverses multiple services by injecting correlation IDs into HTTP headers.
Why Trace Requests?
In a micro-services architecture, a single user request might trigger calls across a dozen different services. If something goes wrong, logs become fragmented. You might see an error in your "Order Service," but have no idea which "User Service" call initiated it. Distributed Tracing solves this by creating a unique fingerprint for every request that stays with it throughout its entire lifecycle.
The Correlation ID
The simplest way to implement this is through a Correlation ID. Think of this as a "tracking number" for your HTTP request.
When your entry point (such as an API Gateway) receives a request, it generates a unique string (a UUID). As that service makes downstream HTTP calls to other internal services, it passes this ID along in a custom header, commonly named X-Correlation-ID.
Here is how you might pass that ID along when using the built-in http module in Node.js:
const http = require('http');
function forwardRequest(incomingHeaders, outgoingOptions) {
// Extract existing ID or create a new one
const correlationId = incomingHeaders['x-correlation-id'] || generateUuid();
// Attach it to the outgoing request headers
const options = {
...outgoingOptions,
headers: {
...outgoingOptions.headers,
'X-Correlation-ID': correlationId
}
};
return http.request(options);
}
Why This Matters
By including this header, every micro-service in your cluster can log the X-Correlation-ID alongside its internal process logs. When an incident occurs, you can search your centralized logging system for that specific ID. You will instantly see the exact sequence of events, which services were involved, and how long each step took, effectively stitching the distributed flow back into a single, cohesive story.
This technique is the foundation of observability. Without it, you are looking at isolated data points; with it, you are looking at the actual path of execution across your infrastructure.
Key Takeaway: Injecting a unique Correlation ID into HTTP headers allows you to link fragmented logs across disparate services, providing a unified view of a single request’s journey through your distributed system.