Observability
🎯 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'));
import express from 'express';
const app = express();
app.get('/availability', async (req, res) => {
// Local demo only: reuse the correlation ID forwarded by orders
const requestId = req.get('X-Request-Id') ?? 'missing';
console.log(JSON.stringify({
timestamp: new Date().toISOString(),
service: 'inventory',
requestId,
message: 'Inventory query received'
}));
// Simulate a downstream delay exceeding the 800ms order timeout
await new Promise(resolve => setTimeout(resolve, 1200));
console.log(JSON.stringify({
timestamp: new Date().toISOString(),
service: 'inventory',
requestId,
message: 'Inventory query completed'
}));
res.json({ available: 10 });
});
app.listen(3003, () => console.log('Inventory service: http://localhost:3003'));
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.
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:
| Metric | Normal | During inventory failure |
|---|---|---|
| Order requests per minute | 600 | 600 |
| Order endpoint error rate | 0.5% | 18% |
| Order endpoint P95 latency | 300ms | 2500ms |
| Inventory call timeouts per minute | 2 | 90 |
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:
| Step | Observation | Conclusion |
|---|---|---|
| 1. Check metrics | Order errors, P95, and inventory timeouts rise | This affects more than one user; investigate inventory first |
| 2. Check traces | Inventory spans are unusually slow in several failed requests | Identify the service call consuming the time |
| 3. Check logs | One requestId links the order timeout and inventory processing records | Confirm 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.
❓ 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
- Start orders and inventory and run
curltwice. Confirm the two requests have differentrequestIdvalues, while each request uses the same ID across both services. - Change inventory's delay from
1200to100milliseconds. Observe response and log changes. - 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.
Security
Understand user identity propagation, service authentication, and business authorization through order queries and stock reservations.
Deployment and Scaling
Learn about statelessness, health checks, and version compatibility through independent order releases, instance scaling, and rolling updates.
