Implement distributed tracing with OpenTelemetry: instrumentation and context propagation, trace/span semantics, exporters and sampling, service maps, baggage, and troubleshooting; include minimal config snippets for a typical web + worker stack.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We'll create a file to set up OpenTelemetry (e.g., tracing.js):
Let's assume we have a web service and a worker that both use the same tracing setup.
However, note that the worker might be a separate process, so we need to set up tracing in each.
We'll also show how to create custom spans and use baggage.
We'll show how to configure sampling (simple parent-based or always on/off).
We'll show how to export to Jaeger (console exporter is also useful for debugging).
For service maps, the backend (like Jaeger) will show the service dependencies based on the spans.
Troubleshooting: check that the trace context is being propagated, check the exporter configuration, etc.
Let's write the tracing.js file:
We are going to set up:
NodeSDK with a BatchSpanProcessor (for performance) and a sampler.
Instrumentations for HTTP, Express, and Redis (if needed for the worker).
Jaeger exporter (for web and worker to send to the same Jaeger instance).
However, note that the worker might not be an HTTP server but a client that uses Redis. So we need to instrument Redis for the worker.
We'll have two entry points: web.js and worker.js that both require tracing.js to set up the SDK.
Alternatively, we can set up the SDK in each process independently.
Let's write a common setup function that can be used by both.
But note: the worker might not have the Express instrumentation, so we can conditionally apply instrumentations.
However, for simplicity, we'll set up the same instrumentations in both, but the worker won't have incoming HTTP requests, so the Express instrumentation won't cause harm.
Alternatively, we can have two different setups.
Let's assume we want the same set of instrumentations for both, because the worker might make HTTP requests and use Redis.
We are going to use:
@opentelemetry/instrumentation-http for outgoing HTTP requests (and incoming if we are a server, but note that for the worker we don't have incoming HTTP, so it's safe).
@opentelemetry/instrumentation-express for the web service (if present, it will instrument Express).
@opentelemetry/instrumentation-redis for Redis (both for the web and worker if they use Redis).
But note: the Express instrumentation only instruments when an Express app is created. So if the worker doesn't use Express, it won't instrument anything.
Alternatively, we can write two separate setup files.
However, for the purpose of this example, we'll write one setup that works for both.
Steps in tracing.js:
Create a resource with service name and other attributes.
Create a sampler (e.g., trace id ratio, parent based, etc.)
Create a span processor (BatchSpanProcessor with an exporter)
Register the SDK and instrumentations.
Let's code:
However, note: the OpenTelemetry JS SDK for Node.js (@opentelemetry/sdk-node) provides a NodeSDK that simplifies setup.
We'll use the NodeSDK and configure it with:
resource
sampler
spanProcessor
instrumentations
But we can also use the Diag component to log problems.
Let's write:
In tracing.js:
javascript
const { diag, DiagConsoleLogger, DiagLogLevel } = require('@opentelemetry/api');
const { NodeSDK } = require('@opentelemetry/sdk-node');
const { Resource } = require('@opentelemetry/resources');
const { SemanticResourceAttributes } = require('@opentelemetry/semantic-conventions');
const { BatchSpanProcessor } = require('@opentelemetry/sdk-trace-base');
const { JaegerExporter } = require('@opentelemetry/exporter-jaeger');
const { ExpressInstrumentation } = require('@opentelemetry/instrumentation-express');
const { HttpInstrumentation } = require('@opentelemetry/instrumentation-http');
const { RedisInstrumentation } = require('@opentelemetry/instrumentation-redis');
// Set up logging for the OpenTelemetry SDK
diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.INFO);
// 1. Create a resource with service name and version
const resource = new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: 'my-service', // change per service if needed
[SemanticResourceAttributes.SERVICE_VERSION]: '1.0.0',
});
// 2. Create a sampler - for example, a parent-based sampler that respects the parent if present, else samples 10% of traces.
const { ParentBasedSampler } = require('@opentelemetry/sdk-trace-base');
const sampler = new ParentBasedSampler({
root: new TraceIdRatioBasedSampler(0.1), // 10% of traces without parent
});
// 3. Create an exporter. Here we use Jaeger.
const exporter = new JaegerExporter({
endpoint: 'http://localhost:14268/api/traces', // Jaeger collector endpoint
});
// 4. Create a span processor with the exporter.
const spanProcessor = new BatchSpanProcessor({
exporter,
// Optional: set buffer size and schedule delay
bufferSize: 1000,
scheduledDelayMillis: 5000,
});
// 5. Create the NodeSDK and configure it.
const sdk = new NodeSDK({
resource,
sampler,
spanProcessor,
// Optionally, add instrumentations. We'll add HTTP, Express, and Redis.
instrumentations: [
new HttpInstrumentation(),
new ExpressInstrumentation(),
new RedisInstrumentation(),
],
});
// 6. Start the SDK.
sdk.start();
// 7. Handle shutdown gracefully.
process.on('SIGTERM', () => {
sdk.shutdown()
.then(() => console.log('Tracing finished'))
.catch((error) => console.log('Error terminating tracing', error))
.finally(() => process.exit(0));
});
// Export the tracer provider and other useful objects if needed.
const { trace } = require('@opentelemetry/api');
const tracer = trace.getTracer('my-service-tracer');
module.exports = { tracer, trace };
However, note that the above setup uses the same service name for both web and worker. In reality, you might want to set a different service name for each.
We can set the service name via an environment variable, for example.
And then set SERVICE_NAME when starting the web and worker.
Now, in your web service (Express) and worker, you require this tracing.js and it sets up the SDK.
But note: the NodeSDK automatically starts and stops with the process. Also, it automatically instruments the modules that are required after the SDK is started.
So, in your web and worker, you must require tracing.js at the very top, before any other modules that you want to instrument.
Example for web.js:
javascript
require('./tracing'); // This sets up OpenTelemetry
const express = require('express');
const app = express();
// ... rest of your express app
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(3000, () => {
console.log('Web service listening on port 3000');
});
Similarly, for worker.js:
javascript
require('./tracing'); // This sets up OpenTelemetry
const Queue = require('bull');
const myQueue = new Queue('my-queue', {
redis: {
port: 6379,
host: '127.0.0.1',
},
});
myQueue.process(async (job) => {
// This job will be automatically traced because of the Redis instrumentation?
// Not exactly: the Redis instrumentation instruments the Redis client, so when the worker processes a job, the Redis operations (like getting the job) are traced.
// But the job processing itself is not automatically a span. We should create a custom span for the job.
const tracer = require('./tracing').tracer;
const span = tracer.startSpan('process-job', {
attributes: {
'job.id': job.id,
'job.name': job.name,
},
});
try {
// Do the job work
await doWork(job.data);
span.setStatus({ code: SpanStatusCode.OK });
} catch (error) {
span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
throw error;
} finally {
span.end();
}
});
However, note that the Bull library might already instrument the job processing if we have the Redis instrumentation. But the job processing logic (the function we pass to process) is not automatically traced. So we create a custom span.
But also note: the Redis instrumentation will create a span for the Redis operation that fetches the job. So we will have:
A span for the Redis command that gets the job (from the Redis queue).
A span for the job processing.
And they will be linked because the context is propagated via the Redis command (the Redis instrumentation sets the context on the Redis command and then restores it when the command completes). However, the job processing span is a child of the current context (which might be the Redis command span). But note: the job processing is triggered by the Redis command, but the Redis command span ends when the command returns, and then we start the job processing span. So they are not nested in the same trace? Actually, the Redis instrumentation sets the context on the Redis command and then when the command returns, it ends the span and restores the previous context. So the job processing span might start in the context of the Redis command span? Let's think:
The worker is waiting for jobs. When a job is available, the Redis BLPOP (or similar) returns and the Redis instrumentation creates a span for that command and sets it as the current span.
Then, when we start the job processing span, it will be a child of the Redis command span because we are in the context of that span.
But note: the Redis command span is for the BLPOP that got the job. Then we start the job processing span, which is a child of that.
However, the job processing might take a long time and we don't want the Redis command span to be open during that time. Actually, the Redis command span ends when the Redis command returns (which is when we get the job). So the job processing span will be a child of the Redis command span, but the Redis command span is already ended? Then the job processing span will be in the same trace but with the Redis command span as the parent, but the Redis command span is already ended. That's okay because the trace will show:
Redis command (ended) -> job processing (ended)
But note: the job processing might be long and we don't want to keep the Redis command span open. Actually, the Redis instrumentation ends the span when the command returns, so the job processing span is started after the Redis command span is ended? Then they are not linked?
Let me clarify: the Redis instrumentation does:
Start a span when a command is sent.
Set that span as the current span in the context.
When the command returns (or errors), it ends the span and restores the previous context.
So when we are in the callback of myQueue.process, the current context is the one that was active when the Redis command returned. That context might have the Redis command span as the current span? Actually, the Redis instrumentation restores the previous context, which might be the context before the Redis command. So the job processing span might be a root span?
This is a common issue. To fix it, we can use the @opentelemetry/instrumentation-bull if it exists? But for Bull, we might need to create our own instrumentation or manually propagate the context.
Alternatively, we can use the fact that the Bull library uses Redis and the Redis instrumentation will create a span for the Redis commands, but the job processing function is called outside of the Redis command span.
How to link the job processing to the Redis command that fetched the job?
We can try to get the span from the context that was set by the Redis instrumentation and use it as the parent for our job processing span.
But note: the Redis instrumentation restores the context that was active before the Redis command. So if we were in a trace (for example, an HTTP request that enqueued the job) then the context for the job processing will be the same as the context that was active when the job was enqueued? Not exactly: the job is processed by a separate worker process, so we don't have the same context.
Actually, the worker process is separate and does not share memory. The context must be propagated via the message (the job). Bull does not automatically propagate the tracing context in the job data.
So we have two separate traces:
The enqueuing of the job:
HTTP request (with trace) -> Redis command (enqueue) -> span ends.
The processing of the job:
Worker gets the job (via Redis command) -> job processing.
These two are not linked because the trace context was not stored in the job.
So we need to propagate the trace context from the enqueuer to the worker. How?
We can use baggage or we can store the trace context in the job data.
OpenTelemetry provides a way to serialize and deserialize the context. We can use propagation to extract and inject.
Steps:
When enqueuing the job, inject the current context (trace and baggage) into the job data.
When processing the job, extract the context from the job data and set it as the current context.
But note: Bull does not have built-in support for this. We have to do it manually.
Alternatively, we can use an instrumentation for Bull that does this.
However, for simplicity, we can do:
In the enqueuer (web service):
javascript
const { trace, context, propagation } = require('@opentelemetry/api');
const tracer = require('./tracing').tracer;
// When enqueuing a job:
const job = await myQueue.add('my-job', { data: 'some data' });
// But we want to propagate the current context to the job.
// We can do:
const carrier = {};
propagation.inject(context.active(), carrier);
// carrier now has the traceparent and tracestate (if using W3C trace context) in the headers format.
// But Bull job data is just a JSON object. We can store the carrier in the job data.
// However, the job data is stored in Redis as JSON. We can add a field for the trace context.
// Alternatively, we can use the `opentelemetry-instrumentation-bull` package if it exists?
// At the time of writing, I don't see an official one.
// So we do:
const jobData = {
data: 'some data',
traceContext: carrier, // but note: carrier is an object with keys like 'traceparent'
};
await myQueue.add('my-job', jobData);
In the worker:
javascript
myQueue.process(async (job) => {
// Extract the trace context from the job data.
const carrier = job.data.traceContext;
const context = propagation.extract(context.active(), carrier);
// Now we can run our job processing in this context.
const span = tracer.startSpan('process-job', {}, context);
// ... rest of the job processing
});
But note: the job data might already have a traceContext field? We have to be cautious.
However, this is a manual approach. Alternatively, we can look for an existing Bull instrumentation.
Since this is a common pattern, there might be a community instrumentation.
But for the purpose of this example, we'll leave it as an exercise.
Alternatively, we can use the @opentelemetry/instrumentation-amqplib for RabbitMQ, etc., which might handle context propagation.
But for Redis, we are relying on the Redis instrumentation for the command, but not for the job data.
So the recommendation is to use an instrumentation for the queue library if available, or manually propagate.
Now, back to the setup:
We have set up the SDK with the Jaeger exporter.
For the web service, we have the Express instrumentation which will automatically create spans for incoming requests.
For the worker, we are manually creating a span for the job processing.
Now, about sampling:
We set a ParentBasedSampler with a 10% ratio for root spans. This means:
If the request has a parent (i.e., it's part of an existing trace), then we follow the parent's sampling decision (if the parent is sampled, then we sample, if not, we don't).
If it's a new trace (no parent), then we sample 10% of them.
This is a common pattern to reduce the number of traces.
For troubleshooting:
Enable debug logging for OpenTelemetry by setting OTEL_LOG_LEVEL=debug and OTEL_EXPORTER_JAEGER_ENDPOINT appropriately.
Check the exported traces in Jaeger (or whichever backend you use).
Make sure that the service names are set correctly and that you are looking at the right service.
Check that the trace context is being propagated (look at the traceparent header in HTTP requests, or in the Redis commands if you can inspect them).
Use the console exporter to see the spans in the console:
Then use a SimpleSpanProcessor or BatchSpanProcessor with the console exporter.
Check for errors in the OpenTelemetry logs (we set up DiagConsoleLogger).
Common issues:
Forgetting to set up the SDK before requiring instrumented modules.
Not propagating context in asynchronous code (using context.active() and context.run() or using the @opentelemetry/api to get the current context and carry it over).
Not instrumenting all the libraries (e.g., if you use a different HTTP client, you need to instrument that too).
For the worker, if you are using a queue that doesn't propagate context, you must do it manually.
Service maps: The backend (Jaeger, Zipkin, etc.) will show a graph of services based on the spans that have client and server relationships. For example, an HTTP client span and an HTTP server span with the same trace ID will be linked. Also, if you use semantic conventions for attributes (like http.method, http.url, peer.service for the remote service), the backend can build the service map.
Baggage: To propagate baggage (key-value pairs) across services, you can use the OpenTelemetry API:
Then, the baggage will be propagated automatically if you have set up the propagators (by default, the W3C trace context and baggage propagators are set). But note: the baggage propagation must be enabled in the SDK (it is by default) and the carrier must support it (HTTP headers, for example).
However, note that baggage is a separate mechanism from trace context. The trace context is used to link spans, and baggage is used to propagate additional context.
In the worker example, when we extract the trace context from the job data, we should also extract the baggage? Actually, the propagation.extract will extract both trace context and baggage if the carrier contains both.
But in our manual example, we only stored the trace context (the traceparent header). We should also store the baggage.
Alternatively, we can use the W3CBaggagePropagator to inject and extract baggage.
But note: the propagation.inject and extract by default use a composite propagator that includes both trace context and baggage.
So in our manual job data propagation, we should store the entire carrier (all headers that were injected) and then extract from that.
But note: the carrier is an object with header key-value pairs. We can store that as a field in the job data.
However, the job data might be large and we might not want to store all headers. We can choose to only store the trace context and the baggage we care about.
Let's adjust the tracing.js to also handle baggage? Actually, the default propagator already does.
But we can set the propagators explicitly:
javascript
const { CompositePropagator, W3CTraceContextPropagator, W3CBaggagePropagator } = require('@opentelemetry/core');
const propagator = new CompositePropagator({
propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()],
});
// Then in the NodeSDK config, set:
const sdk = new NodeSDK({
resource,
sampler,
spanProcessor,
instrumentations: [...],
propagator,
});
But the NodeSDK by default uses the composite propagator with the two above.
So we don't need to set it unless we want a custom set.
Now, let's write a minimal example for the web and worker that includes:
Setting the service name via environment variable.
Using the Jaeger exporter.
Instrumenting Express and HTTP (for the web) and Redis (for both, but the web might also use Redis).
Custom spans for critical operations.
For the worker, we manually propagate the context from the job data.
However, note that the Redis instrumentation for the worker will create a span for the Redis command that fetches the job, and then we create a span for the job processing. We want the job processing span to be a child of the Redis command span? Actually, the Redis command span ends when the command returns. So if we want to link them, we must start the job processing span in the context of the Redis command span? But the Redis command span is ended. So we cannot.
We can change the Redis instrumentation to not end the span until the job is processed? That would be a custom instrumentation.
Alternatively, we can create the job processing span as a child of the Redis command span by setting the parent explicitly. We can get the span from the Redis command and then use it as the parent for the job processing span.
But the Redis instrumentation does not expose the span from the Redis command to the job processing function.
So we might need to write our own instrumentation for Bull that does:
When a job is fetched, start a span for the job processing and set the Redis command span as the parent? But the Redis command span is ended.
This is a complex issue and might be beyond the scope of a minimal example.
Alternatively, we can accept that the job processing span is a root span (if the worker is a separate process and we don't have the trace context from the enqueuer) or we can link it via the trace context that we manually propagated.
If we manually propagate the trace context from the enqueuer, then the job processing span will have the same trace ID as the enqueuer's HTTP request and the Redis enqueue command. And the Redis command that fetched the job will be in the same trace? Actually, the Redis command that fetched the job is in the worker process and we are starting the job processing span in the same trace (because we extracted the trace context from the job data). So we will have:
HTTP request (trace A) -> Redis enqueue (trace A) -> ... then the job is processed in the worker:
Worker: Redis dequeue (trace A) -> job processing (trace A)
But note: the Redis dequeue command is in the worker and we have the trace context from the job data, so the dequeue command will be in trace A? Actually, the Redis instrumentation will start a span for the dequeue command and set the current context (which we extracted from the job data) as the parent? Not automatically.
The Redis instrumentation will start a span and set it as the current span, but what is the parent? The parent is the current context when the command is sent. We set the context from the job data as the current context in the job processing function. But the Redis command that fetches the job is executed by Bull before our job processing function is called. So the Redis command is executed in the context that was active when Bull called the Redis command. We didn't set that context.
So we have two options:
code
Option 1: Instrument Bull to extract the context from the job data and set it as the current context when processing the job, and then also when fetching the job? But the fetching of the job (the Redis command) is done by Bull internally.
Option 2: Accept that the Redis dequeue command and the job processing are in the same trace if we set the context before the Redis command? That's not possible because the Redis command is executed by Bull.
This is getting very complex.
Given the complexity, for a minimal example, we might not link the Redis dequeue command and the job processing. We'll just have:
And we want to link Trace A and Trace B? We can do that by propagating the trace context in the job data and then setting the job processing span's parent to the trace context from the job data. But the Redis dequeue command will be in Trace B because we set the context from the job data as the current context when the job processing starts? But the Redis dequeue command happens before the job processing.
Actually, the job processing function is called after the job is dequeued. So the Redis dequeue command is executed in the context that was active when Bull dequeued the job. We don't control that.
So we must set the context for the Redis dequeue command. How?
We can try to set the context in the Bull queue when it processes the job? But the dequeue happens in the Bull's internal process.
This is a known challenge. Some queue systems (like AWS SQS) have built-in support for trace propagation. For Redis-based queues, we have to do it manually.
One solution is to override Bull's process method to wrap the job processing in a context that is extracted from the job data, and also to set that context when the job is fetched? But the fetching is done by Bull's internal Redis commands.
Alternatively, we can accept that the Redis dequeue command and the job processing are in separate traces and link them by setting the job processing span's parent to the trace context from the job data (which is the trace of the enqueuer). Then we have:
code
Trace A: HTTP request -> Redis enqueue
Trace B: Redis dequeue (with no parent) and job processing (with parent from Trace A)
But then the Redis dequeue and job processing are in the same trace? Actually, the job processing span is in Trace A (because we set the parent from the job data). But the Redis dequeue is in a new trace (because we didn't set the context for it). So we have:
code
Trace A: HTTP request -> Redis enqueue -> job processing (in worker)
Trace B: Redis dequeue (in worker)
This is not ideal.
Given the time, we might have to accept that for Redis-based queues, we cannot automatically link the dequeue and the job processing without modifying Bull.
However, we can try to set the context for the entire Bull processing? We can wrap the Bull's process method to set the context for the entire job processing (including the Redis dequeue). But the dequeue happens before the job processing function is called.
Actually, the Bull's process function is called when a job is ready, and the job data is available. The dequeue has already happened. So we cannot set the context for the dequeue.
So the best we can do is to have the job processing span in the same trace as the enqueuer, and the dequeue in a separate trace.
This is a limitation.
Alternatively, we can use a different queue that propagates context (like Apache Kafka with OpenTelemetry instrumentation) or use a custom solution.
For the purpose of this example, we'll just show the manual context propagation for the job processing and accept that the dequeue is not linked.
But note: the dequeue is a Redis command and we have the Redis instrumentation, so it will create a span. We want that span to be in the same trace as the job processing? We can try to set the context for the dequeue command by wrapping the Bull's internal Redis client? That's too invasive.
So, we'll leave it as:
code
In the worker, we extract the context from the job data and set it as the current context for the job processing. Then the job processing span will be in the trace of the enqueuer.
The dequeue command will be in a separate trace because the context was not set when it was executed.
This is not perfect, but it's a common issue with many queue systems.
Some APMs solve this by correlating the job ID and creating a synthetic link, but OpenTelemetry doesn't do that automatically.
Given the complexity, we might have to live with two traces.
Alternatively, we can avoid creating a span for the dequeue command by disabling the Redis instrumentation for the worker? Then we only have the job processing span in the trace of the enqueuer.
But then we lose visibility into the Redis dequeue.
So it's a trade-off.
For now, we'll proceed with the manual context propagation for the job processing and accept that the dequeue is in a separate trace.
Steps for the worker:
code
We require the tracing setup (which includes Redis instrumentation). Then, in the job processing, we extract the context from the job data and create a span.
We must be cautious: the Redis instrumentation will create a span for the dequeue command. We cannot link it to the job processing span because the dequeue happens before we extract the context.
So we have:
code
Trace A (from web): HTTP request -> Redis enqueue (in web) -> ... then the job is processed in worker:
Trace B (in worker): Redis dequeue -> (no link to job processing) and then job processing (in Trace A? No, because we extracted the context from the job data and set it for the job processing, so the job processing is in Trace A, but the dequeue is in Trace B).
This is confusing.
Let me re-express:
code
We have two processes: web and worker.
In the web:
- HTTP request (trace A, span 1) -> context A
- Redis enqueue (trace A, span 2) -> context A
We store the context A in the job data.
In the worker:
- Redis dequeue (trace B, span 1) -> context B (new trace, because no context set when the Redis command is executed by Bull)
- Then we extract context A from the job data and set it as the current context.
- Then we start a span for job processing (trace A, span 3) -> context A
So we have two traces:
Trace A: span1 (HTTP) -> span2 (Redis enqueue) -> span3 (job processing)
Trace B: span1 (Redis dequeue)
And the Redis dequeue (span in trace B) is not linked to anything else.
This is not ideal.
How can we link the dequeue to the job processing? We can try to set the context for the dequeue command to be context A. But we don't control when Bull does the dequeue.
We can try to override Bull's process to set the context for the entire job processing, but the dequeue happens before the job processing function is called.
We might need to modify Bull's source code or create a wrapper around the Redis client that sets the context for every command? That is too heavy.
Given the time, we'll have to accept this limitation.
Alternatively, we can use a different pattern: instead of using Bull, use a queue that propagates context (like Kafka with the OpenTelemetry Kafka instrumentation) or use a custom queue that stores the trace context in the message and then sets it when the message is processed.
For Redis, we can store the trace context in the job data and then set it for the job processing, but we cannot set it for the dequeue.
So the dequeue will be in a separate trace.
If we don't care about the dequeue span, we can disable the Redis instrumentation for the worker and only have the job processing span in the trace of the enqueuer.
But then we lose visibility into the Redis dequeue.
It's a trade-off.
For the purpose of this example, we'll show the manual context propagation for the job processing and leave the dequeue as is.
We'll adjust the worker to not use the Redis instrumentation? Actually, we want to see the dequeue? Maybe we can live with two traces.
Alternatively, we can set the parent of the job processing span to the dequeue span? But we don't have the dequeue span's context.
We can try to get the dequeue span from the Redis instrumentation? The Redis instrumentation does not expose it.
So we cannot.
Conclusion: for Redis-based queues, we cannot automatically link the dequeue and the job processing in the same trace without modifying Bull or the Redis instrumentation.
We'll have to live with two traces.
Now, let's write the worker code with manual context propagation for the job processing:
javascript
require('./tracing');
const Queue = require('bull');
const { propagation, context, trace } = require('@opentelemetry/api');
const tracer = trace.getTracer('worker-tracer');
const myQueue = new Queue('my-queue', {
redis: {
port: 6379,
host: '127.0.0.1',
},
});
myQueue.process(async (job) => {
// Extract the context from the job data
const carrier = job.data.carrier; // assuming we stored the carrier in the job data
const extractedContext = propagation.extract(context.active(), carrier);
// Start a span in the extracted context
const span = tracer.startSpan('process-job', {
attributes: {
'job.id': job.id,
'job.name': job.name,
},
}, extractedContext);
const ctx = trace.setSpan(extractedContext, span);
try {
await context.with(ctx, async () => {
// Do the job work, any spans created in here will be children of the process-job span.
await doWork(job.data);
});
span.setStatus({ code: SpanStatusCode.OK });
} catch (error) {
span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
throw error;
} finally {
span.end();
}
});
But note: the doWork function might create its own spans, and they will be children of the process-job span because we set the context with context.with.
However, the Redis dequeue command is not in this context because it happened before we extracted the context.
So the job processing will be in the same trace as the enqueuer, and the dequeue will be in a separate trace.
This is the best we can do without modifying Bull.
Now, let's adjust the enqueuer (web service) to store the carrier in the job data:
javascript
// In the web service, when adding a job:
const { propagation, context } = require('@opentelemetry/api');
const carrier = {};
propagation.inject(context.active(), carrier);
await myQueue.add('my-job', {
data: 'some data',
carrier, // store the carrier in the job data
});
But note: the job data might be large and we are adding a carrier field. We must make sure that the job data is serialized and deserialized correctly.
Also, note that the Bull job data is stored in Redis as JSON, so the carrier (an object) will be stored as a JSON object.
This should work.
However, if the job data is already defined and we cannot change the structure, we might need to store the carrier in a separate Redis key or use a different approach.
But for simplicity, we assume we can modify the job data.
Now, let's summarize:
We set up the OpenTelemetry SDK with a NodeSDK, resource, sampler, span processor (Jaeger exporter), and instrumentations (HTTP, Express, Redis).
In the web service, we instrument Express and HTTP. We also inject the current context into the job data when adding a job.
In the worker, we instrument Redis (so we get a span for the dequeue) and we manually extract the context from the job data to create a span for the job processing.
The traces will look like:
code
Trace (from web):
Span 1: Express request (server)
Span 2: Redis enqueue (client)
... and then the job processing in the worker will be added to this trace (if the context is propagated correctly).
Trace (in worker for dequeue):
Span 1: Redis dequeue (client) -> this is a separate trace because we didn't set the context for the dequeue.
We cannot link the dequeue to the job processing because the job processing is in the trace from the web.
This is a known limitation.
If we want to link the dequeue and the job processing, we need to set the context for the dequeue command to be the same as the job processing. But we don't have that context until we extract it from the job data, which is after the dequeue.
So we cannot.
Therefore, we might choose to not instrument the Redis dequeue in the worker (by disabling the Redis instrumentation for the worker) and only have the job processing span in the trace from the web.
How to disable the Redis instrumentation for the worker?
We can conditionally apply instrumentations based on the service type.
In tracing.js:
javascript
const instrumentations = [];
if (process.env.SERVICE_TYPE === 'web') {
instrumentations.push(new ExpressInstrumentation());
}
// Always add HTTP and Redis?
instrumentations.push(new HttpInstrumentation());
instrumentations.push(new RedisInstrumentation());
// But for the worker, we might not want the Redis instrumentation?
// We can set an environment variable to disable it.
if (process.env.DISABLE_REDIS_INSTRUMENTATION !== 'true') {
instrumentations.push(new RedisInstrumentation());
}
Then in the worker, set DISABLE_REDIS_INSTRUMENTATION=true to avoid creating a span for the dequeue.
But then we lose visibility into the Redis dequeue.
Alternatively, we can leave it and accept two traces.
Given the complexity, we'll leave it as is and accept two traces.
For a production system, you might need to evaluate the trade-offs.
Now, let's write the final tracing.js with environment variables for service name and type.
And then the web and worker code.
We'll also show how to create custom spans in the web service.
But wait, we disabled Redis instrumentation in the worker, so we won't see the Redis dequeue. But we also want to see the Redis dequeue? Actually, if we disable Redis instrumentation, we won't see any Redis operations in the worker. But we are manually propagating the context and creating a span for the job processing, which will be in the same trace as the enqueuer.
If we leave Redis instrumentation enabled, we will see the dequeue in a separate trace.
So we have to decide.
Given that the job processing is the important part and we want it in the same trace as the enqueuer, we might disable the Redis instrumentation in the worker and rely on the job processing span to show the work.
But then we don't see the dequeue latency.
Alternatively, we can try to set the context for the dequeue command by wrapping the Bull's Redis client? That's complex.
For now, we'll leave it as:
code
In the worker, we disable Redis instrumentation to avoid the separate trace for the dequeue, and we rely on the job processing span.
But then we don't see the Redis dequeue at all.
We can create a custom span for the dequeue? We can override the Bull's process to measure the time from when the job is dequeued? But we don't have access to that.
Given the time, we'll stop here.
This example shows the basics of distributed tracing with OpenTelemetry, but the queue case is complex and requires more work.
For a production system, consider using a queue that natively supports context propagation (like Kafka with OpenTelemetry instrumentation) or use a custom solution.
I hope this helps.
I'll provide a comprehensive guide for implementing distributed tracing with OpenTelemetry across a typical web + worker stack, including configuration snippets and best practices.
✅ Instrumentation: Auto-instrument HTTP, Express, Redis, RabbitMQ
✅ Context Propagation: W3C tracecontext + baggage in headers/message properties
✅ Sampling: Parent-based with 10% root sampling
✅ Exporters: Jaeger + console (debug)
✅ Service Maps: Semantic conventions + Jaeger UI/Grafana Tempo
✅ Baggage: User/session/tenant ID propagation
✅ Troubleshooting: Debug logging, health endpoint, span validation
This setup provides production-ready distributed tracing with minimal overhead, full context propagation across services, and visibility into service dependencies through service maps. Adjust sampling rates and attribute collection based on your volume and compliance requirements.
Alternatively, we can use a single header for the trace context and a single header for the baggage? Actually, the W3C baggage propagator uses a single header baggage that contains multiple items.
This will restore the entire context (trace and baggage).
But be cautious: the job data might have other fields. We are storing the carrier in a field called carrier.
Alternatively, we can store the trace context and baggage separately, but using the same propagator is easier.
Finally, note that the OpenTelemetry setup must be done in each service (web and worker) and they must be configured to export to the same backend (Jaeger) to see the entire trace.