Distributed Tracing
Carry one trace from a browser or mobile app through a Rust service and on to the services it calls — CORS for traceparent and baggage, session.id on server spans, and injecting the context into reqwest requests.
A trace crosses a process boundary in HTTP headers. traceparent links the next span to the previous one, and baggage carries the session.id of the browser session that started it. A Rust service has two jobs: read both headers on the way in, which the framework middleware does, and write them on the way out, which nothing does for you. If either side is missing, nothing fails; the next service just starts a new trace.
The path
| Step | Where | What has to be true |
|---|---|---|
| 1 | Browser or mobile SDK | The request URL is a propagation target, so traceparent is added (and baggage, from the Browser SDK). |
| 2 | Browser | The CORS preflight response allows traceparent, tracestate, and baggage. |
| 3 | Rust server | The global propagator is set and the middleware extracts the context. |
| 4 | Rust server | A span processor copies session.id from baggage onto every span. |
| 5 | Rust server | Outgoing requests carry the headers injected from the current span. |
1. Client: choose where headers go
The Browser SDK adds the headers only to requests that match tracePropagationTargets, for example tracePropagationTargets: ['api.example.com']. List only your own APIs: the baggage header carries the session ID.
The mobile SDKs send traceparent and have their own switches: traceparent.onlyAllowDomains on iOS, networking.enable_traceparent_injection on Android, and the HTTP clients described in Flutter networking and React Native networking.
2. Server: allow the headers in CORS
traceparent and baggage are not CORS-safelisted, so a cross-origin browser request that carries them is preflighted. If the preflight response does not allow them, the browser blocks the request itself, not just the tracing. Native mobile clients are not affected.
tower-http = { version = "0.6", features = ["cors", "trace"] }use axum::http::{header, HeaderName, HeaderValue, Method};
use tower_http::cors::CorsLayer;
let cors = CorsLayer::new()
.allow_origin("https://shop.example.com".parse::<HeaderValue>().unwrap())
.allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE])
.allow_headers([
header::CONTENT_TYPE,
header::AUTHORIZATION,
HeaderName::from_static("traceparent"),
HeaderName::from_static("tracestate"),
HeaderName::from_static("baggage"),
]);
let app = Router::new()
.route("/users/{id}", get(get_user))
.layer(trace_layer)
.layer(cors);In axum the layer added last runs first, so the CORS layer answers the preflight OPTIONS request before the trace layer sees it. Browsers do not send custom headers on a preflight, so it could never join the trace anyway. With actix-web, allow the same three headers in your CORS middleware.
3. Server: continue the trace
This is the middleware from Framework Middleware plus the propagator from Installation. With both in place, the server span's parent is the client's request span, and the default sampler follows the sampled flag in traceparent, so a trace the client recorded is not cut at the server.
4. session.id on every span
The baggage propagator puts session.id into the request's context, but nothing writes it onto spans. A span processor does that for every span started while handling the request, child spans and database spans included:
use std::time::Duration;
use opentelemetry::baggage::BaggageExt;
use opentelemetry::trace::Span as _;
use opentelemetry::{Context, KeyValue};
use opentelemetry_sdk::error::OTelSdkResult;
use opentelemetry_sdk::trace::{Span, SpanData, SpanProcessor};
#[derive(Debug)]
struct SessionIdProcessor;
impl SpanProcessor for SessionIdProcessor {
fn on_start(&self, span: &mut Span, cx: &Context) {
if let Some(session_id) = cx.baggage().get("session.id") {
span.set_attribute(KeyValue::new("session.id", session_id.to_string()));
}
}
fn on_end(&self, _span: SpanData) {}
fn force_flush(&self) -> OTelSdkResult {
Ok(())
}
fn shutdown_with_timeout(&self, _timeout: Duration) -> OTelSdkResult {
Ok(())
}
}Register it on the tracer provider in your setup function:
let tracer_provider = SdkTracerProvider::builder()
.with_span_processor(SessionIdProcessor)
.with_batch_exporter(span_exporter)
.with_resource(resource.clone())
.build();On browser telemetry session.id is a resource attribute; on server spans it is a span attribute with the same name. A query on session.id returns both halves of the session.
CAUTION — Baggage is sent onward
Baggage is injected into every outgoing request in the next step. Do not put sensitive data in it, and inject only into requests to your own services.
5. Outgoing requests with reqwest
reqwest does not add trace headers. Inject them from the current span:
reqwest = "0.13"
opentelemetry-http = "0.33"use opentelemetry::global;
use opentelemetry_http::HeaderInjector;
use reqwest::header::HeaderMap;
use tracing_opentelemetry::OpenTelemetrySpanExt;
/// traceparent, tracestate, and baggage for the current span.
fn trace_headers() -> HeaderMap {
let mut headers = HeaderMap::new();
let cx = tracing::Span::current().context();
global::get_text_map_propagator(|p| p.inject_context(&cx, &mut HeaderInjector(&mut headers)));
headers
}
#[tracing::instrument(
skip(client),
fields(otel.kind = "client", http.request.method = "GET", server.address = "inventory.internal")
)]
async fn fetch_stock(client: &reqwest::Client, sku: &str) -> reqwest::Result<String> {
client
.get(format!("https://inventory.internal/stock/{sku}"))
.headers(trace_headers())
.send()
.await?
.error_for_status()?
.text()
.await
}#[tracing::instrument] creates the client span, and trace_headers() runs inside it, so the downstream server span becomes its child. Without the attribute the headers carry the enclosing span, which still joins the trace.
To inject on every request of a client, use a reqwest-middleware 0.5 middleware (it needs the async-trait and http crates):
use reqwest_middleware::{ClientBuilder, ClientWithMiddleware, Middleware, Next};
struct Propagate;
#[async_trait::async_trait]
impl Middleware for Propagate {
async fn handle(
&self,
mut req: reqwest::Request,
extensions: &mut http::Extensions,
next: Next<'_>,
) -> reqwest_middleware::Result<reqwest::Response> {
let cx = tracing::Span::current().context();
global::get_text_map_propagator(|p| {
p.inject_context(&cx, &mut HeaderInjector(req.headers_mut()))
});
next.run(req, extensions).await
}
}
fn http_client() -> ClientWithMiddleware {
ClientBuilder::new(reqwest::Client::new()).with(Propagate).build()
}NOTE — reqwest-tracing
reqwest-tracing provides this middleware ready-made, with client spans. Its latest release (0.7.1) supports opentelemetry up to 0.32, so it cannot be used with the 0.33 setup on these pages yet. Check its feature list for an opentelemetry_0_33 feature before adopting it.
For gRPC, the tonic client layer in Framework Middleware injects the context.
Match the service namespace
Dashboards scope by service.namespace. The Browser SDK sends its project option as service.namespace; give the Rust service the same value in OTEL_RESOURCE_ATTRIBUTES, or its spans drop out of namespace-filtered views even when the traces join correctly.
Verifying
Test the server on its own first, with headers you made up:
curl -i https://api.example.com/users/7 \
-H "traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" \
-H "baggage: session.id=test-session-1"The server span in Sophonz should have trace ID 4bf92f3577b34da6a3ce929d0e0e4736, parent span ID 00f067aa0ba902b7, and session.id set to test-session-1. If it starts a new trace, the propagator is not set or the middleware does not extract. If curl works but browser requests start new traces, the browser did not send the header: check tracePropagationTargets and the preflight response.
For the preflight, send an OPTIONS request with Origin, Access-Control-Request-Method, and Access-Control-Request-Headers: traceparent,tracestate,baggage. The response must name all three in Access-Control-Allow-Headers.
Next steps
- Database Tracing — spans for the queries a request runs.
- Web Instrumentation — what the browser records for each request.