SR-003 — Observability & Tracing: System Requirements

By Engineering Team•September 24, 2026•7 min read
Metadata Details
System Name Platform-Wide Observability & Distributed Tracing
Document ID SR-2026-OBS-001
Author Engineering Team
Status Approved

Traces back to BRD-003 — Platform-Wide Observability & Distributed Tracing.


Functional Requirements

Identifier Contract

  • FR-01 (Exactly Four Identifiers): the platform MUST use exactly four tracing identifiers — traceparent/tracestate (W3C trace context), correlation_id, gateway_request_id, and request_id — and MUST NOT introduce a fifth identifier for a new transport or service without updating this contract first.
  • FR-02 (Correlation Guarantee): correlation_id MUST be the one identifier guaranteed to carry the same value on both sides of any hop — it is the identifier support/on-call use to resolve a whole operation, minted at the Nginx/REST edge (X-Correlation-ID) or by the originating service if the request has no upstream edge.
  • FR-03 (Single-Hop Debugging IDs Stay Local): gateway_request_id (Nginx’s $request_id) and request_id (Go’s Echo middleware.RequestID() / Rust’s request_logger per-request UUID) MUST NOT be propagated past the service/hop that minted them, and MUST NOT be substituted for correlation_id.

REST Propagation

  • FR-04 (REST Header Propagation): traceparent, X-Correlation-ID, and X-Gateway-Request-ID MUST propagate as HTTP headers at every REST hop. Go wires this via otelecho.Middleware plus inline middleware in NewEchoServer; Rust via request_logger’s RequestMakeSpan/set_gateway_otel_attr/set_correlation_otel_attr, applied once in transport/router.rs.
  • FR-05 (Go Echo Middleware Order): a Go service’s Echo middleware chain MUST run in this fixed order: otelecho.Middleware → inline traceparent/X-Gateway-Request-ID/X-Correlation-ID extraction → middleware.Recover() + middleware.RequestID() + access logger → requestDurationMiddleware() last. requestDurationMiddleware() MUST stay innermost, since it calls c.Error(err) itself to make c.Response().Status readable before e.HTTPErrorHandler runs.

gRPC Propagation

  • FR-06 (gRPC Metadata Propagation): traceparent and correlation_id MUST propagate via gRPC metadata, never the request payload. Go: TraceContextUnaryServerInterceptor (server, chained first in NewGRPCServer) and TraceContextUnaryClientInterceptor (client, a dial option in NewGrpcClient). Rust: grpc::server::trace_layer() (server) and grpc::client::TraceContextLayer (client).
  • FR-07 (gateway_request_id Excluded from gRPC): gateway_request_id MUST NOT be added to a gRPC interceptor or layer — it is REST-entry-point-only by design; correlation_id is the identifier that continues past the REST/gRPC trust boundary.

Pub/Sub Propagation

  • FR-08 (Pub/Sub Envelope Propagation): traceparent and correlation_id MUST propagate via the Pub/Sub envelope header (MessageHeader.traceparent/.correlation_id), injected on publish and extracted on receive, for every publisher/subscriber in the platform. Go: message.MessageHeader via WithMessageReceiver (receive) and gotel.GetTextMapPropagator().Inject + log.GetCorrelationID(ctx) (publish). Rust: rust_lang_core_lib::pubsub’s MessageEnvelope<D>/MessageHeader, current_message_header(tenant_id) (publish) and the pubsub.receive span wrapping the handler (subscribe).
  • FR-09 (gateway_request_id Excluded from Pub/Sub): gateway_request_id MUST NOT be added to a Pub/Sub MessageHeader, for the same reason as FR-07.

Span Wrapping

  • FR-10 (Mandatory Span Wrapping): every public service and repository method MUST be wrapped in a span. Go: otel.WithSpan[T](ctx, "Type.Method", func(ctx) (T, error)). Rust: #[tracing::instrument], with every struct/reference/trait-object parameter in skip() so it is never auto-printed via Debug. Node: runWithRequestContext('Type.Method', fn), backed by AsyncLocalStorage.
  • FR-11 (Go Tracing Codegen — gowrap): a Go service MUST generate its tracing decorator via the documented go:generate gowrap one-liner — never hand-write one — using the fixed ../../../../../go-lang-core-lib/generator/otel_generator.tmpl relative path (never shortened, never absolute).
  • FR-12 (Go Background-Goroutine Context Rule): a goroutine launched from a Go service or repository MUST use context.WithoutCancel(ctx), never context.Background(), so the OTel span, tenant_id, user_id, and correlation_id survive into the goroutine.
  • FR-13 (Node Fan-Out Trace Root): runInNewTrace MUST be used only at a genuine fan-out point (one unit of work spawning many independent downstream units) — never as a default in place of runWithRequestContext.

Metrics Collection

  • FR-14 (Per-Language Metric Emission): every service MUST emit its language’s documented metrics via its core lib’s shared constructors — Go: http.server.request.duration/rpc.server.request.duration/pgxpool gauges via otel.InitObservability; Rust: http.server.request.duration/rpc.server.request.duration/sqlx pool gauges via db::connect_postgres and the Axum/gRPC metrics layers; Node: http.client.request.duration/event-loop-lag gauges — never a hand-rolled equivalent metric (per the central 05-performance-and-metrics rule).
  • FR-15 (Container-Level Resource Metrics): container CPU/memory/network/restart metrics MUST be collected for every service with zero per-service Dockerfile or code change, via a single shared container-metrics exporter reading each container’s cgroup stats over the Docker socket. Implementation note: the platform’s central rules (.claude/rules/05-performance-and-metrics.md, and several core-lib CLAUDE.md files) describe this component as cadvisor; the container actually deployed in development/docker-compose.yml is docker-exporter (ghcr.io/dlepaux/docker-exporter, port 8091:9713), serving the identical role. This naming mismatch is tracked as technical debt — see TD-00003.
  • FR-16 (Metrics Collection & Visualization Pipeline, Local Dev): every metric from FR-14/FR-15 MUST be scrapeable end-to-end in local development: each service exports OTLP metrics to the OTel Collector (4317); the Collector exposes them on its own Prometheus exporter (9464); Prometheus (development/otel/prometheus.yml) scrapes that single endpoint; Grafana renders them via a provisioned Prometheus datasource. No service is scraped directly by Prometheus.
  • FR-17 (Cardinality Guardrail): no metric label MUST ever be tenant_id, correlation_id, or any other unbounded per-request value — route/method templates only, per the identical rule stated in all three core libs.

Log Aggregation

  • FR-18 (Centralized Log Shipping, Local Dev): every service’s stdout/JSON logs MUST be collected without per-service log-shipping code — a shared log-forwarding agent (Vector, development/otel/vector.yaml) reads every container’s Docker logs off the Docker socket and ships them to a centralized log store (Loki), rather than each service integrating its own shipping client.
  • FR-19 (Trace-to-Log Correlation): a log line containing a trace_id MUST be navigable directly to its matching distributed trace from the log-viewing UI — implemented via Grafana’s Loki datasource derivedFields regex matching trace_id and linking to the Tempo datasource, and Tempo’s datasource tracesToLogsV2 configuration linking a trace back to its Loki log lines.

Cloud Production Export (Gap)

  • FR-20 (Vendor-Neutral Export Contract): every service MUST continue exporting traces/metrics via standard OTLP to the OTel Collector, never directly to a vendor-specific SDK/endpoint — so that adding a cloud export target is a Collector-config change (new exporter, e.g. googlecloud), not an application code change in every service. (Currently satisfied by construction — no service exports anywhere except the local OTel Collector today.)
  • FR-21 (Cloud Monitoring Export Target): the platform SHOULD be able to export the same traces/metrics/logs pipeline to a managed cloud monitoring service (e.g. GCP Cloud Monitoring, Cloud Trace, Cloud Logging) once a cloud deployment target exists, configured as part of that deployment’s infrastructure-as-code rather than hand-configured per environment. (Gap — no cloud deployment target, Terraform, or other IaC exists in this repository today; tracked as technical debt, see TD-00003.)

Client-Side Instrumentation (Flutter & React)

  • FR-22 (Real Client-Side Span Creation, Not Just Header Injection): both ui-application (Flutter) and ui-admin-application (React) MUST create a real client-kind OTel span for each outbound request, not merely inject traceparent/X-Correlation-ID headers. Flutter: base_network_service.dart’s _addTelemetryHeaderInterceptor() starts a span via OTel.tracer().startSpan(...) and ends it with an Ok/Error status in the response/error handler. React: core/telemetry/tracing.ts’s XMLHttpRequestInstrumentation auto-instruments every outbound XHR call, plus a manual startUploadSpan() helper for upload flows.
  • FR-23 (Flutter Structured Log Format Parity with Backend): ui-application’s logger (core/utils/app_logger.dart’s AppLog/_RequestStyleLogPrinter) MUST emit a single-line TIMESTAMP LEVEL message shape with trace_id/span_id/correlation_id fields sourced from the active OTel span context, mirroring go-lang-core-lib’s zap-based request-log field names (log.LogInfoWithTrace’s trace_id/span_id/correlation_id fields) — so a mobile log line and a backend log line for the same operation read with the same field shape and are visually/structurally comparable side by side.

Non-Functional Requirements

Traceability & Consistency

  • NFR-01 (Cross-Language Contract Parity): Go, Rust, and Node core libs MUST implement the same four-identifier contract with the same per-transport propagation scope — a drift between languages (e.g. one language propagating gateway_request_id over gRPC) is a defect, not an acceptable variation.
  • NFR-02 (No Silent Identifier Drift): adding a new transport or language binding MUST update this document’s propagation contract and the relevant core lib’s CLAUDE.md in the same change — the two MUST NOT be allowed to drift apart. (Process gap previously observed — see TD-00003.)
  • NFR-03 (gRPC-Originated Pub/Sub Correlation): a Pub/Sub message published from a gRPC-invoked handler SHOULD carry a populated correlation_id sourced from the inbound gRPC call’s metadata. (Gap — tracked as technical debt, see TD-00003.)

Browser/Client Integration

  • NFR-04 (CORS Header Allowance): traceparent/tracestate and X-Correlation-ID MUST be listed in Access-Control-Allow-Headers in development/nginx.conf, or a browser client’s CORS preflight rejects the header before it ever reaches the gateway.
  • NFR-05 (No Tenant Header from Browser Clients): a browser/mobile client MUST inject traceparent and X-Correlation-ID via its HTTP client interceptor, but MUST NEVER inject X-Tenant-ID itself — tenant scope comes only from the Firebase JWT, decoded server-side by Nginx.
  • NFR-10 (Client Span Export Status Must Not Be Assumed Live): client-side spans created per FR-22 MUST NOT be assumed to reach a collector without checking each app’s current export configuration — Flutter’s OtelTracingService.init() currently registers a _NoopSpanProcessor that discards every span (no collector wired up yet, by explicit code comment); React’s initTracing() only attaches a real BatchSpanProcessor/OTLPTraceExporter when an otelEndpoint value is configured, and exports nothing otherwise. (Gap — tracked as technical debt, see TD-00003.)
  • NFR-11 (React Frontend Log Format Divergence from Flutter/Backend): ui-admin-application’s frontend logging (the loglevel package, plain [Component] message-style prefixes) does NOT currently follow the structured, field-based log shape FR-23 requires of Flutter — there is no cross-platform frontend logging format parity yet, only a Flutter-to-backend one. (Gap — tracked as technical debt, see TD-00003.)

Runtime-Specific Transport

  • NFR-06 (OTLP Transport Parity per Runtime): Go/Rust microservices MUST export OTLP over gRPC (port 4317); Firebase Functions MUST export OTLP over HTTP (port 4318, internal to the Docker network) — this split MUST stay consistent with each runtime’s own constraints, not be silently unified.

Sensitive Data

  • NFR-07 (Sensitive-Value Logging Carve-Out, Rust): a value standing in for real secret material (e.g. an OTP code with no live provider behind it yet) MUST be logged only via log_debug!, never log_info!, so it is structurally absent from production (LOG_LEVEL=info) logs.
  • NFR-08 (No Raw PII/PCI in Aggregated Logs): centralized log aggregation (FR-18) MUST NOT become a second, un-audited place sensitive data leaks to — a service’s own logging discipline (structured logs, no raw PII/PCI fields) is what keeps aggregated logs safe; the log-shipping layer (Vector) performs no masking of its own and MUST NOT be relied on as a masking boundary.

Cloud Readiness

  • NFR-09 (No Cloud-Specific Code in Services): a future cloud-monitoring export target (FR-21) MUST be reachable by reconfiguring the OTel Collector’s exporters alone — no service’s own code should ever need to change to support a new export destination, preserving FR-20’s vendor-neutral contract.