Why Distributed Tracing Is No Longer Optional

When a request travels through a modern backend — hitting an API gateway, an authentication service, a database query, an external payment provider, and a notification service before returning a response — a single log line tells you almost nothing useful when something goes wrong. You know the request failed or was slow, but not where or why.

This is the problem that distributed tracing solves. Instead of isolated log entries, tracing threads a unique identifier (a trace ID) through every service and operation touched by a request, recording the start time, duration, and metadata of each step as a span. The result is a complete, hierarchical view of exactly what happened across your entire system.

For teams in Syria and the region operating on tighter infrastructure budgets — where a slow request might reflect an upstream timeout, an overloaded VM, or a flaky external API — the ability to pinpoint the actual bottleneck without guessing is enormously valuable.

OpenTelemetry (OTel) is the CNCF-graduated open standard for distributed tracing, metrics, and logs. It provides vendor-neutral SDKs for every major language and exports to any backend: Jaeger, Tempo, Zipkin, Datadog, or your own self-hosted collector. This guide walks through a realistic Node.js / Python implementation, the collector configuration, and practical patterns for correlating traces in a multi-service architecture.

---

Understanding the OpenTelemetry Data Model

Before writing any code, it helps to be precise about the building blocks.

Traces, Spans, and Context

| Concept | Definition | |---|---| | Trace | The full journey of a single request across all services. Identified by a 128-bit traceId. | | Span | A single named, timed operation within a trace. Has a spanId and a reference to its parent span. | | Context | The carrier that propagates traceId + spanId across process and network boundaries. | | Attribute | A key-value annotation on a span (e.g., http.method, db.statement). | | Event | A timestamped log entry attached to a span (e.g., "cache miss"). | | Status | Whether the span succeeded (OK) or errored (ERROR). |

W3C TraceContext Propagation

OpenTelemetry defaults to the W3C traceparent header for HTTP propagation:

traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
              ^^ version  ^^ trace-id (32 hex)         ^^ span-id (16 hex) ^^ flags

This header travels with every outbound HTTP call. Each receiving service extracts the parent context, creates a child span, and continues the chain — no central coordinator required.

---

Project Setup: Node.js Microservice

The following example instruments a Node.js Express service. The same principles apply to Python (using opentelemetry-sdk and opentelemetry-instrumentation-fastapi) with near-identical configuration.

> [!NOTE] > The code samples below are illustrative. Adapt connection strings, service names, and exporter endpoints to your environment. Test thoroughly before deploying to production.

1. Install Dependencies

npm install \
  @opentelemetry/sdk-node \
  @opentelemetry/auto-instrumentations-node \
  @opentelemetry/exporter-trace-otlp-http \
  @opentelemetry/resources \
  @opentelemetry/semantic-conventions

The auto-instrumentations-node package automatically instruments Express routes, http/https calls, DNS lookups, and popular databases (pg, mysql2, mongoose, redis) without manual span creation for every call.

2. Create the Instrumentation Bootstrap (tracing.js)

This file must be loaded before any other module in your application.

// tracing.js  — load with:  node --require ./tracing.js server.js
'use strict';

const { NodeSDK } = require('@opentelemetry/sdk-node');
const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-http');
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');
const { Resource } = require('@opentelemetry/resources');
const { SEMRESATTRS_SERVICE_NAME, SEMRESATTRS_SERVICE_VERSION } = require('@opentelemetry/semantic-conventions');

const exporter = new OTLPTraceExporter({
  // Point to your OpenTelemetry Collector (see collector config below)
  url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318/v1/traces',
  headers: {},
});

const sdk = new NodeSDK({
  resource: new Resource({
    [SEMRESATTRS_SERVICE_NAME]: process.env.SERVICE_NAME || 'api-gateway',
    [SEMRESATTRS_SERVICE_VERSION]: process.env.npm_package_version || '1.0.0',
    'deployment.environment': process.env.NODE_ENV || 'development',
  }),
  traceExporter: exporter,
  instrumentations: [
    getNodeAutoInstrumentations({
      '@opentelemetry/instrumentation-fs': { enabled: false }, // skip noisy fs spans
    }),
  ],
});

sdk.start();

process.on('SIGTERM', () => {
  sdk.shutdown()
    .then(() => console.log('Tracing terminated'))
    .catch((err) => console.error('Error terminating tracing', err))
    .finally(() => process.exit(0));
});

3. Add Manual Spans for Business Logic

Auto-instrumentation covers HTTP and database calls. For your own business logic — pricing calculations, file processing, external API calls to custom services — create manual spans:

// order-service.js
const { trace, SpanStatusCode } = require('@opentelemetry/api');

const tracer = trace.getTracer('order-service');

async function processOrder(orderId, userId) {
  // Create a custom span for the entire order-processing operation
  return tracer.startActiveSpan('order.process', async (span) => {
    try {
      // Annotate the span with business-relevant attributes
      span.setAttributes({
        'order.id': orderId,
        'user.id': userId,
        'order.source': 'web',
      });

      // Child spans for sub-operations are created automatically
      // by auto-instrumentation (DB query, HTTP call, etc.)
      const inventory = await checkInventory(orderId);

      if (!inventory.available) {
        // Record a span event (a log entry attached to this span)
        span.addEvent('inventory.unavailable', {
          'product.id': inventory.productId,
          'stock.level': inventory.quantity,
        });
        span.setStatus({ code: SpanStatusCode.ERROR, message: 'Out of stock' });
        throw new Error('Product out of stock');
      }

      const result = await reserveStock(orderId);
      span.setStatus({ code: SpanStatusCode.OK });
      return result;
    } catch (err) {
      span.recordException(err); // Captures stack trace on the span
      span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });
      throw err;
    } finally {
      span.end(); // Always end the span
    }
  });
}

---

The OpenTelemetry Collector: Your Observability Hub

Rather than exporting traces directly from each service to Jaeger or Tempo, the recommended pattern is to route everything through the OpenTelemetry Collector. This keeps your services decoupled from the backend and lets you fan out to multiple destinations, apply sampling, and redact sensitive data in one place.

Collector Configuration (otel-collector.yaml)

# otel-collector.yaml
receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318

processors:
  batch:
    timeout: 1s
    send_batch_size: 1024
  memory_limiter:
    check_interval: 1s
    limit_mib: 400
  resource:
    attributes:
      - key: environment
        value: production
        action: insert
  # Redact sensitive query parameters before exporting
  attributes:
    actions:
      - key: http.url
        pattern: "(token|password|secret)=[^&]*"
        action: hash

exporters:
  jaeger:
    endpoint: jaeger:14250
    tls:
      insecure: true
  logging:
    loglevel: warn

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [memory_limiter, batch, resource, attributes]
      exporters: [jaeger, logging]

Docker Compose Setup (Development)

# docker-compose.yml (excerpt — illustrative)
version: '3.9'

services:
  otel-collector:
    image: otel/opentelemetry-collector-contrib:latest
    command: ["--config=/etc/otel/config.yaml"]
    volumes:
      - ./otel-collector.yaml:/etc/otel/config.yaml
    ports:
      - "4317:4317"   # gRPC
      - "4318:4318"   # HTTP
    networks:
      - observability

  jaeger:
    image: jaegertracing/all-in-one:latest
    environment:
      - COLLECTOR_OTLP_ENABLED=true
    ports:
      - "16686:16686"  # Jaeger UI
    networks:
      - observability

networks:
  observability:
    driver: bridge

---

Python Instrumentation (FastAPI)

For teams running Python microservices, the setup is equally straightforward.

Install Dependencies

pip install \
  opentelemetry-sdk \
  opentelemetry-instrumentation-fastapi \
  opentelemetry-instrumentation-httpx \
  opentelemetry-instrumentation-sqlalchemy \
  opentelemetry-exporter-otlp-proto-http

Bootstrap (instrumentation.py)

# instrumentation.py
import os
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource, SERVICE_NAME, SERVICE_VERSION

def configure_tracing(service_name: str, version: str = "1.0.0") -> None:
    resource = Resource.create({
        SERVICE_NAME: service_name,
        SERVICE_VERSION: version,
        "deployment.environment": os.getenv("ENVIRONMENT", "development"),
    })

    exporter = OTLPSpanExporter(
        endpoint=os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4318/v1/traces"),
    )

    provider = TracerProvider(resource=resource)
    provider.add_span_processor(BatchSpanProcessor(exporter))
    trace.set_tracer_provider(provider)

FastAPI Application

# main.py
from fastapi import FastAPI
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
from instrumentation import configure_tracing

configure_tracing(service_name="inventory-service")

app = FastAPI()

# Auto-instrument FastAPI (adds spans for every route)
FastAPIInstrumentor.instrument_app(app)
# Auto-instrument httpx (propagates trace context in outbound HTTP calls)
HTTPXClientInstrumentor().instrument()

@app.get("/inventory/{product_id}")
async def get_inventory(product_id: str):
    # Spans for this route and any DB/HTTP calls inside are created automatically
    return {"product_id": product_id, "quantity": 42}

---

Sampling Strategies: Managing Trace Volume

Tracing every request at high throughput generates significant data volume. Sampling controls which traces are retained.

Head-Based Sampling (Probabilistic)

Decided at the start of the trace — fast and simple, but may miss rare errors:

// In tracing.js — add to NodeSDK config
const { TraceIdRatioBased, ParentBasedSampler } = require('@opentelemetry/sdk-trace-base');

// Sample 10% of requests; always follow parent's decision if set
const sampler = new ParentBasedSampler({
  root: new TraceIdRatioBased(0.1),
});

Tail-Based Sampling (Collector-Side)

Decided after the trace is complete — retains 100% of error traces and slow traces regardless of the sample rate:

# In otel-collector.yaml — add tail_sampling processor
processors:
  tail_sampling:
    decision_wait: 10s
    num_traces: 50000
    policies:
      - name: errors-policy
        type: status_code
        status_code: { status_codes: [ERROR] }
      - name: slow-traces-policy
        type: latency
        latency: { threshold_ms: 2000 }
      - name: probabilistic-policy
        type: probabilistic
        probabilistic: { sampling_percentage: 5 }

> [!TIP] > For most production systems, start with 100% sampling in development, tail-based sampling in production (always keep errors + latency outliers, probabilistically keep 5-10% of the rest). This keeps storage costs low while ensuring you never lose the traces that matter most.

---

Correlating Traces with Logs

Traces alone aren't enough — you also want your existing log lines to be searchable by traceId so you can jump from a trace waterfall to the full log context.

Node.js: Inject Trace Context into Log Lines

// logger.js — using pino
const pino = require('pino');
const { trace, context } = require('@opentelemetry/api');

const baseLogger = pino({ level: 'info' });

function getLogger(name) {
  return {
    info: (msg, extra = {}) => {
      const span = trace.getActiveSpan();
      const ctx = span ? span.spanContext() : null;
      baseLogger.info({
        ...extra,
        logger: name,
        traceId: ctx?.traceId,
        spanId: ctx?.spanId,
        traceFlags: ctx?.traceFlags,
      }, msg);
    },
    // Repeat for warn, error, debug...
  };
}

module.exports = { getLogger };

Now every log line emitted during a request includes traceId and spanId. In Grafana, you can click a trace span and jump directly to the correlated log lines in Loki — without manual searching.

---

Practical Patterns for Multi-Service Systems

Pattern 1: Baggage for Business Context Propagation

W3C Baggage lets you attach key-value pairs to the context that flow through every downstream service, without polluting span attributes in every service:

const { propagation, context } = require('@opentelemetry/api');

// At the entry point (API gateway)
const bag = propagation.createBaggage({
  'tenant.id': { value: tenantId },
  'request.region': { value: 'sy-damascus' },
});
const ctx = propagation.setBaggage(context.active(), bag);

// In any downstream service, read it without touching HTTP headers directly:
const bag2 = propagation.getBaggage(context.active());
const tenantId = bag2?.getEntry('tenant.id')?.value;

Pattern 2: Custom Span Naming for Readability

Auto-instrumentation names spans like GET /orders/:id. Rename high-value spans to reflect business operations:

span.updateName('order.fulfillment.reserve-stock');

Pattern 3: Alerting on Span Error Rate

In Grafana with Tempo as your trace backend, you can query for error rate by service:

# PromQL query (Tempo metrics generator must be enabled)
rate(traces_spanmetrics_calls_total{status_code="STATUS_CODE_ERROR", service="order-service"}[5m])
/
rate(traces_spanmetrics_calls_total{service="order-service"}[5m])

This gives you an error-rate alert without needing to instrument Prometheus counters separately — Tempo's metrics generator derives them from your spans automatically.

---

Deployment Considerations for Syrian Infrastructure

Teams operating in Syria face specific infrastructure realities that affect observability deployments:

Self-host the collector and backend. Cloud-based SaaS observability tools require stable international bandwidth. Running Jaeger or Grafana Tempo on a local or regional VM keeps trace export latency low and avoids data leaving the network when connectivity is degraded.

Tune the batch processor. The collector's batch processor buffers spans before exporting. Set timeout to 2-5 seconds and send_batch_size to 512-1024. This tolerates short network blips without losing spans or overwhelming downstream storage.

Use gRPC over HTTP for internal collector communication. gRPC with binary Protobuf encoding is roughly 30% smaller on the wire than JSON-over-HTTP for the same span data — meaningful when exporting from many services on a constrained internal network.

Limit cardinality. Each unique combination of attribute values creates a new time-series entry in your metrics backend. Avoid putting raw user IDs, order IDs, or IP addresses directly into span attributes — use them in span events instead, or in baggage. High cardinality attributes cause storage and query performance problems in Jaeger and Prometheus alike.

---

Verifying Your Setup

Before going to production, run through this checklist:

  • [ ] A test request through your API appears as a complete trace in Jaeger UI with all services represented
  • [ ] Parent-child span relationships are correct (no orphan spans)
  • [ ] Database query spans include sanitized db.statement attributes
  • [ ] Outbound HTTP calls to external services appear as child spans
  • [ ] Error responses set span.status = ERROR and call span.recordException()
  • [ ] Log lines include traceId that matches the trace in Jaeger
  • [ ] Collector restarts do not cause application errors (use the SDK's retry configuration)
  • [ ] Sampling is configured — you are not storing every trace in a high-throughput environment

---

Summary

| Phase | Key Action | |---|---| | Bootstrap | Load tracing.js before all other modules; configure resource attributes | | Auto-instrument | Use language auto-instrumentation packages for HTTP, DB, and framework spans | | Manual spans | Wrap critical business logic in named spans with meaningful attributes | | Collector | Route all traffic through OTel Collector for sampling, redaction, and fan-out | | Sampling | Use tail-based sampling in production — always retain errors and slow traces | | Correlation | Inject traceId / spanId into log lines for cross-signal navigation | | Alerting | Use Tempo metrics generator to derive error-rate and latency alerts from spans |

Distributed tracing with OpenTelemetry transforms debugging from a guessing game into a systematic, evidence-driven process. Whether you are operating two services or twenty, instrumenting them with a consistent, vendor-neutral standard from the start avoids painful retrofitting later and gives your engineering team the visibility needed to maintain reliable systems.

---

Ready to build a reliable, observable backend? Dragonfly Soft designs and implements production-grade backend architectures — including observability pipelines, distributed tracing setups, and DevOps tooling — for businesses in Syria and across the region.

Get in touch with our engineering team →