1. Analyze the Request:
* Goal: Build an "OpenTelemetry-first stack".
* Key Components: Schema alignment, Baggage rules, Sampling gates, Service maps.
* Implicit Requirement: Practical guidance, code/configuration examples, and architectural principles for a modern observability setup based on OTel.
-
Deconstruct the Components:
-
"OpenTelemetry-first": This means OTel is the source of truth, not an add-on. The stack relies on OTel Collector, OTel SDKs, and OTLP (OpenTelemetry Protocol). It implies vendor neutrality.
-
Schema Alignment:
- Problem: Different services name things differently (e.g.,
user.id vs userID), units differ, semantic conventions evolve.
- Solution: Semantic Conventions (SemConv), Schema URLs, and transforming data in the Collector to enforce consistency before it hits the backend.
-
Baggage Rules:
- Problem: Context propagation is critical, but passing too much or sensitive data is bad. Need logic to control what gets passed.
- Solution: Define what goes into Baggage (e.g., TenantID, FeatureFlags) vs. Span Attributes. Use OTel Baggage API. Implement filtering/limits in the Collector or SDK.
-
Sampling Gates:
- Problem: Cost vs. Visibility. High throughput requires dropping data, but intelligently.
- Solution: Tail-based sampling (needs a collector), Head-based sampling (SDK), and dynamic sampling (rate limiting or policy-based).
- Strategy: "Gates" suggests conditional logic (e.g., keep all errors, sample 1% of success).
-
Service Maps:
- Problem: Understanding topology.
- Solution: Derived from trace data. Requires consistent service naming, peer service attributes, and potentially generating metrics from traces (SpanMetrics).
-
Structure the Response:
- Introduction: Define the philosophy (OTel as the center).
- Architecture Diagram (Mental): SDKs -> OTel Collector -> Backend.
- Section 1: Schema Alignment (The Contract): Semantic conventions, Transformation in Collector (OTTL).
- Section 2: Baggage Strategy (Context Propagation): What to propagate, Security/Size limits, Unpacking baggage into attributes.
- Section 3: Sampling Gates (Cost Control): Head vs. Tail, Probabilistic vs. Deterministic, Collector configuration (Tail Sampling Processor).
- Section 4: Service Maps (Topology): Service naming, Edge detection (Peer Service), Reducing to Metrics (Span-to-Metrics).
- Summary/Stack: List specific tools (Collector, Grafana/Prometheus/Jaeger, etc.).
-
Drafting the Content (Iterative Refinement):
-
Schema Alignment: Mention urn:otel:semconv. Focus on the Collector as the enforcement point. Use OTTL (OpenTelemetry Transformation Language) examples.
- Example: Rename
http.status_code to http.response.status_code (if legacy). Ensure consistency.
-
Baggage: This is often misunderstood. Baggage is for cross-cutting concerns that affect the request path (e.g., testing a feature flag, multi-tenancy).
- Rule: Don't put PII in baggage (it goes over the wire).
- Code: Show how to inject/extract.
-
Sampling Gates: This is complex. A "Stack" needs a central collector for Tail Sampling.
- Scenario: A "Gate" that checks latency. If > 500ms, keep 100%. If < 100ms, keep 10%.
- Config:
tail_sampling processor in the Collector.
-
Service Maps: How do we build them? Usually, the backend does it, but to be "OTel-first", we should ensure the attributes are there (service.name, peer.service). Also, Service Graphs based on metrics generated from traces are faster. Mention spanmetricsconnector.
-
Refining the Examples (Technical Details):
- Collector Config: This is the core of the infrastructure. I need a robust YAML example showing the pipeline:
receivers -> processors (transform, baggage, sampling) -> exporters.
-
Review against Constraints:
- Is it OTel-first? Yes, SDKs + Collector.
- Schema included? Yes (Transform processor).
- Baggage included? Yes (Baggage processor/API).
- Sampling included? Yes (Tail sampling).
- Service Maps? Yes (Attributes + SpanMetrics).
-
Final Polish:
- Use clear headings.
- Use code blocks for YAML and Go/Python snippets.
- Add a "Why this matters" conclusion.
(Self-Correction during drafting): I initially thought about using specific vendor backends (like Datadog or Honeycomb), but "OTel-first" implies the backend should be pluggable. I will focus on the Collector configuration which prepares data for any backend. I will use Prometheus/Grafana/Tempo as the generic reference backend because it's open source and widely understood, but keep the OTel config generic.
Specific focus on "Gates": I'll interpret "Sampling Gates" as the logic policies within the tail_sampling processor (e.g., and, latency, status_code).
Schema Alignment: Emphasize the Semantic Conventions stability. If you upgrade OTel versions, schemas might change. The collector fixes this.
- Final Output Generation: (Proceed to generate the structured response).
Building an OpenTelemetry-first stack means treating OTel not just as a data pipe, but as the central control plane for your observability logic. In this architecture, the OTel Collector is the most critical component, handling data quality, cost control, and context propagation before data ever reaches your backend (Prometheus, Tempo, Mimir, ClickHouse, etc.).
Here is the architectural blueprint for building this stack, focusing on Schema Alignment, Baggage, Sampling, and Service Maps.
1. Architecture Overview
- SDKs (Language Native): Instrument code to emit traces, metrics, and logs.
- OTel Collector (The Gatekeeper): A fleet of collectors (Agent mode) running sidecar or DaemonSet.
- Central Collector (The Aggregator): Handles tail-based sampling and metric aggregation.
- Backend: Vendor agnostic storage (e.g., Grafana Stack, OpenSearch, or Cloud Native build).
2. Schema Alignment (The Contract)
Schema misalignment is the #1 cause of broken dashboards. An OTel-first stack enforces Semantic Conventions at the edge.
Strategy: The "Pivot" Attribute
You must standardize on a single high-cardinality identifier (usually service.name + service.namespace).
Collector Config (Transform Processor):
Use the transform processor to enforce naming conventions and fix common SDK lazy habits (e.g., renaming http.method to http.request.method if using older instrumentation).
# otel-collector-config.yaml
processors:
transform:
error_mode: ignore
trace_statements:
- context: span
statements:
# Enforce Semantic Conventions (SemConv)
- set(attributes["service.name"], attributes["service.name"]) where attributes["service.name"] != nil
- set(attributes["service.name"], "unknown_service") where attributes["service.name"] == nil
# Standardize HTTP attributes
- set(attributes["http.route"], attributes["http.path"]) where attributes["http.route"] == nil
# Redact sensitive data
- delete_key(attributes, "authorization")
- delete_key(attributes, "password")
3. Baggage Rules (Context Propagation)
Baggage is used to pass static context (e.g., TenantID, BetaTestFlag, MerchantID) alongside the trace context. This allows downstream services to tag their telemetry without accessing the original user request.
The Rules:
- Allowlist: Never accept all baggage blindly from external traffic (security risk).
- Limits: Baggage is sent in HTTP headers. Cap the size to prevent 4xx errors.
Baggage Processor Configuration:
Instead of configuring baggage in every SDK, manage it centrally in the Collector using the baggage processor.
processors:
baggage:
# Context: Incoming data from specific services
statements:
# Only allow specific keys from the "frontend" service
- insert(attributes["tenant.id"], baggage["tenant.id"]) where IsMatch(resource.attributes["service.name"], "frontend")
# Promote baggage to Span Attributes for easy querying in the backend
- insert(attributes["user.beta_tester"], baggage["beta_flag"])
4. Sampling Gates (Cost Control)
In an OTel-first world, you move away from random "Head Sampling" (dropping 90% of traffic at the SDK) toward intelligent "Tail Sampling" at the Collector layer. This ensures you catch the "unknown unknowns" (errors in low-traffic endpoints) while controlling volume.
The Setup:
- SDK: Sends 100% of traces to the local Collector.
- Local Collector: Batches data and forwards to the Central Collector.
- Central Collector: Runs
tail_sampling.
Tail Sampling Policy Example:
processors:
tail_sampling:
decision_wait: 10s # Wait 10s to see the whole trace
policies: [
{
name: error-policy,
type: status_code,
status_code: { status_codes: [ERROR] }
},
{
name: latency-policy,
type: latency,
latency: { threshold_ms: 1000 } # Keep traces > 1s
},
{
name: probabilistic-policy,
type: probabilistic,
probabilistic: { sampling_percentage: 10 } # Keep 10% of healthy traffic
}
]
Note: Tail sampling requires state. You must use loadbalancingexporter (based on TraceID) before the tail sampling processor to ensure all spans of a trace arrive at the same collector instance.
5. Service Maps (Topology)
Service Maps are not just pretty pictures; they are derived from Span Metrics. By generating metrics from traces, you can build a real-time map that shows request volume, error rate, and latency between services.
The Connector: spanmetrics
This connector consumes traces and produces metrics (Prometheus format).
connectors:
spanmetrics:
# Dimensions to group by (creates the edges on the map)
dimensions:
- service.name
- service.namespace
- peer.service # The destination service name
histogram:
explicit:
buckets: [100ms, 250ms, 500ms, 1s, 2.5s, 5s]
service:
pipelines:
traces:
receivers: [otlp]
processors: [batch]
exporters: [spanmetrics, otlp/tempo] # Send to Connector AND Backend
metrics:
receivers: [spanmetrics] # Receive from Connector
exporters: [prometheus]
Visualizing the Map:
Most modern backends (Grafana, Datadog, Jaeger) will ingest these "Service Graph" metrics and render the topology automatically.
6. The Complete Stack Manifest
Here is how the pieces fit together in a config.yaml for your Central OTel Collector.
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
processors:
# 1. Schema Alignment
transform:
trace_statements:
- context: resource
statements:
- set(attributes["service.namespace"], "production") where attributes["service.namespace"] == nil
# 2. Baggage Handling
baggage:
statements:
- insert(attributes["tenant.id"], baggage["tenant.id"])
# 3. Memory Limiter (Safety)
memory_limiter:
check_interval: 1s
limit_percentage: 75
spike_limit_percentage: 15
# 4. Tail Sampling (Cost Gate)
tail_sampling:
decision_wait: 10s
policies:
- name: keep-errors
type: status_code
status_code: { status_codes: [ERROR] }
- name: keep-slow
type: latency
latency: { threshold_ms: 500 }
- name: keep-some
type: probabilistic
probabilistic: { sampling_percentage: 5 }
connectors:
# 5. Service Map Generation
spanmetrics:
dimensions: [service.name, peer.service]
exporters:
otlp/tempo:
endpoint: tempo:4317
tls:
insecure: true
prometheus:
endpoint: "0.0.0.0:8889"
namespace: otel_span_metrics
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, transform, baggage, tail_sampling]
exporters: [spanmetrics, otlp/tempo]
metrics/spanmetrics:
receivers: [spanmetrics]
exporters: [prometheus]
Summary of the Stack
- Schema: Enforced via
transform processor.
- Baggage: Extracted and secured via
baggage processor.
- Sampling: Intelligence applied via
tail_sampling.
- Maps: Materialized via
spanmetrics connector.
- Result: You own the data logic, not the vendor. You can switch backends simply by changing the
exporter.