OpenTelemetry Fundamentals — DevOps

OpenTelemetry (OTel) is a vendor-neutral open standard (not tied to any vendor) for three signals: traces (the journey of one request, answering "where is it…

Imagine notes-api has spent a year sending traces with an SDK from one vendor (a company that sells an observability service). Then the team decides to switch vendors, and it turns out the code that makes those traces is spread across dozens of routes. All of it has to be rewritten.

OpenTelemetry (OTel for short) exists so that doesn't happen. It is an open standard for producing and sending observability data (traces, metrics and logs) in one shared format, whatever vendor it goes to. Picture a musician who records a song once, in a standard audio format. The song goes to a music distributor, which passes it on to the streaming platforms the musician chose. If the musician wants to move to another platform or add one, the song is not recorded again: only the settings at the distributor change. In OTel, the song is the observability data from your application, and the standard format is OTLP. The distributor is the collector, a program that receives that data and passes it on. The platforms are the backends, the systems that store and display observability data, such as Jaeger, Grafana Tempo or Datadog. Changing platforms without recording again is switching vendors without rewriting the code. The vendor's own SDK from the start is like a recording that only one platform accepts.

In the Structured Logging Patterns lesson, nginx and notes-api were tied together by request_id. OTel does something similar for traces, with a standard that many programming languages and vendors use.

Three signals: traces, metrics, logs

OTel calls the three kinds of observability data signals:

Signal What it holds The question it answers
Traces the journey of one request, split into timed operations "Where is this request slow?"
Metrics numbers counted all the time: requests per second, error rate, p95 latency "What is the error rate over the last 5 minutes?"
Logs events with context, one line per event "What exactly does the error say?"

They complete each other. Metrics say that something is slow, a trace shows where, and a log explains why. One log line records a request's total duration, but does not split it per operation. Throughput (requests per second) and error rate show the symptom, not the slow part. To find the part that takes the longest, you need traces.

Traces and spans

A span is one operation with a start time and a duration: one HTTP request, one database query, or one important function. A trace is the set of spans from one request, tied together by the same trace ID. Every span has its own span ID, and stores its parent span ID: the span ID of its parent, the span that called it. So spans form a tree. Here is the trace of Sari saving a note in the Lab:

trace 4bf92f3577b34da6a3ce929d0e0e4736
└─ nginx        POST /notes        48 ms   span 00f067aa0ba902b7
   └─ notes-api    POST /notes     45 ms   span 53995c3f42cd8ad8, parent 00f067aa0ba902b7
      ├─ render-markdown            6 ms   span e1f04a7c9b2d3568 (manual)
      └─ INSERT notes              31 ms   span 8c3b6d0e5f2a1974 (automatic, from the pg driver)

nginx's span comes from nginx's OpenTelemetry module, installed separately. The notes-api span stores nginx's span ID as its parent. The INSERT notes span is made automatically by the pg driver (the Postgres library for Node), while render-markdown is written by hand. Both are covered in the section Automatic and manual instrumentation.

Another example from an online shop. The trace POST /api/orders holds spans for the API Gateway (2 ms), the auth middleware (5 ms) and OrderController.create (150 ms). Inside the controller (the code that handles that route) are the DB spans INSERT orders (30 ms) and UPDATE inventory (20 ms), plus the HTTP span POST payment-service (80 ms). Without reading any code, you can see that inside the controller, the call to payment-service takes the longest. One trace holds many spans, and each span is one operation.

From SDK to collector to backend

OTel data passes three places:

  1. The SDK (the OTel library) inside notes-api creates spans, gathers them and sends them with the OTLP protocol (OpenTelemetry Protocol): port 4318 for OTLP over HTTP, 4317 for gRPC.
  2. The collector (the Docker image otel/opentelemetry-collector-contrib) receives that data, processes it (for example sends it in batches) and forwards it.
  3. The backend stores and displays the data: Jaeger or Grafana Tempo for traces, Prometheus for metrics, Loki for logs, or a paid service such as Datadog.

This is the collector config on web-1:

receivers:
  otlp:
    protocols:
      http:
        endpoint: 0.0.0.0:4318

processors:
  batch:

exporters:
  otlp/jaeger:
    endpoint: jaeger:4317
    tls:
      insecure: true

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [batch]
      exporters: [otlp/jaeger]

What if the team moves to Datadog next year? Change the exporter to datadog (with api.key from an environment variable), and notes-api's code does not change by a single line. The code that creates spans is not tied to any vendor, so only the destination changes. In the Lab, switch the backend: only the exporters block and the exporter's name in the pipeline change, and the application code changes by 0 lines.

Automatic and manual instrumentation

Instrumentation is the code that creates spans and metrics. For Node.js, one tracing.js file is enough for automatic instrumentation:

// tracing.js: loaded BEFORE the application code
const { NodeSDK } = require("@opentelemetry/sdk-node");
const { getNodeAutoInstrumentations } = require("@opentelemetry/auto-instrumentations-node");
const { OTLPTraceExporter } = require("@opentelemetry/exporter-trace-otlp-http");

const sdk = new NodeSDK({
  traceExporter: new OTLPTraceExporter(), // address from OTEL_EXPORTER_OTLP_ENDPOINT
  instrumentations: [getNodeAutoInstrumentations()],
});

sdk.start();

The collector's address, the service name and other details come from these environment variables:

OTEL_SERVICE_NAME=notes-api
OTEL_RESOURCE_ATTRIBUTES=service.version=1.8.0,deployment.environment.name=production
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318

Run it with node --require ./tracing.js server.js. --require loads tracing.js first, so the http, express and pg modules are already "tapped" before the application uses them. Tapped means wrapped by the SDK, so every use of them becomes a span. The result is automatic, without changing the route code: a POST /notes span for the request and an INSERT notes span for its query.

The environment variables above fill in the resource attributes: labels attached to all data from this process. OTEL_SERVICE_NAME fills in service.name, which answers "who is sending". service.version and deployment.environment.name help compare versions and environments (for example production and staging). Without OTEL_SERVICE_NAME, all your spans appear as unknown_service:node.

For business logic (rules that belong to your application) that no library knows about, add a manual span:

const { trace, SpanStatusCode } = require("@opentelemetry/api");
const tracer = trace.getTracer("notes-api");

function renderMarkdown(note) {
  return tracer.startActiveSpan("render-markdown", (span) => {
    try {
      span.setAttribute("note.length", note.content.length);
      return markdownToHtml(note.content);
    } catch (err) {
      span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });
      throw err;
    } finally {
      span.end(); // without end(), the span is never sent
    }
  });
}

traceparent: context that travels in a header

For notes-api's spans to join nginx's span, the trace context (the trace ID and the caller's span ID) must travel with the request. The standard is W3C Trace Context, from the W3C, the organisation that makes web standards. The context goes in the traceparent header, which has four parts separated by hyphens:

Part Value in the Lab Meaning
version 00 the format version, 00 today
trace-id 4bf92f3577b34da6a3ce929d0e0e4736 32 hex characters: the trace's ID, the same in every service
parent-id 00f067aa0ba902b7 16 hex characters: the caller's span ID (nginx's span)
trace-flags 01 last bit 1 = sampled, this trace is recorded

The SDK in notes-api reads this header and creates the POST /notes span with the same trace ID, parent 00f067aa0ba902b7, and a new span ID of its own, 53995c3f42cd8ad8. The flags 01 mean nginx decided this trace is recorded, and notes-api follows that decision. When notes-api calls another service over HTTP, it sends a new traceparent: the trace ID stays, but the parent-id becomes notes-api's span ID (the span for its outgoing HTTP request).

When the flags are 00, notes-api does not record spans either, but still passes the context on. That is what the default sampler, parentbased_always_on, does: a rule that follows the parent's decision, and records everything when there is no parent. When the header is missing or broken (uppercase, wrong length, an all-zero trace-id), it is ignored. notes-api then starts a new trace, so the trace is cut off from nginx.

⚠️ Why are spans missing, nameless or cut off?

TL;DR: OpenTelemetry (OTel) is a vendor-neutral open standard (not tied to any vendor) for three signals: traces (the journey of one request, answering "where is it slow"), metrics (numbers like error rate and latency) and logs (events with context). One trace holds many spans. Each span is one timed operation, and the spans are tied together by the trace ID and the parent span ID (the ID of the span that called it). The flow: the SDK in the application sends over OTLP (OTel's protocol; port 4318 for HTTP, 4317 for gRPC) to the collector (which passes the data on). The collector sends it to a backend (which stores and displays the data) such as Jaeger, Tempo or Datadog. Switching vendors means switching the collector's exporter (the destination), and the application code stays the same. Instrumentation (the code that creates spans) can be automatic, through a tracing.js loaded first, or manual, with startActiveSpan and span.end(). OTEL_SERVICE_NAME and resource attributes (labels on all data from that process) mark who is sending. Trace context travels between services in the traceparent header: version-traceid-parentid-flags, with flags 01 = sampled (recorded).

⚡ Traces and spans

Guess first: in an online shop, a POST /api/orders request passes the API Gateway, the auth middleware, the query INSERT orders and the call POST payment-service. Each of those operations becomes one span. How many traces does this request make, and how do they relate to those spans?

One trace. That trace holds many spans, and each span is one operation: the API Gateway, the auth middleware, INSERT orders, POST payment-service. The spans share the same trace ID and form a tree through their parent span IDs (the IDs of the spans that called them).

Meaning: A span is one operation with a start time and a duration. A trace is the set of spans from one request, tied together by the same trace ID.

⚡ Automatic instrumentation

Write:

// tracing.js: loaded BEFORE the application code
const sdk = new NodeSDK({
  traceExporter: new OTLPTraceExporter(), // address from OTEL_EXPORTER_OTLP_ENDPOINT
  instrumentations: [getNodeAutoInstrumentations()],
});

sdk.start();

Meaning: This tracing.js file starts the OpenTelemetry SDK (the OTel library) before the application loads, with automatic instrumentation: spans are created without changing the route code. Run it with node --require ./tracing.js server.js, so http, express and pg are tapped (wrapped so every use becomes a span) before the application uses them. The SDK sends spans over OTLP (OTel's protocol) to the collector (a program that passes data on), which sends them to a backend (where traces are stored and viewed) such as Jaeger. Switching vendors only means switching the exporter (the destination) in the collector.

⚡ traceparent ties services together

Meaning: The traceparent header carries the trace context from one service to the next. It holds four parts: the version, the trace-id, the parent-id (the caller's span ID) and the flags (01 = recorded). The next service uses the same trace ID, with a new span ID of its own. A missing or broken header cuts the trace off, and that service starts a new trace.

What you will learn