OpenTelemetry Node Tracing Spans

Instrument a Node service with OpenTelemetry tracing spans, nesting child spans across async boundaries and exporting OTLP batches.

TypescriptNodeResilience

Code

typescriptsnippet
45 lines
import { NodeSDK } from '@opentelemetry/sdk-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { trace, context, SpanStatusCode } from '@opentelemetry/api';

const sdk = new NodeSDK({
  serviceName: 'orders-service',
  traceExporter: new OTLPTraceExporter({
    url: process.env.OTLP_ENDPOINT ?? 'http://collector:4318/v1/traces',
  }),
  instrumentations: [getNodeAutoInstrumentations()],
});

await sdk.start();
const tracer = trace.getTracer('orders', '1.0.0');

async function processOrder(orderId: string): Promise<void> {
  return tracer.startActiveSpan('order.process', async (span) => {
    span.setAttribute('order.id', orderId);
    try {
      await tracer.startActiveSpan('order.validate', async (child) => {
        await new Promise((r) => setTimeout(r, 10));
        child.setAttribute('validation.rules', 12);
        child.end();
      });

      await tracer.startActiveSpan('order.charge', async (child) => {
        await new Promise((r) => setTimeout(r, 25));
        child.recordException(new Error('card declined simulated'));
        child.setStatus({ code: SpanStatusCode.ERROR });
        child.end();
      });

      span.setStatus({ code: SpanStatusCode.OK });
    } catch (err) {
      span.recordException(err as Error);
      span.setStatus({ code: SpanStatusCode.ERROR });
    } finally {
      span.end();
    }
  });
}

await processOrder('ord-7');
await sdk.shutdown();

How it works

OpenTelemetry Node Tracing Spans is built around the function processOrder.

The asynchronous flow is linearized with await, keeping failure handling local. The snippet’s external surface is NodeSDK, OTLPTraceExporter, getNodeAutoInstrumentations, trace, context, all of it via @opentelemetry/sdk-node.

Configuration comes from the environment — it reads OTLP_ENDPOINT, so the same code switches behavior between environments without edits.

What to watch for

  • Plan for an install step: @opentelemetry/sdk-node, @opentelemetry/exporter-trace-otlp-http and @opentelemetry/auto-instrumentations-node are a real dependency, resolved by the package manager.

Using it

Signature: async function processOrder(orderId: string)

Key statements

await new Promise((r) => setTimeout(r, 10));
await new Promise((r) => setTimeout(r, 25));
await processOrder('ord-7');

Interactive Tools for This Topic

FAQ

What does this need from the package registry?
These are real dependencies: `@opentelemetry/sdk-node`, `@opentelemetry/exporter-trace-otlp-http` and `@opentelemetry/auto-instrumentations-node`. Without them the snippet will not load.