Follow the label before trusting its meaning
A request arrives with tenant.id=forged and role=admin in its baggage header. Another service receives those same labels. That observation proves that information traveled, but it does not prove who supplied it or what the caller may do. This is a hypothetical investigation, reproduced with synthetic values in the downloadable fixture.
OpenTelemetry baggage carries application-defined key-value pairs alongside distributed context. It can make a label available to downstream telemetry without adding it to every function signature. It supplies no built-in integrity check. The official baggage guide explicitly separates that convenience from authentication and authorization.
Our experiment executes 14 cases with opentelemetry-api 1.45.3. Six use real HTTP requests between two owned loopback receivers. The unfiltered carrier sends six baggage entries to either receiver. A defined boundary policy retains three entries for the trusted destination and suppresses baggage plus traceparent for the simulated external destination. No real third party receives these values.
Separate propagation from the attributes you search
Baggage is a separate key-value store in context. A span attribute describes a recorded span, a metric attribute participates in a measurement and a resource attribute describes the emitting entity. Reading a baggage entry does not automatically attach it to any of those records. A Baggage Span Processor or explicit application code can copy selected entries, which creates another validation and cardinality boundary.
The traceparent header carries trace context, including identifiers and flags defined by W3C Trace Context. Tracestate carries tracing-system information under that specification. Baggage carries different application-defined values. Neither a trace identifier nor a caller-supplied tenant label establishes an authenticated principal.
A correlation ID can help connect observations without being a baggage item. Decide which field owns that job and where it is recorded. Duplicating an arbitrary identifier into baggage, every span and every metric label can increase the amount of retained data without improving the investigation. The fixture has no SDK exporter or telemetry backend, so it makes no claim about indexed attributes.
Inspect the actual outgoing carrier
baggage: tenant.id=forged,role=admin,account.tier=enterprise,release.channel=canary,test.cohort=control,debug.token=synthetic
traceparent: 00-11111111111111111111111111111111-2222222222222222-01The W3C Baggage specification defines the HTTP representation, including comma-separated members and encoding rules. A value containing a delimiter or nontrivial text needs the appropriate serialization, not string concatenation. Optional baggage member properties are not an authentication mechanism. Use a conforming propagator to parse and serialize the carrier, then apply application policy to the decoded values.
The receiver in our fixture reflects the header it actually received and decodes it with W3CBaggagePropagator. That gives a stronger observation than inspecting an in-memory dictionary before a request. It still says nothing about an untested proxy, framework or message broker. The chart counts observed baggage members and UTF-8 bytes in the baggage field value, excluding the field name and other HTTP headers.
| Scenario | Baggage members | Baggage value bytes | Traceparent received |
|---|---|---|---|
| Raw internal | 6 | 116 | Yes |
| Raw external simulation | 6 | 116 | Yes |
| Filtered internal | 3 | 60 | Yes |
| Filtered external simulation | 0 | 0 | No |
| Clear baggage only | 0 | 0 | Yes |
| Trace context only | 0 | 0 | Yes |
The raw internal and raw external-simulation requests each deliver six members and 116 bytes. Filtering the internal request leaves three members and 60 bytes. The external-boundary policy sends neither baggage nor traceparent. Clearing baggage alone sends zero baggage members while retaining traceparent. Ordinary HTTP fields such as Host still exist in every request.
Treat incoming context as a claim from its sender
A header can arrive from a browser, another service or a proxy. An internal network location does not establish who originally wrote each baggage item. Any participating service can add or change values. Do not use role, tenant.id or account.tier from received baggage to authenticate a caller, authorize an operation or select protected tenant data.
Keep the authenticated principal and authorization decision in a separately established application context. If that context supplies a telemetry label, distinguish its provenance from a label accepted from a caller. In this fixture, account.tier=free is a fixed synthetic server-owned value after an assumed authentication boundary. It replaces the incoming enterprise value, but no authentication provider or access-control operation is executed.
The SaaS permission-matrix guide covers decisions about allowed operations. Baggage propagation is another contract. A useful test can confirm that an untrusted label is dropped without proving that every protected operation uses the right principal. Keep both acceptance conditions.
Validate a small vocabulary before retaining entries
The fixture accepts release.channel only when its value is stable or canary. It accepts test.cohort only when its value is control or variant-a. Unknown keys disappear, and known keys with unexpected values disappear too. Restricting names without restricting values would still allow arbitrary labels to flow downstream.
ALLOWED = {
'release.channel': {'stable', 'canary'},
'test.cohort': {'control', 'variant-a'},
}
def sanitize(raw):
if len(raw.encode('utf-8')) > 256:
raise Rejected('ingress_bytes')
ctx = PROP.extract(
{'baggage': raw, 'traceparent': TRACE},
context=context.Context(),
)
clean = baggage.clear(ctx)
for key, permitted in ALLOWED.items():
value = baggage.get_baggage(key, context=ctx)
if value in permitted:
clean = baggage.set_baggage(key, value, context=clean)
return baggage.set_baggage('account.tier', 'free', context=clean)Two policy cases exercise unknown keys and invalid values for allowed keys. Both retain only the synthetic account.tier=free label. That label is still telemetry in this example. Release.channel and test.cohort are accepted for bounded observation, not used as instructions to route requests, grant features or change permissions.
A production entry point must also enforce transport limits before accepting an unbounded field into memory. Decide whether malformed or excessive input rejects a request, removes baggage or records a bounded diagnostic. The runner checks an already available Python string and raises a local policy exception. It supplies no production HTTP status mapping.
Make the destination part of the forwarding decision
The outbound policy compares an exact origin tuple: scheme, hostname and port. Two receivers share 127.0.0.1 but use different ports, so only the explicitly selected origin receives the retained context. A hostname substring or suffix match would not express the same rule. This check is a fixed-destination fixture, not a general URL parser or redirect policy.
def outbound(url, trusted_url, ctx, budget=128):
selected = (
ctx if origin(url) == origin(trusted_url)
else context.Context()
)
carrier = {}
PROP.inject(carrier, context=selected)
if len(carrier.get('baggage', '').encode('utf-8')) > budget:
raise Rejected('egress_bytes')
return carrierReview redirects separately in a real HTTP client. A decision for the initial origin is not permission to forward context to every redirect target. Confirm when your instrumentation injects headers and whether it can reintroduce baggage after application code removes it. The fixture uses explicit injection and receivers that return no redirects.
A telemetry collector is a later processing boundary. Removing an exported attribute there cannot retract a baggage header already delivered to an HTTP peer. Inspect the client request path and any gateway that owns the outgoing boundary. The context-propagation guidance calls out both incoming and outgoing context risks.
Restore the context that was current before the request
In Python, set_baggage returns an updated Context. It does not mutate or automatically attach the current context. The fixture confirms that an explicitly supplied context contains canary while both the original context and the current context remain empty. The Python baggage API documentation explains this distinction.
changed = baggage.set_baggage(
'release.channel', 'canary', context=context.Context()
)
token = context.attach(changed)
try:
assert baggage.get_baggage('release.channel') == 'canary'
finally:
context.detach(token)
assert not baggage.get_all()A nested fixture scope temporarily changes the channel to stable. Detaching the inner token restores canary, and detaching the outer token restores an empty context. Dropping tokens can leave context attached to later work in the same execution unit. Avoid a cleanup path that clears every context value without restoring what was there before.
Threads, asynchronous tasks, callbacks and message consumers need their own propagation and lifetime review. These context checks run on the runner's main execution unit, while the HTTP receivers extract each received carrier independently. They do not certify an application framework's task inheritance or automatic context cleanup.
Pass the intended context to the propagator explicitly
from opentelemetry.baggage.propagation import W3CBaggagePropagator
from opentelemetry.propagators.composite import CompositePropagator
from opentelemetry.trace.propagation.tracecontext import (
TraceContextTextMapPropagator,
)
PROP = CompositePropagator([
TraceContextTextMapPropagator(),
W3CBaggagePropagator(),
])
carrier = {}
PROP.inject(carrier, context=selected_context)An explicit context argument makes the carrier under investigation visible in code. Relying on an ambient context while a different context object is being edited is a common source of an empty or unexpected header. Inspect the selected propagator, the context passed to injection and the final carrier before examining a backend dashboard.
The fixture pins opentelemetry-api 1.45.3 and captures its propagator source internally. Its HTTP transport is Python's standard library, with environment proxies disabled and only loopback destinations. It does not test Requests, FastAPI, Django, a service mesh or an auto-instrumentation agent.
Distinguish configured propagation from carrier transport
OTEL_PROPAGATORS names configured propagators in distributions that honor the SDK environment-variable contract. Tracecontext and baggage refer to different propagation concerns. The SDK environment-variable specification is the reference for that setting. An explicit propagator composition such as this runner's PROP is still a code-level choice, not proof that changing an environment variable changes that object.
Automatic instrumentation can inject baggage into outgoing requests. Its coverage and exclusion controls depend on the language and integration. Verify the actual client instead of assuming that a server-side setting covers every HTTP library. Manual injection can expose the same values just as easily, as the raw external-simulation case demonstrates.
Message queues, gRPC and child-process carriers need explicit review of their own metadata format and supported propagation path. A W3C HTTP header example does not establish that a broker consumer extracts it or that a subprocess receives it. Those transports are outside this lab.
Keep observation labels small and deliberate
Do not put credentials, session tokens or API keys into baggage. Personal identifiers can also travel farther than intended and be retained in several systems. Once an entry becomes a log field, span attribute or metric dimension, its access and retention rules matter independently of the request that carried it.
A short user identifier is not automatically a low-cardinality dimension. Copying a different identifier for every customer into a metric label can create many distinct time series. The fixture instead permits a tiny vocabulary for two caller-supplied labels. It records no real customers and measures no telemetry-backend cost.
Trace sampling is not an egress filter. A request can carry context even when no span is ultimately exported. Baggage and trace context are separate propagation data, so explicitly choose which may leave. The audit-log minimization guide offers another place to review which observations a system should retain.
Set an application budget without inventing a protocol limit
The runner chooses a 256-byte limit for the incoming baggage field value and a normal 128-byte limit for the outgoing baggage field value. A negative case lowers the egress budget to 16 bytes and confirms a rejection before sending a request. Another case supplies an excessive incoming value and confirms the same no-forwarding outcome.
Those numbers are fixture policy, not universal W3C limits, HTTP server defaults or a measured safe maximum. They exclude the field name, traceparent and the rest of the request. A real ingress, proxy and client can impose different aggregate and individual field limits. Read their current behavior alongside the W3C processing requirements.
Section 3.3.2 of the W3C specification describes minimum propagation requirements when the resulting baggage string has at most 64 members and at most 8192 bytes. Platforms may support higher limits. Above their supported limits, whole members can be dropped, with no guaranteed retention order. These are protocol processing requirements, not a universal server capacity estimate. Our smaller limits are deliberate application policy at a trust boundary.
Silently truncating a serialized header can split a member or its encoding. Decide how to handle a failed budget and test the receiver's interpretation. The example rejects its forwarding operation, which makes that outcome observable without pretending the request succeeded with all its context.
Debug missing baggage in the order it can disappear
- Check whether the sender created a baggage-bearing context and whether code reads that explicit context or the current one.
- Confirm which propagator performs extraction and injection, then inspect the actual outgoing field after boundary policy.
- Check whether the next receiver gets that field and successfully extracts it before inspecting recorded telemetry.
- If a span or log lacks the label, verify whether an explicit approved mapping copies baggage to that signal.
An empty dictionary in a span is not evidence that an HTTP peer received no baggage. Conversely, an entry visible in a request header is not evidence that a backend indexed it. Keep observations labeled by boundary: context, carrier, receiver and exported record.
Malformed members and duplicate keys have protocol and implementation-specific processing details. This lab uses valid synthetic members and does not certify every parser edge case. Avoid recording complete baggage fields in production diagnostics. A bounded count or a reviewed list of rejected key names may answer the question without retaining the values.
Run the carrier investigation locally
Download the Python experiment and saved results. The dependency is isolated from the application project. The runner starts two local HTTP receivers, makes six requests and shuts both receivers down.
uv run --no-project --with opentelemetry-api==1.45.3 python experiment.py > actual.jsonFourteen assertion-backed cases include six wire cases, four policy checks and four context checks. Two executions produced byte-identical JSON. The chart and native table read the six wire records directly. Policy budget failures send no request, and the context checks do not claim to exercise a web framework.
The experiment establishes behavior for this API version and explicit policy. It does not establish end-to-end authorization, exporter behavior, automatic instrumentation coverage, proxy handling, CORS, a broker path or production performance. Before adopting the pattern, test every actual sender and receiver that owns one of those boundaries.
Close the investigation at both trust boundaries
Language-specific Java, JavaScript, .NET, Go and Rust integrations need their own configuration and context-lifetime checks. Collector transformations, Kubernetes or mesh policies and browser CORS controls are separate deployment tasks. The examples here deliberately provide no tested recipe for those environments.
Record which incoming keys and values may survive, which values are supplied by authenticated application context and which outgoing origins may receive any context. Revisit that decision when adding a new HTTP client, destination or exporter mapping. The next successful request should demonstrate both useful correlation and the intended absence of unapproved labels.
Sources
Documentation checked .

Continue the conversation
Comments (0)