rust
68 lines · 8 steps
Propagating trace context in Axum extractors
A custom Axum extractor pulls W3C trace headers off incoming requests and forwards them onto outbound HTTP calls.
Explained by
highlit
1use axum::{
2 async_trait,
3 extract::FromRequestParts,
4 http::{header::HeaderValue, request::Parts, HeaderName},
5};
6use reqwest::Client;
7use serde::Deserialize;
8
9const TRACEPARENT: HeaderName = HeaderName::from_static("traceparent");
10const TRACESTATE: HeaderName = HeaderName::from_static("tracestate");
11
12#[derive(Clone, Debug)]
13pub struct TraceContext {
14 traceparent: HeaderValue,
15 tracestate: Option<HeaderValue>,
16}
17
18#[async_trait]
19impl<S> FromRequestParts<S> for TraceContext
20where
21 S: Send + Sync,
22{
23 type Rejection = std::convert::Infallible;
24
25 async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
26 let traceparent = parts
27 .headers
28 .get(TRACEPARENT)
29 .cloned()
30 .unwrap_or_else(|| HeaderValue::from_static("00-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-01"));
31
32 Ok(Self {
33 traceparent,
34 tracestate: parts.headers.get(TRACESTATE).cloned(),
35 })
36 }
37}
38
39impl TraceContext {
40 pub fn apply(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
41 let mut req = req.header(TRACEPARENT, self.traceparent.clone());
42 if let Some(state) = &self.tracestate {
43 req = req.header(TRACESTATE, state.clone());
44 }
45 req
46 }
47}
48
49#[derive(Deserialize)]
50pub struct Quote {
51 pub symbol: String,
52 pub price: f64,
53}
54
55pub async fn fetch_quote(
56 trace: TraceContext,
57 client: Client,
58 symbol: &str,
59) -> reqwest::Result<Quote> {
60 let request = client.get(format!("https://prices.internal/v1/quotes/{symbol}"));
61 trace
62 .apply(request)
63 .send()
64 .await?
65 .error_for_status()?
66 .json()
67 .await
68}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Implementing FromRequestParts turns any struct into an Axum handler argument extracted straight from the request.
- 2Using Infallible as the rejection type guarantees extraction always succeeds, so handlers never see an error path.
- 3Forwarding traceparent and tracestate onto outbound clients is what stitches services into a single distributed trace.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/propagating-trace-context-in-axum-extractors-explained-rust-4c97/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.