Observability

Locate failures across order service requests using request correlation IDs, structured logs, metrics, and distributed tracing.

🎯 Introduction

After a user clicks “Create order,” the request may pass through the BFF, orders, and inventory. If the page eventually reports failure, where should we start? Order error logs alone might show only an inventory timeout, without revealing how many users were affected or where the request spent its time.

This article explores three troubleshooting questions: which requests were affected, which services they traversed, and what specifically failed. First we correlate two Express services' logs with one request ID, then examine metrics and distributed tracing, and finally investigate a failure.


🧱 Why One Service's Logs Are Not Enough

When a user creates an order, orders queries inventory. Both services produce logs, while many other users may be ordering simultaneously. Searching by time alone can mix unrelated requests.

Assign a request correlation ID, or requestId, to each request. Orders forwards it to inventory, and both include it in logs. This identifies records for one request even across separate services.

A requestId only correlates logs. It is not an identity credential and cannot authorize a request.


🔗 Finding Cross-Service Logs with a Correlation ID

Two small Express services demonstrate the flow. Orders receives a request, generates requestId, and calls inventory, which reuses the ID in its logs. The example uses Node.js 22 or a newer compatible version, Express 5, and built-in fetch.

1. Create the project

observability-demo/
├── package.json
└── services/
    ├── orders.mjs
    └── inventory.mjs

Run in a new directory:

mkdir -p observability-demo/services
cd observability-demo
npm init -y
npm install express@5

Create two files:

import express from 'express';
import { randomUUID } from 'node:crypto';

const app = express();

function log(requestId, message, extra = {}) {
    console.log(JSON.stringify({
        timestamp: new Date().toISOString(),
        service: 'orders',
        requestId,
        message,
        ...extra
    }));
}

// Generate an ID for each incoming request, not once at module load
app.use((req, res, next) => {
    req.requestId = randomUUID();
    res.setHeader('X-Request-Id', req.requestId);
    next();
});

app.get('/check-inventory', async (req, res) => {
    const { requestId } = req;
    log(requestId, 'Starting inventory query');

    try {
        const response = await fetch('http://localhost:3003/availability', {
            headers: { 'X-Request-Id': requestId },
            signal: AbortSignal.timeout(800)
        });

        if (!response.ok) {
            throw new Error(`Inventory endpoint returned HTTP ${response.status}`);
        }

        const result = await response.json();
        log(requestId, 'Inventory query succeeded');
        res.json({ requestId, ...result });
    } catch (error) {
        log(requestId, 'Inventory query failed', { error: error.name });
        res.status(503).json({ requestId, message: 'Inventory service temporarily unavailable' });
    }
});

app.listen(3002, () => console.log('Order service: http://localhost:3002'));

2. Run and observe

Open two terminals and run from the project root:

node services/inventory.mjs
node services/orders.mjs

In a third terminal, run:

curl -i http://localhost:3002/check-inventory

Inventory deliberately waits 1200 milliseconds while orders waits only 800, so you should normally receive HTTP 503. The body includes the request's requestId, for example:

{"requestId":"req-example-01","message":"Inventory service temporarily unavailable"}

The actual ID is a random UUID; this value only illustrates the format. Both services' logs should contain the actual ID returned in the response. Combining them gives something like:

{"service":"orders","requestId":"req-example-01","message":"Starting inventory query"}
{"service":"inventory","requestId":"req-example-01","message":"Inventory query received"}
{"service":"orders","requestId":"req-example-01","message":"Inventory query failed","error":"TimeoutError"}
{"service":"inventory","requestId":"req-example-01","message":"Inventory query completed"}

The illustrative logs omit timestamp to highlight correlation. Notice that inventory may still finish processing after orders stops waiting. This reinforces the previous article's point that a timeout does not stop the remote operation.

The local example uses fixed ports to demonstrate log correlation and does not implement full service authentication. In real environments, inventory should accept upstream X-Request-Id values according to the agreed rules only after trusting the caller. Arbitrary client headers are not trustworthy identity or audit evidence.

🔍 Distributed Tracing: Finding Where Time Is Spent

A requestId locates logs, but the shared ID alone cannot show which step took the most time.

Distributed tracing records a cross-service request as a trace. Each individual operation is a span, usually recording its start time, duration, outcome, and parent-child relationships with other spans.

An order trace might look like:

courseComponents.mermaid.loading

These hypothetical timings illustrate call relationships. Actual span timing can reveal that most waiting occurs in inventory, rather than merely showing that the order endpoint is slow. Span intervals can overlap, so adding every span's duration does not give total request duration.

requestId and traceId differ: the former is our application-defined log correlation identifier; the latter belongs to tracing context, which combines span IDs and relationships into a trace. Production systems often use OpenTelemetry to collect and propagate this automatically. Here we focus on reading traces without repeating monitoring platform deployment.


📊 Metrics: Measuring the Impact

Logs explain individual errors and traces identify slow steps, but neither directly answers: is this isolated or affecting many orders? Metrics summarize operation over time. For orders, useful measures include request volume, error rate, P95 latency, and inventory call timeouts.

Suppose monitoring shows:

MetricNormalDuring inventory failure
Order requests per minute600600
Order endpoint error rate0.5%18%
Order endpoint P95 latency300ms2500ms
Inventory call timeouts per minute290

These are hypothetical values, not measurements from the Express demo. P95 means approximately 95% of sampled requests took no longer than this value. It highlights slower requests, but should be interpreted alongside errors and volume.

Stable order volume with rising errors, P95, and inventory timeouts suggests a problem with the inventory dependency. This is a lead, not a final diagnosis; verify it with traces and logs.


🛠 Investigating a Cross-Service Failure

Combine all three tools. Suppose a user reports that order creation keeps failing:

StepObservationConclusion
1. Check metricsOrder errors, P95, and inventory timeouts riseThis affects more than one user; investigate inventory first
2. Check tracesInventory spans are unusually slow in several failed requestsIdentify the service call consuming the time
3. Check logsOne requestId links the order timeout and inventory processing recordsConfirm orders stopped waiting while inventory responded too slowly

We can now answer the opening questions: metrics show impact, traces show call paths and slow steps, and correlated logs confirm specific errors.

The order of investigation can vary. If a user provides requestId, start with logs and then inspect traces and metrics. The goal is corroboration across all three, rather than guessing from one log entry.


⚠️ Keep Sensitive Information Out of Logs and Traces

Do not log complete JWTs, passwords, payment credentials, database connection strings, or sensitive personal data. Apply the same rule to trace attributes. requestId locates a request but does not replace authentication or authorization.

Metrics usually aggregate by endpoint, service, status code, and similar dimensions. Avoid using every unique order ID as a metric label: the resulting label combinations increase storage and query costs.

Observability aims to identify affected requests, locate failures, and confirm causes, rather than maximize the amount recorded.

❓ Knowledge Check

Q1: Are requestId and traceId the same?

No. requestId is an application-defined correlation ID. traceId identifies a distributed trace, whose span relationships describe the call chain. Both can appear in logs for correlation.

Q2: Why use metrics when logs already exist?

Logs describe specific events. Metrics reveal how many requests fail over time and whether slowness is widespread. They answer different questions.

Q3: Why not add every span duration?

Operations can overlap or contain one another. Orders already includes the time waiting for inventory, so adding both counts it twice.


🧪 Exercise

  1. Start orders and inventory and run curl twice. Confirm the two requests have different requestId values, while each request uses the same ID across both services.
  2. Change inventory's delay from 1200 to 100 milliseconds. Observe response and log changes.
  3. Using the hypothetical metrics table, explain which traces to inspect, which field to search in logs, and how to verify inventory is the slow dependency.

Acceptance criteria: Correlate multiple services' logs with one requestId and explain the troubleshooting roles of metrics, traces, and logs.


🎉 Congratulations on completing this article! You can now combine correlated logs, metrics, and distributed tracing to analyze failures in an order request spanning multiple services.