Skip to Content
gentlemans-stack
ReferenceLibs

observability

OpenTelemetry for the stack: traces and metrics through the Node SDK over OTLP, with a light API that is a no-op until a service starts the SDK.

The browser and the services send telemetry over OTLP to the Collector, which forwards it to Grafana

API

  • . (only @opentelemetry/api, safe in any package or test): withSpan(name, attributes, fn) runs fn in an active span, records a throw as an error and always ends the span. getTraceContext() returns { spanId, traceId } of the active span or undefined. createMetrics() returns the named instruments (authFailures, counted by cause where a request is rejected, and invitesAccepted). Request duration is not here: instrumentation-http already records http.server.request.duration for every service.
  • ./instrument: runInstrumentation({ serviceName }) starts the Node SDK with the http, undici, mongodb and ioredis instrumentations. It does nothing when OTEL_SDK_DISABLED=true.
  • ./orpc-middleware: createSpanMiddleware() wraps a procedure in a span named after its path (workspaces.create) tagged with user.id and workspace.id. Attach it after the authenticate and intent middleware, as iam-service and todo-service do.
  • ./log-drain: createObservabilityLogPlugin() is an evlog plugin that ships every wide event to the Collector as an OTLP log record and stamps it with the active span's traceId and spanId. Pass it to initLogger({ plugins }); evlog applies it to the request logger too. It is undefined when the SDK is disabled.
  • ./web (browser only, imported by apps/todo-ui): initWebObservability({ apiOrigins, collectorUrl, dev, sampleRatio, serviceName }) starts browser tracing (document load, fetch), Core Web Vitals as OTel histograms (browser.web_vital.*) and uncaught errors / unhandled rejections as exception events on browser.error spans, all over OTLP/HTTP to the Collector. It returns undefined and does nothing on the server, without collectorUrl, or when already started. Sampling is 100% when dev, else sampleRatio (default 0.1).

Layers

Services never import ./instrument from main.ts. Each service has src/instrument.ts (a second esbuild entry, additionalEntryPoints) that calls runInstrumentation, and runs node --require ./instrument.js main.js (the Dockerfile CMD, and runtimeArgs on the serve target). That order lets the instrumentations patch the modules before they load. Third-party packages stay external in the bundle, so the OpenTelemetry packages must be in the service's package.json; pnpm sync:deploy-deps <service> --check verifies it.

@orpc/otel adds oRPC's own spans (route, find_procedure, validate_input, handler). It is pinned to the exact @orpc/server version (a second @orpc/shared would never see its config) and re-enabled after the SDK starts, because as an ESM package it holds its own copy of @opentelemetry/api.

Server spans are named METHOD /route with identifiers masked (PATCH /workspaces/:id), CORS preflights and the GET / health probe are not traced, and the exporters' own requests to the Collector are ignored; fetch spans in the browser get the same names. The browser flushes its spans every second and on pagehide, so a server span is not left without its browser parent when a tab closes. A procedure must run each middleware once: build the router from a bare implement(...), not from a chain that already carries authenticate/traced (iam-service's implementers.router), or oRPC applies the chain a second time.

Instrumentations are listed explicitly, not through auto-instrumentations-node, because the dependency sync only sees real require() calls. Mongo uses the driver instrumentation only: Better Auth and mongoose both end in the driver, so adding mongoose duplicates spans.

Browser privacy rules

The browser holds no secret: the Collector's HTTP receiver is public. lib/web-privacy.ts (specs in web-privacy.spec.ts, web.spec.ts, web-errors.spec.ts; the Playwright spec apps/todo-ui/e2e/tracing.spec.ts checks it in a real browser) enforces.

  • traceparent goes only to apiOrigins and the page's own origin. Each origin becomes an anchored matcher, so https://api.example.com.evil.test and another port do not match; an invalid entry is dropped (no header is the safe failure).
  • Every URL attribute (url.full, http.url, http.target) loses its query string, fragment and credentials in a span processor's onEnding, which covers every instrumentation. url.query and url.fragment are blanked. The Collector strips them again.
  • Errors carry only the type and a 200-character message with URLs stripped, no stack and no page URL, at most 20 per page.
  • No instrumentation reads input or form values, and request or response bodies are not recorded.

Generators

deployable-service and deployable-web-app wire all of this in by default. Pass --observability=none to leave the project uninstrumented.

Configuration

VariableDefaultMeaning
OTEL_SDK_DISABLEDunsettrue turns everything off (tests, CI).
OTEL_EXPORTER_OTLP_ENDPOINThttp://localhost:4318Where spans and metrics go.
OTEL_SERVICE_NAMEthe name the service passesOverrides it.
SERVICE_VERSION0.0.0service.version resource attribute.
DEPLOY_ENVlocaldeployment.environment.name resource attribute.

The sampler, exporters and propagators follow the standard OTEL_* variables. The browser takes its settings as arguments: apps/todo-ui reads VITE_OTEL_COLLECTOR_URL (see .env.example).

Tests

vitest.setup.ts sets OTEL_SDK_DISABLED=true. Assert spans with InMemorySpanExporter and SimpleSpanProcessor({ exporter }) from @opentelemetry/sdk-trace, as src/lib/spans.spec.ts does, never against a running Collector.

Commands

pnpm nx run observability:typecheck   # type-check the package
pnpm nx run observability:test        # run the Vitest suite

On this page