TL;DR: Use OpenTelemetry and AWS X-Ray to see where time goes in a request that crosses several Node.js services. This guide explains how W3C Trace Context propagates across services, how to configure the OpenTelemetry Node.js SDK and the ADOT collector for X-Ray, when you still need the X-Ray ID generator and propagator, and how trace context crosses an SQS queue.
Key Takeaways
- Use the W3C
traceparentheader to propagate trace IDs and parent span IDs between services, so instrumentation is not tied to one tracing vendor. - Since October 2023, X-Ray accepts W3C-format (fully random) trace IDs when spans arrive through ADOT collector 0.34.0 or later or CloudWatch agent 1.300030.0 or later.
AWSXRayIdGeneratoris now optional and mainly useful for interoperability with services instrumented by the legacy X-Ray SDKs. - Combine the W3C propagator with
AWSXRayPropagatorin aCompositePropagatorwhen requests pass through AWS services that use theX-Amzn-Trace-Idheader, such as ALB, API Gateway and Lambda. - Send spans with
OTLPTraceExporterover gRPC to an AWS Distro for OpenTelemetry (ADOT) collector (port4317by default) and let the collector export to X-Ray. @opentelemetry/auto-instrumentations-nodealready propagates context through SQS message attributes via the AWS SDK instrumentation; disable noisy instrumentations such as@opentelemetry/instrumentation-fs.
A user clicks "Checkout". Eight seconds later, they are greeted by a generic 504 Gateway Timeout. In a monolithic architecture, tracking down this latency bottleneck is often as simple as profiling a single active process. In a distributed microservices environment, those eight seconds could have been spent in any of several services.
Did the Order API choke? Was there an AWS SQS queue backup? Did the Payment Service exhaust its PostgreSQL connection pool?
If your incident response strategy involves grepping through thousands of fragmented CloudWatch logs trying to match obscure correlation IDs, you spend most of an incident reconstructing the request by hand. Logs tell you what happened, but without structured Context Propagation, they cannot tell you how long the network hop took between Service A and Service B.
The solution to these microservice blind spots is OpenTelemetry (OTel) integrated with AWS X-Ray. With distributed tracing, every service records timed spans that share one trace ID, so you can see how long each hop, queue wait and database query took within a single request.
Here is how to set it up for Node.js services.
The Anatomy of a Trace: Spans, Context, and Propagation
Before writing any configuration code, we must understand the mechanics of distributed observability. A Trace represents the entire journey of a request as it moves through a distributed system. A trace is composed of individual Spans, which represent a single unit of work (e.g., an HTTP request, a database query, or a message queue operation).
To stitch these spans together across different microservices, OpenTelemetry relies on the W3C Trace Context standard. When Service A calls Service B, it injects trace metadata into the HTTP headers.
GET /api/v1/payments/status HTTP/1.1
Host: payment-service.internal
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
tracestate: rojo=00f067aa0ba902b7
Let's break down that traceparent header, as it is the backbone of the system:
00: The version format.4bf92f3577b34da6a3ce929d0e0e4736: The Trace ID. This remains identical across all microservices, tying the entire request lifecycle together.00f067aa0ba902b7: The Parent Span ID. This identifies the specific operation in Service A that triggered Service B.01: The Trace Flags. This indicates whether this trace is being sampled and recorded.
Because the header format is a W3C standard rather than a vendor format, the instrumentation stays portable. Switching from AWS X-Ray to Datadog, Honeycomb or Jaeger is mostly a change of exporter in the collector, not a change to business logic. If you need help instrumenting an existing API estate this way, see our backend development and API services.
Bootstrapping OpenTelemetry for AWS X-Ray in Node.js
Setting up OpenTelemetry in Node.js requires initializing the SDK before any other modules are loaded.
X-Ray has its own trace ID format, 1-<8 hex digits of epoch seconds>-<24 random hex digits>. Older X-Ray ingestion paths rejected trace IDs without that timestamp prefix, which is why many guides insist on the AWSXRayIdGenerator. Since October 2023, X-Ray accepts W3C-format trace IDs, provided you send spans through ADOT collector 0.34.0 or later or CloudWatch agent 1.300030.0 or later. The X-Ray ID generator is still useful if some services use the legacy X-Ray SDKs or an older collector, and it is harmless otherwise, so the example keeps it.
The propagator matters more. The OpenTelemetry default reads and writes W3C traceparent headers, while ALB, API Gateway and Lambda use X-Amzn-Trace-Id. A CompositePropagator with both keeps traces connected across your services and AWS-managed hops. Here is the tracing.ts bootstrap file:
// tracing.ts
import { NodeSDK } from '@opentelemetry/sdk-node';
import { resourceFromAttributes } from '@opentelemetry/resources';
import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions';
import {
CompositePropagator,
W3CBaggagePropagator,
W3CTraceContextPropagator,
} from '@opentelemetry/core';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';
import { AWSXRayIdGenerator } from '@opentelemetry/id-generator-aws-xray';
import { AWSXRayPropagator } from '@opentelemetry/propagator-aws-xray';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
const traceExporter = new OTLPTraceExporter({
// AWS Distro for OpenTelemetry (ADOT) Collector sidecar or DaemonSet
url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4317',
});
const sdk = new NodeSDK({
resource: resourceFromAttributes({
[ATTR_SERVICE_NAME]: 'order-service',
[ATTR_SERVICE_VERSION]: '1.0.0',
'deployment.environment.name': process.env.NODE_ENV || 'development',
}),
traceExporter,
// Optional: X-Ray-style IDs (timestamp prefix) for legacy X-Ray SDK interop
idGenerator: new AWSXRayIdGenerator(),
// Read and write both W3C traceparent and AWS X-Amzn-Trace-Id headers
textMapPropagator: new CompositePropagator({
propagators: [
new W3CTraceContextPropagator(),
new W3CBaggagePropagator(),
new AWSXRayPropagator(),
],
}),
instrumentations: [
getNodeAutoInstrumentations({
// We will customize database instrumentation in the next section
'@opentelemetry/instrumentation-fs': { enabled: false },
}),
],
});
sdk.start();
process.on('SIGTERM', () => {
sdk
.shutdown()
.then(() => console.log('Tracing terminated cleanly'))
.catch((error) => console.error('Error terminating tracing', error))
.finally(() => process.exit(0));
});
Production Note: Load the compiled
tracing.jsbefore your application with Node's--requireflag (for examplenode --require ./dist/tracing.js ./dist/index.js) when your build outputs CommonJS. For ES modules, follow the OpenTelemetry ESM instructions, which use--importtogether with the@opentelemetry/instrumentation/hook.mjsloader. If you import the file insideindex.tsafter Express or the AWS SDK, the instrumentation cannot patch those modules. The SIGTERM handler callsprocess.exitafter flushing, because registering a SIGTERM listener replaces Node's default exit behavior.
Exposing Database Latency with Auto-Instrumentation
OpenTelemetry's auto-instrumentations do most of the work. Passing getNodeAutoInstrumentations() to the SDK patches Express, the AWS SDK, and database drivers such as pg and mysql2 as they are loaded.
The pg instrumentation already records the SQL text of each query (as db.statement, or db.query.text with the newer semantic conventions) along with its duration. It has an enhancedDatabaseReporting option, but that option adds the bound parameter values to the span, which is rarely what you want in production. Instead, use hooks to add the context you actually need, such as row counts:
import { ExpressLayerType } from '@opentelemetry/instrumentation-express';
// Inside tracing.ts instrumentations array
getNodeAutoInstrumentations({
'@opentelemetry/instrumentation-pg': {
// SQL text is recorded by default. Leave enhancedDatabaseReporting off:
// it would also record bound parameter values (often PII).
responseHook: (span, responseInfo) => {
if (responseInfo?.data?.rowCount != null) {
span.setAttribute('db.row_count', responseInfo.data.rowCount);
}
},
},
'@opentelemetry/instrumentation-express': {
ignoreLayersType: [ExpressLayerType.MIDDLEWARE], // Skip middleware spans
},
});
Security Warning: Recorded SQL text goes to your tracing backend. Use parameterized queries (e.g.,
SELECT * FROM users WHERE id = $1) so values such as emails or names stay out of the statement text, and leaveenhancedDatabaseReportingoff unless you have checked that parameter values contain no personal data or secrets.
With this configuration, an engineer can open a slow trace in X-Ray, see which query took the time and how many rows it returned, then run EXPLAIN ANALYZE on that query to check for a missing index.
Bridging the Asynchronous Gap: Context Propagation in SQS
Synchronous HTTP calls are relatively easy to trace because the HTTP instrumentation injects and extracts headers for you. Asynchronous messaging needs more care.
When you push a message to an SQS queue and a worker picks it up seconds or minutes later, the active context does not travel with it unless something puts it in the message. The @opentelemetry/instrumentation-aws-sdk package, included in the auto-instrumentations bundle, already injects trace context into SQS MessageAttributes on SendMessage and SendMessageBatch and extracts it on ReceiveMessage. If you use it, you mostly need to make sure your consumer requests the attributes. Write the propagation by hand, as below, when that instrumentation is not active or when you want explicit control over the processing span.
SQS allows at most 10 message attributes per message, and the injected trace keys count toward that limit. Here is manual injection in the producer:
// producer.ts
import { SQSClient, SendMessageCommand, MessageAttributeValue } from '@aws-sdk/client-sqs';
import { propagation, context } from '@opentelemetry/api';
const sqs = new SQSClient({ region: 'us-east-1' });
export async function dispatchOrderEvent(orderData: any) {
// 1. Create a carrier object for our trace attributes
const carrier: Record<string, string> = {};
// 2. Inject the active OpenTelemetry context into the carrier
propagation.inject(context.active(), carrier);
// 3. Map the carrier strings to the SQS MessageAttribute format
const messageAttributes: Record<string, MessageAttributeValue> = {};
for (const [key, value] of Object.entries(carrier)) {
messageAttributes[key] = {
DataType: 'String',
StringValue: value,
};
}
const command = new SendMessageCommand({
QueueUrl: process.env.ORDER_QUEUE_URL,
MessageBody: JSON.stringify(orderData),
MessageAttributes: messageAttributes,
});
await sqs.send(command);
}
On the Consumer microservice side, we must extract those SQS attributes and wrap our message handler in a new active span that links back to the parent context.
// consumer.ts
import { trace, propagation, context, SpanStatusCode } from '@opentelemetry/api';
const tracer = trace.getTracer('sqs-consumer');
export async function handleSqsMessage(message: any) {
// 1. Reconstruct the carrier from SQS attributes
const carrier: Record<string, string> = {};
if (message.MessageAttributes) {
for (const [key, attr] of Object.entries(message.MessageAttributes)) {
carrier[key] = (attr as any).StringValue;
}
}
// 2. Extract the parent context from the carrier
const parentContext = propagation.extract(context.active(), carrier);
// 3. Start a new span using the extracted context as the parent
await tracer.startActiveSpan(
'process_order_queue',
{ attributes: { 'messaging.system': 'sqs' } },
parentContext,
async (span) => {
try {
// Execute business logic
await processOrder(JSON.parse(message.Body));
// Mark the span as successful
span.setStatus({ code: SpanStatusCode.OK });
} catch (error) {
// Record the error details in the trace
span.recordException(error as Error);
span.setStatus({
code: SpanStatusCode.ERROR,
message: (error as Error).message,
});
throw error;
} finally {
// Ensure the span is always closed
span.end();
}
},
);
}
The consumer must request the attributes when it polls, for example MessageAttributeNames: ['All'] on ReceiveMessageCommand, or the carrier will be empty. With the context propagated, the consumer's span joins the producer's trace, so X-Ray shows the original request, the queue send and the message processing as one trace.
Exporting Traces via the ADOT Collector
You may have noticed in our bootstrap file that we used an OTLPTraceExporter pointing to localhost:4317 instead of sending data directly to AWS X-Ray.
You can export from the Node.js process directly, but a collector is the usual choice. It batches and retries outside your application process, signs requests to AWS with its own IAM role (it needs xray:PutTraceSegments and xray:PutTelemetryRecords), and lets you change sampling or backends without redeploying services.
Run the AWS Distro for OpenTelemetry (ADOT) collector, version 0.34.0 or later for W3C trace ID support, as a sidecar or DaemonSet. The Node.js app sends OTLP over gRPC to the collector, and the collector converts spans to X-Ray segments.
Here is the otel-collector-config.yaml required to route OTLP data to X-Ray:
# otel-collector-config.yaml
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
processors:
batch:
timeout: 5s
send_batch_size: 512
exporters:
awsxray:
region: us-east-1
# Attributes listed here become X-Ray annotations you can filter on;
# all other attributes are stored as metadata
indexed_attributes:
- http.route
- db.row_count
service:
pipelines:
traces:
receivers: [otlp]
processors: [batch]
exporters: [awsxray]
Deploying this collector as a sidecar in ECS Fargate or a DaemonSet in EKS keeps export work and AWS credentials out of your Node.js services.
Querying X-Ray to Uncover Bottlenecks
Once traces are flowing through the ADOT collector into AWS X-Ray, you can query trace summaries that exceed a latency threshold instead of guessing.
Using the AWS CLI and an X-Ray filter expression (string values go in double quotes): For example, if we want to find all requests to the /checkout route that took longer than 3 seconds in the last hour:
aws xray get-trace-summaries \
--start-time $(date -d "1 hour ago" +%s) \
--end-time $(date +%s) \
--filter-expression 'service("order-service") AND responsetime > 3 AND http.url CONTAINS "/checkout"'
When you open one of these traces in the console, the timeline shows where the time went. Twenty sequential 150ms PostgreSQL spans in a staircase pattern usually point to an N+1 query, which you can confirm in the code without searching through logs first.
Wrapping Up
Eliminating microservice blind spots is not about logging more data; it's about logging connected data. OpenTelemetry's vendor-neutral instrumentation, an ADOT collector and AWS X-Ray give you per-request timing across services, queues and databases.
With W3C and X-Ray propagation configured, a request that travels through an Express API, an SQS queue and a PostgreSQL database shows up as one trace. Sampling, attribute hygiene (no secrets or personal data in spans) and collector capacity are the main things to settle before rolling this out widely.
Sources
- AWS What's New: AWS X-Ray supports W3C format trace IDs (ADOT collector 0.34.0 and CloudWatch agent 1.300030.0 requirements)
- AWS X-Ray Developer Guide: Using filter expressions
- OpenTelemetry JS contrib: AWS SDK instrumentation, SQS (context injection into
MessageAttributes) - OpenTelemetry JS contrib: AWS X-Ray propagator (
X-Amzn-Trace-Idformat) - OpenTelemetry Collector contrib: AWS X-Ray exporter (
indexed_attributes,index_all_attributes)
Need help building this in production?
SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.
Get a Free ConsultationFrequently Asked Questions
Why is AWS X-Ray silently dropping my OpenTelemetry traces in Node.js?
Older X-Ray ingestion paths required the first four bytes of the trace ID to be an epoch timestamp, so random OpenTelemetry IDs were rejected. Since October 2023, X-Ray accepts W3C-format IDs through ADOT collector 0.34.0+ or CloudWatch agent 1.300030.0+. If traces are still missing, check the collector version, its IAM permissions (xray:PutTraceSegments), the Region and your sampling settings, or add the AWSXRayIdGenerator.
What is the purpose of the traceparent header in distributed tracing?
The traceparent header is part of the W3C Trace Context standard used to propagate trace metadata across microservice boundaries. It contains the global Trace ID, the Parent Span ID, and Trace Flags, allowing different services to stitch their individual operations into a single, unified request journey.
How can I ensure my microservice tracing architecture remains vendor-agnostic?
By relying on standard OpenTelemetry SDKs and W3C headers rather than proprietary vendor agents, your code remains decoupled from the backend observability platform.
When should I initialize the OpenTelemetry SDK in my Node.js application?
The OpenTelemetry SDK must be bootstrapped and started before any other modules, frameworks, or business logic are required in your application. This ensures the auto-instrumentation hooks can successfully wrap standard libraries (like HTTP or database drivers) before they are executed.
Why is distributed tracing better than standard CloudWatch logging for microservices?
Traditional logs only tell you what happened, often requiring engineers to manually grep through fragmented correlation IDs to find latency bottlenecks. Distributed tracing shows the time taken for network hops and database queries across your entire system.
How do I export OpenTelemetry traces from Node.js to AWS X-Ray?
Configure OTLPTraceExporter in your Node.js application to send spans to an AWS Distro for OpenTelemetry (ADOT) collector, and use the awsxray exporter in the collector's traces pipeline. The AWSXRayPropagator is separate: it controls the headers passed between services, and you add it alongside the W3C propagator when requests cross ALB, API Gateway or Lambda.
