OTEL me more
AI solutions add even more complexity to an already diverse and distributed software landscape. Now we are not just talking to our own systems, but to externally hosted, unpredictable, slow and expensive APIs. As we step into a new year, OpenTelemetry (OTEL) is not just a buzzword, it is a must have for all distributed software.
OpenTelemetry (OTEL) is now the vendor-neutral standard for instrumenting your app - traces, metrics, and logs in one SDK, owned by you, not by an agent vendor. Point it at any backend with a config change. The LGTM stack (Loki for logs, Grafana as the UI, Tempo for traces, Mimir/Prometheus for metrics) is the free, self-hostable place to send it all. It is easy to play around with OTEL locally now. One docker-compose service on my dev machine now gives me what only Datadog-budget clients had in 2015: every request as a trace, the SQL query timed inside it, logs linked by trace ID, latency histograms etc.
For a small startup, two modest VMs could cover observability for the whole company. But talk is cheap, so let’s build something real and see what we actually get.
The Demo - Orders, an Outbox and a Queue
A “hello world” endpoint with a trace is boring - every OTEL tutorial has one. Observability earns its money when work leaves the request: queues, background workers, third party APIs. So this “demo app” is a small orders system -
POST /ordersvalidates and prices the order and saves it together with an outbox event in one transaction- An outbox relay picks up unpublished events and pushes them to a Redis queue
- A fulfilment worker consumes the queue, books shipping with a (fake, flaky 😈) carrier over HTTP, then reserves stock and confirms the order
POST /orders ──► orders-api ──(1 tx: order + outbox row)──► Postgres │ outbox-relay ◄── SELECT … SKIP LOCKED ─┘ │ LPUSH ▼ Redis ──BRPOP──► fulfilment-worker ──HTTP──► shippingThree processes, Postgres, Redis and an HTTP hop. The goal: one trace from the HTTP request all the way to the order being confirmed, plus logs and metrics that tie into it.
Tech setup
A note on the queue - to keep the demo small it is a plain Redis list (LPUSH / BRPOP). BRPOP removes the message before it is processed, so a worker crash at the wrong moment loses it - not great after all the effort the outbox makes to never lose an event 😅 For real use, go for a Redis Stream with consumer groups or a proper broker. Shameless plug - I’ve been working on xstreamq, “a reliable SQS on Redis” built on Redis Streams and consumer groups, with acks, visibility timeouts, retries with backoff and a dead-letter queue. The tracing approach below works exactly the same with it - the trace context simply travels in the message.
If you haven’t come across the Outbox pattern - it solves the problem that “save to DB and publish a message” can never be atomic across two systems. If you publish after the commit and crash in between, the message is lost. If you publish before the commit and the commit fails, you’ve announced an order that doesn’t exist. So instead, we write the event into an outbox table in the same DB transaction and let a separate process ship it (I wrote about it in more detail here). Simple and robust, but now the work hops across processes - exactly where traditional logging leaves you blind.
The Backend - One Container
services: lgtm: image: grafana/otel-lgtm ports: - "3000:3000" # Grafana UI - "4317:4317" # OTLP gRPC - "4318:4318" # OTLP HTTPThat’s it. grafana/otel-lgtm bundles an OTEL Collector, Loki, Tempo, Prometheus and Grafana with all the data sources pre-wired. For production you’d run them separately (or use Grafana Cloud, or any other OTLP-compatible vendor) - and the app code doesn’t change, only the OTEL_EXPORTER_OTLP_ENDPOINT.
Wiring up the SDK
The whole setup is one file -
const sdk = new NodeSDK({ resource: resourceFromAttributes({ [ATTR_SERVICE_VERSION]: '0.1.0', 'deployment.environment.name': process.env.DEPLOY_ENV ?? 'local', }), traceExporter: new OTLPTraceExporter(), metricReader: new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter() }), logRecordProcessors: [new BatchLogRecordProcessor(new OTLPLogExporter())], instrumentations: [getNodeAutoInstrumentations({ '@opentelemetry/instrumentation-fs': { enabled: false }, // way too noisy })],})
sdk.start()Each process gets its name from an env var - OTEL_SERVICE_NAME=orders-api, outbox-relay, fulfilment-worker.
One ESM gotcha that cost me some time - instrumentation works by patching modules like pg and ioredis as they are loaded. With CommonJS require that’s easy, with ESM import you need a loader hook registered before anything else is imported -
// telemetry/register.ts - run with: node --import ./dist/telemetry/register.js dist/api/main.jsimport { register } from 'node:module'
register('@opentelemetry/instrumentation/hook.mjs', import.meta.url)
await import('./sdk.js')Forget this and everything seems to work, you just get suspiciously empty traces with no DB or Redis spans.
Free Stuff - Auto-instrumentation
With zero changes to the application code we already get spans for -
- every incoming HTTP request (with route, status code etc.)
- every Express middleware and handler
- every SQL query - with the actual statement 🙌
- every Redis command
- every outgoing
fetchcall - and the W3Ctraceparentheader is added to it automatically, so the shipping service continues the same trace
We also get HTTP server metrics (http_server_request_duration_seconds) for free. That alone beats “grep the logs”.
One more small gotcha - for backwards compatibility, the Node HTTP instrumentation still emits the old semantic conventions by default (http_server_duration_milliseconds with http_method, http_status_code labels). Set OTEL_SEMCONV_STABILITY_OPT_IN=http to get the stable names, which is what current dashboards and docs expect.
Tracing the Pipeline
If you have read my previous posts, you know I like to write the orchestration layer as a pipeline of small functions returning a Result. Here is how creating an order looks -
export const createOrder = (db: Db) => (input: unknown) => pipeAsync( input, traced('order.validate', validateOrder), traced('order.price', priceOrder(db)), traced('order.save_with_outbox', saveWithOutbox(db)), tap(recordOrderCreated), )This is where a pipeline really pays off. Every step goes through the same function, so we can wrap each one in a span in a single place -
export const traced = <A, B>(name: string, step: Step<A, B>, options: TraceOptions<A> = {}) => (input: A): Promise<Result<B>> => tracer.startActiveSpan(name, { kind: options.kind }, parentOf(input, options.parentFrom), async (span) => { try { const result = await step(input) if (isErr(result)) markFailed(span, name, result.error) return result } catch (cause) { const error = unexpected(cause) markFailed(span, name, error) return err(error) } finally { span.end() } })An error Result marks the span red, an exception is recorded on it and turned into a Result. The business code knows nothing about spans - it just reads like a description of what happens, and the trace reads exactly the same way.
👆 POST /orders in Tempo - each pipeline step (order.validate, order.price, order.save_with_outbox) is a span, with the auto-instrumented SQL queries nested inside
The Interesting Part - Crossing Async Boundaries
Inside a process, OTEL tracks the “current span” for you (via AsyncLocalStorage in Node). HTTP calls carry it in headers automatically. But an outbox row sitting in Postgres or a message waiting in Redis? OTEL can’t know about those, so we pass the context along ourselves - and it is surprisingly little code.
When writing the outbox row, we take a snapshot of the current trace context -
export const currentTraceHeaders = (): Carrier => { const carrier: Carrier = {} propagation.inject(context.active(), carrier) // -> { traceparent: '00-4bf9…-00f0…-01' } return carrier}
const orderCreatedEvent = (order: Order): NewOutboxEvent => ({ aggregateId: order.id, eventType: 'order.created', payload: { orderId: order.id }, traceHeaders: currentTraceHeaders(), // stored in a jsonb column next to the event})The relay then continues the trace from that column (parentFrom) and injects its own context into the Redis message, which the worker continues in turn -
const relayEvent = (tx: Tx, redis: Redis, queue: string) => traced('outbox.relay', (event: OutboxEvent) => pipeAsync( event, traced('queue.publish', publishEvent(redis, queue), { kind: SpanKind.PRODUCER }), traced('outbox.mark_published', markPublished(tx)), tap(recordPublishLag), ), { parentFrom: (event) => event.traceHeaders }, )
export const fulfilOrder = (db: Db, shippingUrl: string, queue: string) => traced('order.fulfil', (message: unknown) => pipeAsync( message, traced('message.parse', parseOrderCreated), tap(tagOrder), traced('order.find_pending', findPendingOrder(db)), traced('shipping.book', bookShipping(shippingUrl)), traced('order.confirm_with_stock', confirmWithStock(db)), tap(recordConfirmed), ), { kind: SpanKind.CONSUMER, parentFrom: carrierOf }, // + messaging.* attributes using `queue` )And now one trace shows the HTTP request, the SQL inserts, the gap while the event sat in the outbox, the Redis publish, the worker picking it up, the HTTP call to the carrier and the final stock update - across three services 🤩
👆 One trace, three services - the order is saved by orders-api, relayed by outbox-relay, and fulfilled by fulfilment-worker, including the HTTP call to the carrier and the stock update
A side note - for single messages “child of” works well. When a consumer processes a batch of messages, each with its own origin, OTEL has span links for that, a span can point to many other traces.
”What Happened to My Order?”
That’s the question support actually gets - with an order id, not a trace id. Two small additions make it a one step lookup.
First, the trace id is stored on the order itself when it is created (and returned from GET /orders/:id) -
const saved = await ordersRepo.insert(tx, order, currentTraceId() ?? null)Second, every span that works on an order is tagged with order.id - including the worker, right after it parses the message, so failed fulfilments can be found too -
traced('message.parse', parseOrderCreated),tap(tagOrder), // annotate({ 'order.id': orderId }) on the consumer spanNow support can copy the traceId from the order, or search Tempo directly -
{ span.order.id = "3f6c0e2a-..." }Since the API, relay and worker all belong to the same trace, this one search shows the whole lifecycle - created, relayed, shipping booked (or failed), stock reserved (or not).
Metrics - Business and Technical
Traces tell you what happened to one request, metrics tell you how the system is doing overall. A few custom ones go a long way -
export const ordersCreated = meter.createCounter('orders.created')export const ordersFulfilled = meter.createCounter('orders.fulfilled') // by outcomeexport const outboxPublishLag = meter.createHistogram('outbox.publish.lag', { unit: 'ms' })export const outboxPending = meter.createObservableGauge('outbox.pending')outbox.pending and outbox.publish.lag are the ones that would page me in production - a growing outbox means the relay is down or Redis is struggling, long before a customer notices that their order confirmation never arrived. In Prometheus -
histogram_quantile(0.95, sum by (le) (rate(outbox_publish_lag_milliseconds_bucket[5m])))sum by (outcome) (rate(orders_fulfilled_total[5m]))Typing queries into Explore is fine for digging, but the main metrics deserve a dashboard - and the dashboard should live in the repo, not be clicked together once and lost. Grafana can provision dashboards from JSON files on startup, so it is just two more volume mounts on the lgtm container -
volumes: - ./grafana/provisioning/otel-demo-dashboards.yaml:/otel-lgtm/grafana/conf/provisioning/dashboards/otel-demo.yaml:ro - ./grafana/dashboards:/otel-demo/dashboards:roThe dashboard has four rows: business (orders created, fulfilment success rate, outcomes over time), outbox health (pending events, publish lag p50/p95/p99), API (request rate and p95 latency per route - from the auto-instrumentation, zero code) and problems (warning and error logs from all three services, each one a click away from its trace). Reviewed in PRs, versioned with the code, and identical on every machine.
👆 The provisioned “Orders - Business & Health” dashboard - orders created, fulfilment success rate and outcomes, outbox pending events and publish lag p50/p95/p99
So What Did It Cost?
Looking at the code -
- One SDK file, one register file, ~60 lines of
traced/untraced/ propagation helpers - Telemetry stays at the edges - repositories have none, services only record a metric or tag a span here and there, and the trace context hitches a ride on the outbox row
- One
docker-composeservice for the backend - No license, no agent, no vendor lock-in
And in return we get a distributed trace through a DB transaction, an outbox, a queue and an HTTP call, logs linked to traces, and business + technical metrics - all in one UI.
If you’re a tech lead still treating observability as an “expensive” line item to defer: the proprietary and price argument is dead. It’s time to adopt OTEL - for good!