Skip to content
ImagineWorld

Instrumenting the Request Journey

node_idnode-book_mastering-distributed-observability-in-rust_chapter-04-instrumenting-the-request-journey
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num4
chapter_titleInstrumenting the Request Journey
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 4 — Instrumenting the Request Journey

Section titled “Chapter 4 — Instrumenting the Request Journey”

In Chapter 3, we saw how println! logging and manual correlation IDs leave us blind to timing and causality across service boundaries. They tell us what happened, but not where the time went.

This chapter bridges that gap. We will integrate OpenTelemetry into our Rust services to capture timing information at every service boundary. By the end, every HTTP request flowing through OtelMart, Products, Inventory, and Orders will automatically generate connected traces, complete with timing information, service boundaries, and causal relationships, without requiring manual propagation of correlation IDs.

We will build what we call the telemetry skeleton: the foundational infrastructure that makes every future observability feature possible. Just as a skeleton provides structure for muscles and organs, this telemetry foundation will support the metrics, logs, and alerts we add in later chapters. Without this skeleton, those features would collapse into disconnected data points: metrics that can’t explain spikes, logs that can’t link to requests.

In this chapter, we will cover the following key topics:

  • Understanding trace structure, propagation, and span hierarchy
  • Adding OpenTelemetry dependencies to Rust services
  • Initializing the telemetry pipeline and configuring exporters
  • Defining a consistent trace taxonomy for our services
  • Instrumenting HTTP boundaries and business logic
  • Propagating trace context across service boundaries
  • Visualizing end-to-end distributed traces in Jaeger

By the end of this chapter, you’ll be able to diagnose distributed failures in minutes instead of hours.

Before this chapter: “Checkout is slow.” -> Grep 4 log files -> Guess which service -> SSH into containers -> Calculate time deltas manually.

After this chapter: “Checkout is slow.” -> Open Jaeger -> Click trace -> See that inventory: db.query took 550ms (65% of total time).

The Transformation: Before and After OpenTelemetry

Section titled “The Transformation: Before and After OpenTelemetry”

Before diving into implementation, let’s clearly establish where we’re starting and where we’re going.

Our application consists of four Rust microservices:

ServiceDirectoryPortRole
OtelMartotelmart/4200API Gateway, proxies to backend services
Productsproducts/3001Product catalog management
Inventoryinventory/3002Stock levels and reservations
Ordersorders/3003Order processing

Table 4.1 – The four OpenTel E-Commerce services with their directories, ports, and roles

In Chapter 3, our services used println! for logging with no structured telemetry. Here’s what we’re transforming:

Problems with the Chapter 3 approach:

  • println! output disappears into container logs with no structure
  • No timing information: we can’t see how long operations take
  • No trace context: requests across services are disconnected
  • Debugging requires grepping multiple log files manually

The transformation touches three areas: startup initialization, middleware attachment, and handler instrumentation. Here’s how we’ll transform the Products service. Notice the inline ← NEW and ← CHANGED markers showing what’s different:

Before reading the code, focus on these three concrete changes:

  • Startup initialization: call init_telemetry("products") before router startup so every request is traceable from the first packet.
  • Middleware attachment: add OtelAxumLayer and OtelInResponseLayer so incoming requests create HTTP spans and propagate context automatically.
  • Handler instrumentation: use #[instrument] on business handlers so domain operations appear as named child spans under each HTTP request.

products/src/main.rs:

use axum::{routing::get, Router};
use tokio::net::TcpListener; // ← NEW
use axum_tracing_opentelemetry::middleware::{ // ← NEW
OtelAxumLayer, OtelInResponseLayer,
};
mod telemetry; // ← NEW: Telemetry module
#[tokio::main]
async fn main() {
let tracer_provider = telemetry::init_telemetry("products"); // ← NEW: Initialize first
let config = Config::load().expect("Failed to load config");
let pool = db::create_pool(&config.database.url).await;
let state = AppState { pool, config };
let app = Router::new()
.route("/products", get(handlers::list_products))
.route("/products/{id}", get(handlers::get_product_by_id))
.with_state(state)
.layer(OtelInResponseLayer::default()) // ← NEW: Trace context in response headers
.layer(OtelAxumLayer::default()) // ← NEW: Automatic HTTP spans + context extraction
.layer(CorsLayer::permissive());
let listener = TcpListener::bind("0.0.0.0:3001").await.unwrap();
tracing::info!(port = 3001, "Products service listening"); // ← CHANGED: println! → tracing::info!
axum::serve(listener, app).await.unwrap();
// Note: axum::serve blocks until the server shuts down, so this line
// only runs on graceful shutdown (e.g., via Ctrl+C signal handling).
// In production, use tokio::signal to trigger shutdown and flush spans.
telemetry::shutdown_telemetry(tracer_provider); // ← NEW: Graceful shutdown
}

products/src/handlers/products.rs:

use tracing::instrument; // ← NEW
#[instrument( // ← NEW: Automatic span creation
name = "get_product_by_id",
skip(state), // Don't log the entire AppState (too verbose)
fields(product.uuid = %uuid) // Attach product UUID as span attribute
)]
pub async fn get_product_by_id(
State(state): State<AppState>,
Path(uuid): Path<Uuid>,
) -> Result<Json<ProductDetail>, Response> {
tracing::info!("Fetching product"); // ← CHANGED: Structured, attached to span
let product = db::products::get_product_by_uuid(&state.pool,uuid).await?;
Ok(Json(product))
}

New infrastructure added:

ComponentPurpose
telemetry.rsInitializes OpenTelemetry pipeline, exports to Jaeger
OtelAxumLayerAutomatic spans for all incoming HTTP requests
reqwest‑tracingAutomatic spans and context injection for outgoing HTTP calls
#[instrument]Manual spans for business logic with attributes
Jaeger containerCollects and visualizes distributed traces
traceparent propagationLinks spans across service boundaries

Table 4.2 – New infrastructure introduced in Chapter 4 and what each component provides

After Chapter 4, we can:

  • See all requests in a unified Jaeger UI
  • View timing breakdowns across all four services
  • Click a trace to see exactly where time was spent
  • Correlate logs with their originating spans

Before we implement this pattern across all services, we need to understand the concepts that make this possible. Section 4.2 explains how traces, spans, and context propagation work under the hood.

Chapter 1 introduced us to the three pillars of observability and how OpenTelemetry unifies them. In Chapter 3, we discussed the need for distributed tracing, specifically how correlation IDs help link logs but miss out on timing and causality details.

Now, we move on to translating these concepts into working Rust code. This section connects practical implementation. We will examine how span hierarchies are formed, how identities move across service boundaries, and how Rust’s tracing ecosystem fits in with OpenTelemetry.

In Chapter 1, we talked about a trace being a request’s journey through the system. Now, let’s look at the technical side: a trace is a tree of span s linked by a common TraceID (that’s a 128-bit identifier, displayed as 32 hex characters). Every span carries its own SpanID, which creates the tree hierarchy. This link is exactly what allows Jaeger to show us the waterfall view.

Consider what happens when a user clicks “Buy” in OpenTel E-Commerce:

Figure 4.1 – A four-service distributed trace tree linked by a single TraceID, with ParentID references forming the hierarchy

Figure 4.1 – A four-service distributed trace tree linked by a single TraceID, with ParentID references forming the hierarchy

All four spans share the same TraceID (4bf92f…). The ParentID linkages create the hierarchy: Gateway spawned Orders, which spawned both Products and > Inventory calls. When you view this in Jaeger or another tracing UI, you’ll see this tree rendered as a waterfall diagram with timing bars.

This structure answers questions that logs alone cannot:

  • Which service is called which? Follow the ParentID chain.
  • Where did time go? Compare span durations.
  • What ran in parallel vs. sequentially? Spans C and D share the same parent and overlapping timestamps; they ran concurrently.

In Chapter 1, we established that spans share a TraceID, which flows through HTTP headers via the W3C traceparent format. But what, exactly, is being propagated?

Why not send the entire span? Spans contain internal execution details (logs, database queries, and timing) that are irrelevant to downstream services. The receiving service only needs to know which trace it belongs to and who its immediate parent is if any, not what happened before it was called.

SpanContext is an immutable object that contains the state which must propagate to child spans and across process boundaries in a distributed trace. It acts as a unique identifier for a span within a trace, conforming to the W3C TraceContext specification. It contains:

  • TraceID (128-bit): It globally identifies the trace and stays the same as the request travels from your Frontend (Rust/Axum) to other services, through a database, and into an external API. It is the “glue” that allows a tracing backend (such as Jaeger or Honeycomb) to group all segments.
  • SpanID (64-bit): Identifies a single operation within a trace (e.g., an HTTP call). While immutable, this ID propagates downstream to become the Parent SpanID for subsequent operations, linking them into the trace hierarchy (parent SpanID -> identifies who called it and is optional for the root span).
  • TraceFlags (8-bit): Contains sampling decisions. While the TraceID and SpanID identify where the data belongs, the TraceFlag tells the system how to handle that data. For example, you can use it to decide whether to sample the trace or not.
  • TraceState (optional): carries vendor specific or application specific metadata across service boundaries. For example, you can use it to carry information about the user’s tenant ID or any other context that needs to be preserved across service calls.
  • IsRemote: a boolean indicating whether the SpanContext was received from somewhere else or locally generated.

When the Orders Service calls the Inventory Service, it only sends the SpanContext, packaged (serialized) into HTTP headers:

figure 4.2

Figure 4.2 – The W3C traceparent header broken down into version, trace ID, parent span ID, and trace flags

ComponentBit ValueMeaning
Sampled0x01Record and export this trace.
Sampled bit unset0x00Sampled bit (0x01) is not set; implementations typically do not export.
Random0x02Trace ID was generated randomly (defined in W3C Trace Context Level 2).
Reserved0x04 to 0xFFReserved for future use.

Table 4.3 – TraceFlags bit values defined by the W3C Trace Context specification

The Inventory Service extracts this header, creates a new span with its own SpanID, and sets the extracted SpanID as the Parent SpanID. This parent-child linkage is what creates the hierarchical trace visualization you see in Jaeger.

This is precisely what our manual X‑Correlation‑ID header was doing in Chapter 3, but OpenTelemetry standardizes the format, automates the serialization, and handles edge cases like missing headers or malformed values.

Chapter 1 covered the core span fields: name, timestamps, duration, status, and attributes. OpenTelemetry spans include one additional concept worth understanding before we instrument our services: events.

Events are timestamped annotations within a span. Unlike attributes (which describe the span as a whole), events mark specific moments during execution:

span.add_event("cache_miss", vec![KeyValue::new("key", "product:123")]);
// ... fetch from database ...
span.add_event("cache_populated", vec![]);

Events are especially useful for recording retries, state transitions, or checkpoints within long-running operations. In our saga pattern from Chapter 3, events could mark each compensation step during rollback, creating a clear audit trail of the failure recovery process.

// In the Orders service saga compensation
span.add_event("saga.compensation_started", vec![]);
release_inventory_reservation(&state,&reserved_items).await?;
span.add_event("saga.inventory_released", vec![
KeyValue::new("items_count", reserved_items.len() as i64)
]);

When debugging a failed checkout in Jaeger, you’d see these events as markers on the timeline, showing exactly when and why the saga rolled back.

The tree structure shows relationships, but traces also capture timing. Here’s the same checkout flow as a waterfall, the visualization that reveals bottlenecks:

figure 4.3

Figure 4.3 – Waterfall view of the checkout showing the Inventory call consuming 80 percent of total request time

The waterfall immediately shows that Inventory consumed 2 seconds (80% of the total request time). Notice that Products (200ms) and Inventory (2000ms) overlap in time; they’re concurrent HTTP calls from the Orders service. The Orders span’s 2350ms duration includes both calls plus their own processing overhead.

In a tracing UI like Jaeger, you’d also see events within that span marking when locks were acquired and released, revealing that the span spent almost its entire duration holding a database lock. This is the visibility that Chapter 3 ‘s println! logging could never provide.

Before instrumenting code, it’s important to understand the lifecycle of a span object. This knowledge is crucial because certain operations (such as setting a parent) are only valid during specific phases of its life cycle.

The Three Execution States:

  1. Created: The span object exists but has not started (is not active).
  2. Entered: The span is active, measuring time and recording events.
  3. Exited: The span is closed, the timer stops, and it is ready for export.
use tracing::{span, Level};
// State 1: CREATED - span exists but is not active
let span = span!(Level::INFO, "my_operation");
{
// State 2: ENTERED - span becomes active
let _guard = span.enter();
// Any events or child spans created here will be linked to this span
} // _guard dropped here
// State 3: EXITED - span is closed and will be exported

When the _guard is dropped, the span is no longer “current” or “active”. It is removed from the thread’s current-span stack, and new child spans will not automatically attach to it. However, the span’s duration is not paused; it runs continuously from span creation until the span itself is dropped (ended). When the span variable is dropped, the span is marked as complete, the SDK calculates the final span state and sends the data to the exporter (e.g., Jaeger).

Why Parent-Child Timing Matters

Once a span is entered (made active), its parent relationship is immutable. You cannot change a span’s parent after it has been entered. This is why OtelAxumLayer handles context extraction internally; it sets the parent relationship during span creation, before the span is entered.

use tracing_opentelemetry::OpenTelemetrySpanExt;
// ❌ WRONG: Trying to set parent after entering
let span = span!(Level::INFO, "request");
let _enter = span.enter(); // Span is now active
span.set_parent(parent_context); // ⚠️ TOO LATE - parent is already set!
// ✅ CORRECT: Set parent before entering
let span = span!(Level::INFO, "request");
span.set_parent(parent_context); // ✅ Parent set while span is created
let _enter = span.enter(); // Now enter with correct parent

This is precisely why OtelAxumLayer handles context extraction internally (discussed in section 4.7) it creates the span with the correct parent relationship before entering it.

Automatic Lifecycle Management with #[instrument]:

The #[instrument] macro handles the entire lifecycle automatically. This solves the common issue where developers forget to explicitly link the parent span, which results in broken or disconnected traces.

#[instrument]
async fn my_function() {
// Span is created and entered at function start
// Span stays active across .await points
// Span exits when function returns (even on error)
}

For synchronous functions, this is equivalent to:

fn my_function() {
let span = tracing::span!(tracing::Level::INFO, "my_function");
let _enter = span.enter();
// ... function body ...
// Span exits when _enter is dropped
}

For async functions, the expansion is fundamentally different. The macro wraps the function of the body’s future with tracing::Instrument, which enters the span on each poll() and exits it when the poll completes. This is runtime-agnostic (works with Tokio, async-std, etc.) and ensures the span is active only while the future is being polled, preventing it from leaking into other tasks between await points. We’ll see why this matters in section 4.6.

Use #[instrument] for almost all cases. Manual span creation is only needed when you need fine-grained control over span timing or when working with non-async code that has complex control flow.

We’ve covered what spans are, how they link together, and when they are active. But implementing all this manual logic (context propagation, state management, serialization) is error-prone. This is where OpenTelemetry comes in.

How OpenTelemetry Fits into the Rust Ecosystem

Section titled “How OpenTelemetry Fits into the Rust Ecosystem”

Rust’s observability ecosystem centers on the tracing crate, which provides structured diagnostics with span support. If you’ve written #[tracing::instrument] or info!() in Rust, you’ve already used tracing.

However, tracing alone doesn’t export data to external systems. It’s a facade that defines how to create spans and events, but not where they go. This is where OpenTelemetry enters.

The tracing‑opentelemetry crate bridges these worlds:

figure 4.4

Figure 4.4 – The four-layer pipeline from application tracing macros through tracing-opentelemetry, the OpenTelemetry SDK, and the OTLP exporter

This layered approach means you write idiomatic Rust code using tracing ‘s macros, and OpenTelemetry handles the export. You get the ergonomics of Rust’s ecosystem with the interoperability of OpenTelemetry’s vendor-neutral protocol.

There are two valid approaches to instrumenting Rust services with OpenTelemetry. The first, which we use throughout this chapter, is the tracing + tracing‑opentelemetry bridge. It gives you macro ergonomics (#[instrument], tracing::info!) and seamless integration with the broader Rust ecosystem. The second is using the OpenTelemetry API directly:

use opentelemetry::{global, trace::Tracer};
let tracer = global::tracer("products");
tracer.in_span("validate_product", |cx| {
// Business logic here
});

The native OpenTelemetry API gives you direct access to SpanKind, Link s, SpanContext, and full spec compliance without a bridge layer. However, the Rust OpenTelemetry API is still stabilizing; the tracing bridge and core SDK are production-ready, but the direct API surface continues to evolve across releases (see the opentelemetry-rust roadmap https://github.com/open-telemetry/opentelemetry-rust/issues). For that reason, we don’t dive deep into the native API in this book. The tracing approach provides mature macro ergonomics and broad ecosystem integration, making it the pragmatic choice today. The community supports both, and as the native API matures, it will become an increasingly attractive option for teams that want full spec compliance without a bridge layer.

In the next section, we’ll add these crates to our services and see this pipeline in action.

Adding the tracing and OpenTelemetry Crates

Section titled “Adding the tracing and OpenTelemetry Crates”

The Rust OpenTelemetry ecosystem is modular by design, you compose the exact capabilities you need from specialized crates. This section walks through each dependency, explaining not just what it does, but why the ecosystem is structured this way and where you’ll use it in your application code.

Add the following to each service’s Cargo.toml (Products, Inventory, Orders, and OtelMart):

The versions shown are current as of writing this book. For the latest compatible versions, check the opentelemetry-rust releases https://github.com/open-telemetry/opentelemetry-rust/releases.

[dependencies]
# Core tracing ecosystem
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
# OpenTelemetry core
opentelemetry = "0.31"
opentelemetry_sdk = "0.31"
# OTLP exporter (sends traces to collectors/backends)
opentelemetry-otlp = { version = "0.31", features = ["grpc-tonic"] }
# Bridge between tracing and OpenTelemetry
tracing-opentelemetry = "0.32"
# HTTP instrumentation (server + client)
axum-tracing-opentelemetry = "0.33.0"
reqwest-middleware = { version = "0.5", features = ["json"] }
reqwest-tracing = { version = "0.7.0", features = ["opentelemetry_0_31"] }

Let’s understand what each crate provides, organized by how we’ll use it in the application:

tracing: Is the crate for daily use in the handlers and business logic? Every #[instrument] macro, every info!() call, every span! uses this crate, it’s the only observability API you’ll directly interact with in handlers/, db/, and business logic modules.

// This is tracing in action - in your handlers
#[instrument(skip(state))]
pub async fn get_product_by_id(...) {
info!("Fetching product"); // ← tracing macro
}

tracing‑subscriber: Lives in main.rs or telemetry.rs initialization code. Configure it once at startup to control what gets logged (env‑filter for RUST_LOG) and how it’s formatted (json feature for structured output). After initialization, it runs in the background collecting spans.

// In telemetry.rs - configure once, forget
let env_filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("info,otel::tracing=trace"));

tracing‑opentelemetry: Is the invisible bridge between tracing and OpenTelemetry. Configure it once in telemetry.rs as a subscriber layer; it then automatically converts every #[instrument] span into an OpenTelemetry span, intercepting tracing spans behind the scenes.

// In telemetry.rs - set up once
let otel_layer = tracing_opentelemetry::layer().with_tracer(tracer);
tracing_subscriber::registry()
.with(otel_layer) // ← Intercepts all tracing spans
.init();

Version note: This crate is maintained by the Tokio team (not the OpenTelemetry project), so version compatibility matters, always check the compatibility matrix https://github.com/tokio-rs/tracing-opentelemetry/blob/main/CHANGELOG.md when upgrading.

axum‑tracing‑opentelemetry: Provides OtelAxumLayer and OtelInResponseLayer middleware for Axum. Drop these two layers onto your router, and every incoming HTTP request gets a span with proper OpenTelemetry semantic convention attributes (http.request.method, http.route, http.response.status_code, url.path). It also extracts the W3C traceparent header from incoming requests and sets the parent context automatically, no custom MakeSpan implementation needed.

// In main.rs - two lines on your router
use axum_tracing_opentelemetry::middleware::{OtelAxumLayer, OtelInResponseLayer};
let app = Router::new()
.route("/products", get(handlers::list_products))
.layer(OtelInResponseLayer::default()) // Adds trace context to response headers
.layer(OtelAxumLayer::default()) // Creates server span + extracts parent context
.layer(CorsLayer::permissive());

OtelAxumLayer creates its spans at the TRACE level, targeting otel::tracing. This means your EnvFilter must allow otel::tracing=trace through, or every request will produce a SpanDisabled warning. We’ll configure this correctly in section 4.4.

reqwest‑middleware and reqwest‑tracing: Are the client-side counterparts. Wrap your reqwest::Client in a ClientWithMiddleware and add TracingMiddleware. Every outgoing HTTP request gets a client span, and the traceparent header is injected automatically; no manual header manipulation is required.

// In main.rs - wrap your HTTP client once
let reqwest_client = reqwest::Client::builder().build()?;
let http_client = reqwest_middleware::ClientBuilder::new(reqwest_client)
.with(reqwest_tracing::TracingMiddleware::<reqwest_tracing::SpanBackendWithUrl>::new())
.build();
// Then use http_client.get(...), http_client.post(...) as normal

The opentelemetry_0_31 feature flag on reqwest‑tracing ensures version compatibility with our OpenTelemetry stack. The json feature on reqwest‑middleware re-exports reqwest’s JSON support through the middleware wrapper.

opentelemetry: The API traits defining what a tracer, span, and context are. Rarely imported directly, mostly used by opentelemetry_sdk and tracing‑opentelemetry. The main place it appears in is the trace context propagation (global::get_text_map_propagator).

opentelemetry_sdk: Where the TracerProvider is built in telemetry.rs. This is configuration-heavy code written once, setting up the exporter, defining the resource (service name), and configuring sampling. After init_telemetry() runs, the SDK batches and exports spans in the background using a dedicated thread.

// In telemetry.rs - configuration code
let provider = SdkTracerProvider::builder()
.with_batch_exporter(exporter)
.with_resource(Resource::builder_empty()
.with_service_name("products")
.build())
.build();

opentelemetry‑otlp: Creates the exporter in telemetry.rs, literally 5 lines that configure where spans go (Jaeger, Collector) and how they’re sent (gRPC vs HTTP). OTLP is the standard wire format for OpenTelemetry, supported by virtually all backends:

  • gRPC (via grpc‑tonic feature): HTTP/2 with Protocol Buffers, better performance for high-volume telemetry.
  • HTTP/Protobuf (via http‑proto feature): HTTP/1.1, simpler for environments where gRPC is blocked.
// In telemetry.rs - exporter setup
let exporter = opentelemetry_otlp::SpanExporter::builder()
.with_tonic() // ← gRPC transport
.with_endpoint(&otlp_endpoint)
.build()?;

OpenTelemetry crates are modular by default. Instead of compiling every possible exporter (HTTP, gRPC, Zipkin, etc.), we must opt in to the specific features we need. This keeps our building times fast and our binary size small.

The grpc‑tonic feature on opentelemetry‑otlp enables gRPC transport using the Tonic library.

IMPORTANT

When using grpc‑tonic, the OTLP exporter must be created from within a Tokio runtime context. Since our Axum services already run on Tokio, this requirement is satisfied. If you’re using a different async runtime (e.g., async-std), you’ll need the HTTP transport instead.

If your infrastructure doesn’t support gRPC, you can use HTTP transport instead, like below:

# Alternative: HTTP transport instead of gRPC
opentelemetry-otlp = { version = "0.31", features = ["http-proto", "reqwest-client"] }

OpenTelemetry crates follow a coordinated versioning scheme. The versions listed above (0.31 for opentelemetry/sdk/otlp/http, 0.32 for tracing-opentelemetry) are compatible with each other. Mixing mismatched versions can cause subtle runtime errors where spans fail to connect or exports silently fail.

For example, tracing‑opentelemetry 0.32 is compatible with opentelemetry 0.31, but tracing‑opentelemetry 0.25 expects opentelemetry 0.24. Mixing 0.32 with 0.24 will compile but fail at runtime with cryptic errors like “span context not found.”

When upgrading, always upgrade the entire OpenTelemetry stack together. Check the opentelemetry-rust changelog https://github.com/open-telemetry/opentelemetry-rust/blob/main/CHANGELOG.md for version compatibility matrices, and the tracing-opentelemetry changelog https://github.com/tokio-rs/tracing-opentelemetry/blob/main/CHANGELOG.md for bridge compatibility.

With dependencies in place, the OpenTelemetry tracing pipeline must be initialized once at application startup, before any requests are handled. If this step is missed or misconfigured, spans may silently fail to export or worse, trigger a runtime panic when the first span is created without a registered subscriber.

The initialization involves three components: a Resource (metadata about your service), an Exporter (where to send traces), and a TracerProvider (manages span creation and export). We’ll build these step by step, then see the complete module.

Every span exported from your service carries metadata identifying its origin. This is the Resource:

telemetry.rs
// 1. Create the Resource (app metadata)
let resource = Resource::builder_empty()
.with_service_name(service_name.to_string())
.build();

A Resource describes the entity producing telemetry. When viewing traces in Jaeger, spans are grouped by service.name - this is how you distinguish Products service spans from Inventory service spans.

The service.name is required and should match your service’s identity (e.g., “products”, “inventory”, “orders”, “otelmart”). For a more sophisticated setup, you would also add standard attributes following OpenTelemetry’s semantic conventions https://opentelemetry.io/docs/concepts/semantic-conventions/:

use opentelemetry::KeyValue;
let provider = SdkTracerProvider::builder()
.with_batch_exporter(exporter)
.with_resource(
Resource::builder_empty()
.with_service_name("products") // required
// additional attributes (optional)
.with_attribute(KeyValue::new("service.version", "1.0.0"))
.with_attribute(KeyValue::new("service.namespace", "opentel-ecommerce"))
.with_attribute(KeyValue::new("deployment.environment.name", "production"))
.build(),
)
.build();

Resource vs. Span Attributes:

Understanding when to use Resource vs. span attributes is crucial for effective instrumentation:

AspectResourceSpan Attributes
ScopeService level (all spans)Span level (individual operations)
Examplesservice.name, service.version, host.namehttp.method, db.query.text, user.id
CardinalityLow (same for all spans)High (varies per operation)
When to useMetadata that identifies the serviceMetadata specific to an operation
Set onceAt initializationPer span during execution

Table 4.4 – Resource attributes versus span attributes by scope, cardinality, and lifecycle

Example:

// ✅ Resource: Service-level metadata (set once at startup)
Resource::builder_empty()
.with_service_name("products") // Same for all spans
.with_attribute(KeyValue::new("deployment.environment.name", "prod")) // Same for all spans
.build()
// ✅ Span Attributes: Operation-level metadata (varies per span)
#[instrument(fields(
product.id = %product_id, // Different for each request
user.id = %user_id, // Different for each request
http.method = "GET" // Specific to this operation
))]
async fn get_product(product_id: Uuid, user_id: Uuid) { ... }

Using Resource correctly reduces data volume (no need to repeat service.name on every span) and enables better filtering in observability backends.

The exporter sends completed spans to an external system. We use OTLP (OpenTelemetry Protocol) over gRPC:

telemetry.rs
let otlp_endpoint = std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT")
.unwrap_or_else(|_| "http://localhost:4317".to_string()); // where the collector is running and configured to receive data
let exporter = opentelemetry_otlp::SpanExporter::builder()
.with_tonic()
.with_endpoint(&otlp_endpoint) // the endpoint to send spans to
.build()
.expect("Failed to create OTLP exporter");

Port 4317 is the standard OTLP gRPC port. The OTEL_EXPORTER_OTLP_ENDPOINT environment variable follows OpenTelemetry’s environment variable specification https://opentelemetry.io/docs/concepts/sdk-configuration/otlp-exporter-configuration/, allowing operators to configure the export destination without rebuilding the application.

In our Docker Compose setup, this endpoint will point to the OpenTelemetry Collector or directly to Jaeger. For local development without a collector, Jaeger’s all-in-one image accepts OTLP on port 4317.

WARNING

The code uses .expect() for simplicity, which will panic if the exporter fails to initialize (e.g., due to an invalid endpoint URL). In production, consider using? and propagating the error to main(), or logging a warning and falling back to a no-op tracer.

The SdkTracerProvider is the central configuration point. It creates Tracer instances, which create spans:

telemetry.rs
let provider = SdkTracerProvider::builder()
.with_batch_exporter(exporter)
.with_resource(resource)
.build();

Key configuration options:

Sampler: Determines which traces are recorded. By default, the SDK uses Sampler::ParentBased(Box::new(Sampler::AlwaysOn)), which records every trace appropriate for development and low-traffic services. In high traffic production, configure a ratio-based sampler to reduce storage costs:

telemetry.rs
let provider = SdkTracerProvider::builder()
.with_sampler(Sampler::TraceIdRatioBased(0.1)) // 10% sampling
.with_id_generator(RandomIdGenerator::default()) // optional, default is RandomIdGenerator
.with_batch_exporter(exporter)
.with_resource(resource)
.build();

A ratio-based sampler is a probabilistic head-sampling strategy that decides whether to sample a trace based on a fixed percentage (0.0 to 1.0).

IdGenerator: Creates TraceIDs and SpanIDs. RandomIdGenerator (the default) produces cryptographically random IDs, ensuring uniqueness across distributed services. Alternative generators exist for specific use cases (e.g., AWS X-Ray compatible IDs).

BatchExporter: Spans are buffered and sent in batches rather than individually. This significantly reduces network overhead. The SDK’s default batch configuration (512 spans per batch, 5-second intervals) works well for most applications.

Step 4: Connecting to the tracing Ecosystem

Section titled “Step 4: Connecting to the tracing Ecosystem”

This is where tracing and OpenTelemetry meet:

telemetry.rs
// Create a tracer from the provider for the OpenTelemetry layer
let tracer = provider.tracer(service_name.to_string());
// Create the OpenTelemetry tracing layer
let otel_layer = tracing_opentelemetry::layer().with_tracer(tracer);
// Create an environment filter for log levels
// The otel::tracing=trace directive allows axum-tracing-opentelemetry's
// spans through (they're emitted at TRACE level with target "otel::tracing")
let env_filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("info,otel::tracing=trace"));
// Create a formatting layer for console output
let fmt_layer = tracing_subscriber::fmt::layer()
.with_target(true)
.with_thread_ids(false)
.compact();
// Combine all layers into a subscriber and set it as the global default
tracing_subscriber::registry()
.with(env_filter)
.with(fmt_layer)
.with(otel_layer)
.init();

The tracing_opentelemetry::layer() creates a subscriber layer that:

  1. Intercepts spans created by tracing (via #[instrument] or manual span! macros)
  2. Converts them to OpenTelemetry spans
  3. Exports them through the configured TracerProvider

We stack multiple layers in the subscriber:

  • env_filter: Controls which spans/events are processed based on RUST_LOG
  • fmt_layer: Prints to stdout for local debugging
  • otel_layer: Exports to OpenTelemetry (via tracing‑opentelemetry)

With this setup, a single #[tracing::instrument] annotation simultaneously logs to console and exports to your observability backend.

The shutdown function is critical it flushes any buffered spans before the application exits:

telemetry.rs
pub fn shutdown_telemetry(provider: SdkTracerProvider) {
if let Err(e) = provider.shutdown() {
eprintln!("Failed to shutdown tracer provider: {e}");
}
}

Without calling shutdown_telemetry, spans created in the last few seconds before shutdown may be lost. The provider.shutdown() call blocks until all pending exports complete or a timeout is reached.

Here’s the complete implementation, combining all the pieces above. Create this file at src/telemetry.rs in each service:

📁 Repository Reference: This code is available at code/chapter_4/products/src/telemetry.rs (and is identical in orders, inventory, and otelmart). You can copy it directly or type it out to reinforce understanding.

Here are the key parts of the implementation:

telemetry.rs
pub fn init_telemetry(service_name: &str) -> SdkTracerProvider {
// 1. Set up W3C Trace Context propagator for cross-service correlation
global::set_text_map_propagator(TraceContextPropagator::new());
// 2. Create OTLP exporter (sends traces to Jaeger via gRPC)
let otlp_endpoint = std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT")
.unwrap_or_else(|_| "http://localhost:4317".to_string());
let exporter = opentelemetry_otlp::SpanExporter::builder()
.with_tonic()
.with_endpoint(&otlp_endpoint)
.build()
.expect("Failed to create OTLP exporter");
// 3. Build tracer provider with service resource
let provider = SdkTracerProvider::builder()
.with_batch_exporter(exporter)
.with_id_generator(RandomIdGenerator::default())
.with_resource(
Resource::builder_empty()
.with_service_name(service_name.to_string())
.build(),
)
.build();
// 4. Create layered subscriber (console + OpenTelemetry)
let tracer = provider.tracer(service_name.to_string());
let otel_layer = tracing_opentelemetry::layer().with_tracer(tracer);
// Include otel::tracing=trace to allow axum-tracing-opentelemetry spans through.
// Without this directive, OtelAxumLayer's spans (emitted at TRACE level with
// the target "otel::tracing") would be filtered out, producing SpanDisabled warnings.
let env_filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("info,otel::tracing=trace"));
let fmt_layer = tracing_subscriber::fmt::layer()
.with_target(true)
.with_thread_ids(false)
.compact();
tracing_subscriber::registry()
.with(env_filter)
.with(fmt_layer)
.with(otel_layer)
.init();
provider
}
pub fn shutdown_telemetry(provider: SdkTracerProvider) {
if let Err(e) = provider.shutdown() {
eprintln!("Failed to shutdown tracer provider: {e}");
}
}

💡 Key Concepts:

Propagator (line 7): Enables W3C Trace Context format for cross-service traces

Batch Exporter (line 23): Buffers spans and sends them in batches for efficiency

Resource (line 25): Service-level metadata attached to all spans

Layered Subscriber (line 32): Combines console logging with OpenTelemetry export

In the service’s main.rs, add the module declaration and call init_telemetry. We pass the specific name of the service (e.g., "products"), which flows into the Resource configuration we defined in telemetry.rs:

mod telemetry; // ← Declare the module
#[tokio::main]
async fn main() {
// Initialize telemetry first, before any spans are created
let tracer_provider = telemetry::init_telemetry("products");
// ... build your Axum app, database connections, etc. ...
let listener = tokio::net::TcpListener::bind("0.0.0.0:3001").await.unwrap();
tracing::info!(port = 3001, "Products service listening");
axum::serve(listener, app).await.unwrap();
// Gracefully shut down telemetry, flushing any pending spans
telemetry::shutdown_telemetry(tracer_provider);
}

The initialization order matters: call init_telemetry before creating any spans (including those from #[instrument] macros in your route handlers). The shutdown call ensures buffered spans are exported before the process exits.

With the telemetry pipeline initialized, every #[instrument] macro will now create spans that flow through this infrastructure. The next section establishes a trace taxonomy: naming conventions and semantic attributes that make your traces searchable and meaningful.

Trace Taxonomy: Naming Conventions & Semantic Attributes

Section titled “Trace Taxonomy: Naming Conventions & Semantic Attributes”

A trace is only as useful as its span names and attributes. Imagine debugging a production outage: you search for “all order creation failures” but find nothing because each service named its spans differently (create_order, new_order, order.create). Or you try to filter by customer email, but half the services use customer.email and half use user_email. This is the chaos that trace taxonomy (a strict naming convention) prevents.

This section establishes a systematic approach to naming and annotating spans, ensuring your traces are searchable, aggregatable, and consistent across services.

OpenTelemetry} defines five span kinds via the SpanKind enum, each serving a distinct role:

SpanKindPurposeExample in OpenTel E-Commerce
SpanKind::ServerHandles incoming requestsPOST /orders received by Orders Service
SpanKind::ClientRepresents outbound callsHTTP GET products‑service/products/123
SpanKind::InternalIn-process work with no network I/Ovalidate_order, calculate_total
SpanKind::ProducerPublishing a message to a queuekafka.send orders‑topic
SpanKind::ConsumerReceiving a message from a queuekafka.receive orders‑topic

Table 4.5 – The five OpenTelemetry SpanKind values with examples from OpenTel E-Commerce

Why SpanKind Matters:

SpanKind isn’t just metadata, it has practical implications for trace analysis:

  1. Service Maps: Observability backends use SpanKind to build service dependency graphs:
    • CLIENT → SERVER pairs show service-to-service communication
      • PRODUCER → CONSUMER pairs show async messaging flows
  2. CLIENT/SERVER Pairing: For synchronous calls, you typically see: Generated ASCII Image
  3. The CLIENT span in Orders and the SERVER span in Products are linked by trace context.
  4. Latency Attribution:
    • CLIENT span duration = network + server processing
      • SERVER span duration = just server processing
      • Difference reveals network latency
  5. Boundary Detection: INTERNAL spans never cross process boundaries. If you see an INTERNAL span with a parent in a different service, something is wrong with context propagation.

Example: Choosing the Right SpanKind

// ✅ CORRECT: CLIENT span for outgoing HTTP call
#[instrument(
name = "HTTP GET products-service/products",
skip(client),
fields(otel.kind = "client") // Marks this as a client span
)]
async fn fetch_product(client:&reqwest::Client,id:Uuid)-> Result<Product> {
// ... HTTP call to products service ...
}
// ✅ CORRECT: INTERNAL span for business logic
#[instrument(skip(state))] // Defaults to INTERNAL
async fn calculate_order_total(state:&AppState,items:&[Item])-> Decimal {
// ... local computation, no external calls ...
}

When viewing traces in Jaeger, SpanKind determines the span’s color and icon, making it possible to distinguish between local processing and external calls at a glance.

When to use each SpanKind:

  • Server: Automatically set by HTTP middleware for incoming requests
  • Client: Automatically set by HTTP client middleware for outgoing calls
  • Client: Also used for outbound calls to databases, caches, and other backends — set otel.kind = "client" on #[instrument] spans wrapping SQLx, Redis, or gRPC client calls
  • Internal: Explicitly set for business logic or any in-process work that does not cross a process boundary
  • Producer/Consumer: For message queue operations (not covered in this chapter)

When using tracing with tracing‑opentelemetry, span kinds are typically inferred:

  • Server spans: Automatically set by OtelAxumLayer for incoming HTTP requests
  • Client spans: Automatically set by reqwest‑tracing middleware for outgoing HTTP calls
  • Internal spans: The default for #[instrument] macros

You can explicitly set the span kind using OpenTelemetry attributes:

#[instrument(
skip(state),
fields(otel.kind = "internal") // Explicit internal span
)]
async fn validate_order(state:&AppState,order:&Order)-> Result<()> {
// Business logic
}

For OpenTel E-Commerce’s synchronous HTTP architecture, we primarily use Server, Client, and Internal spans. Producer and Consumer become relevant when adding message queues.

Well formed traces follow these rules:

  1. One root span per trace: The entry point (typically an HTTP server span set by otelmart) has no parent
  2. Client spans are children of their initiator: When Orders calls Inventory, the client span is a child of the Orders handler span
  3. Internal spans nest within their service: validate_order is a child of the server span, not a sibling
  4. No orphaned spans: Every span except the root must have a valid parent

Here’s what a well-formed trace looks like:

Generated ASCII Image

Figure 4.5 – A well-formed trace hierarchy with root, server, client, and internal spans across the four services

Notice:

  • One root (Gateway Server span set by otelmart)
  • Client spans are children of their initiator
  • Server spans in downstream services are children of Client spans (via propagation)
  • Internal spans nest within their service

Violating these rules produces flat, disconnected traces that cannot answer “what called what?”

Cardinality refers to the number of unique values. A low cardinality field has few distinct values (e.g., HTTP methods: GET, POST, PUT). A high cardinality field has many unique values (e.g., UUIDs, timestamps).

Span names should be low-cardinality and operation-centric, not instance-centric.

Bad: High cardinality names

// DON'T: Includes variable data in span name
#[tracing::instrument(name = "get_product_a7f3c5")] // instance centric name!
async fn get_product(id: Uuid) -> Product { ... }

This creates a unique span name for every product. You can’t search for “all product fetches” because each has a different name.

Good: Operation-centric names

// DO: Static operation name, variables as attributes (\`%id\`)
#[tracing::instrument(name = "get_product", skip(state), fields(product.id = %id))]
async fn get_product(state:&AppState,id:Uuid)-> Product { ... }

Now you can search for all spans named get_product and filter by the product.id attribute.

OpenTelemetry defines semantic conventions https://opentelemetry.io/docs/specs/semconv/, standardized attribute names for common operations. Using ensures your traces are compatible with observability tools and comparable across services.

Why follow semantic conventions?

  • Tool compatibility: Observability platforms (Jaeger, Grafana, Datadog) recognize standard attributes and provide built-in dashboards
  • Cross-service consistency: All services use the same attribute names, enabling unified queries
  • Futureproofing: New tools automatically understand your traces

Rather than memorizing dotted strings and risking typos, the Rust ecosystem provides the https://crates.io/crates/opentelemetry-semantic-conventions crate. It defines every standard attribute name as a &str constant, giving you compile-time guarantees and easy discoverability via your IDE’s autocomplete.

# Add to Cargo.toml
[dependencies]
opentelemetry-semantic-conventions = "0.31"

The convention is to import the crate with a short alias:

use opentelemetry_semantic_conventions as semconv;

The crate is organized into modules that match how you use the constants:

ModulePurposeExample Constants
semconv::resourceResource-level attributesSERVICE_NAME, SERVICE_VERSION
semconv::traceSpan-level attributesHTTP_REQUEST_METHOD, DB_SYSTEM_NAME, ERROR_TYPE
semconv::attributeAll constants (superset)Everything in resource and trace, plus more

Table 4.6 – Modules of the opentelemetry-semantic-conventions crate

Here are the key conventions you’ll encounter throughout the book, along with their crate constants:

HTTP Conventions (for server and client spans):

AttributeCrate ConstantExampleDescription
http.request.methodsemconv::trace::HTTP_REQUEST_METHODPOSTHTTP method
http.routesemconv::trace::HTTP_ROUTE/orders/{id}Route template (not actual path)
http.response.status_codesemconv::trace::HTTP_RESPONSE_STATUS_CODE200Response status code
url.pathsemconv::trace::URL_PATH/orders/a7f3c5Actual request path
server.addresssemconv::trace::SERVER_ADDRESSorders‑serviceTarget server hostname

Table 4.7 – HTTP semantic convention attributes with their crate constants

Database Conventions:

AttributeCrate ConstantExampleDescription
db.system.namesemconv::trace::DB_SYSTEM_NAMEpostgresqlDatabase system identifier
db.namespacesemconv::trace::DB_NAMESPACEotelmartDatabase name / namespace
db.operation.namesemconv::trace::DB_OPERATION_NAMESELECTOperation type
db.query.textsemconv::trace::DB_QUERY_TEXTSELECT * FROM...Query text (sanitized!)

Table 4.8 – Database semantic convention attributes with their crate constants

Custom Business Attributes:

For domain-specific data, prefix with your organization or project name. There are no crate constants for these; they’re your own:

AttributeExampleDescription
otelmart.order.idord_123Order identifier
otelmart.customer.email[email protected]Customer email
otelmart.item.count3Items in order

Table 4.9 – Custom otelmart. business attributes for domain-specific data*

The otelmart. prefix prevents collisions with standard OpenTelemetry attributes and clearly identifies domain specific data. This is especially important when:

  • Sending traces to shared observability platforms (multi-tenant SaaS)
  • Merging traces from multiple projects
  • Avoiding conflicts with future OpenTelemetry conventions

Using the constants in code:

The constants are &str values, so they plug directly into KeyValue::new() for span events and resource attributes:

use opentelemetry::KeyValue;
use opentelemetry_semantic_conventions as semconv;
// Resource attributes (set once at startup in telemetry.rs)
let resource_attrs = vec![
KeyValue::new(semconv::resource::SERVICE_NAME, "products"),
KeyValue::new(semconv::resource::SERVICE_VERSION, env!("CARGO_PKG_VERSION")),
];
// Span event attributes (set during execution in handlers)
span.add_event("db.query", vec![
KeyValue::new(semconv::trace::DB_SYSTEM_NAME, "postgresql"),
KeyValue::new(semconv::trace::DB_OPERATION_NAME, "SELECT"),
]);

One caveat with #[instrument]: The #[instrument(fields(...))] macro requires compile-time field name identifiers; you cannot use a constant as a field name:

// Won't compile: field names must be identifiers, not expressions
#[instrument(fields(semconv::trace::DB_SYSTEM_NAME = "postgresql"))]
// Works: use the dotted name directly as a field identifier
#[instrument(fields(otel.kind = "client", db.system.name = "postgresql"))]

This means #[instrument] fields use the dotted string names by convention, while KeyValue::new() and span.add_event() can use the crate constants. In our Chapter 4 code, HTTP and client conventions are handled automatically by OtelAxumLayer and reqwest‑tracing, so you won’t need to set them manually. The crate becomes more valuable in later chapters when we add custom span events and richer resource attributes.

The crate also has a semconv_experimental feature flag that unlocks experimental and deprecated attributes. Stick with the defaults (stable attributes only) unless you have a specific need.

Designing a Taxonomy for OpenTel E-Commerce

Section titled “Designing a Taxonomy for OpenTel E-Commerce”

Here’s our span naming taxonomy for the four services:

Service

Span Name

Kind

Key Attributes

Gateway

HTTP POST /api/orders

Server

http.route, http.method

HTTP POST orders‑service

Client

server.address

Products

HTTP GET /products/{id}

Server

http.route, product.id

db.query get_product

Client

db.system.name, db.operation.name

cache.lookup product

Internal

cache.hit (if implemented)

Inventory

HTTP POST /inventory/reserve

Server

http.route

db.query reserve_stock

Client

db.system.name, db.query.text

lock.acquire inventory

Internal

lock.key (if using explicit locks)

Orders

HTTP POST /orders

Server

http.route

validate_order

Internal

otelmart.order.id

HTTP GET products‑service

Client

server.address, product.id

HTTP POST inventory‑service/reserve

Client

server.address

db.query create_order

Client

db.system.name, db.operation.name

saga.compensate

Internal

saga.step (rollback on failure)

Table 4.10 – Span naming taxonomy for the four OpenTel E-Commerce services

To illustrate how these conventions would look in code, here’s a sketch for the Orders service. In our actual Chapter 4 implementation, HTTP client attributes like http.request.method and server.address are handled automatically by the reqwest‑tracing middleware, so you won’t see them in thehandler code. We include them here to show how you’d add them manually if the middleware weren’t available:

#[instrument(
name = "create_order",
skip(state, request),
fields(
otelmart.order.item_count = request.items.len(),
otelmart.customer.email = %request.customer_email,
)
)]
pub async fn create_order(
state: &AppState,
request: CreateOrderRequest,
) -> Result<Order, OrderError> {
info!("Starting order creation");
// Validate products
for item in &request.items {
let product = fetch_product(state, item.product_id).await?;
// Add product info to current span
Span::current().record("otelmart.product.sku",&product.sku);
}
// Reserve inventory
reserve_inventory(state,&request.items).await?;
// Create order in database
let order = insert_order(state,&request).await?;
info!(order.id = %order.uuid, "Order created successfully");
Ok(order)
}
#[instrument(
name = "HTTP GET products-service",
skip(state),
fields(
http.request.method = "GET",
server.address = "products-service",
product.id = %product_id,
)
)]
async fn fetch_product(state:&AppState,product_id:Uuid)-> Result<Product, OrderError> {
let url = format!("http://products:3001/products/{}", product_id);
let response = state.http_client
.get(&url)
.send()
.await?;
// Record response status
Span::current().record("http.response.status_code", response.status().as_u16());
// ... parse response
}

With a consistent taxonomy in place, we’re ready to instrument our services. The next section covers automatic vs. manual instrumentation**,** when to use #[instrument] macros versus explicit span creation.

With the telemetry skeleton in place, we’re ready to instrument the request journey we mapped in Chapter 3. We’ll start at the entry point: HTTP requests arriving at the services.

There are two approaches to adding spans to the code: automatic instrumentation (middleware that creates spans for you) and manual instrumentation (explicit span creation in the code).

Use only automatic instrumentation, and you’ll see HTTP requests but not what happens inside them. Use only manual instrumentation, and you’ll spend hours adding #[instrument] to every function, creating noisy traces. The recommended approach is to combine both strategically.

Server-Side: Automatic HTTP Instrumentation

Section titled “Server-Side: Automatic HTTP Instrumentation”

For HTTP servers like Axum, automatic instrumentation captures every incoming request without modifying the handlers. We’ll use axum‑tracing‑opentelemetry, which provides purpose-built middleware that handles span creation, OpenTelemetry semantic conventions, and trace context extraction in one package:

# Add to Cargo.toml
[dependencies]
axum-tracing-opentelemetry = "0.33.0"
tower-http = { version = "0.6", features = ["cors"] }
// otelmart/src/main.rs
use axum_tracing_opentelemetry::middleware::{OtelAxumLayer, OtelInResponseLayer};
pub fn create_router(state: AppState) -> Router {
Router::new()
// ...router configuration
// Include trace context as header into the response
.layer(OtelInResponseLayer::default())
// Start OpenTelemetry trace on incoming request
.layer(OtelAxumLayer::default()) // must be added after OtelInResponseLayer
.layer(CorsLayer::permissive())
// ...other middleware
}

These two middleware layers automatically:

  • Create a server span for every incoming HTTP request
  • Record OpenTelemetry semantic convention attributes (http.request.method, http.route, url.path, http.response.status_code)
  • Extract the traceparent header from incoming requests and set the parent context
  • Inject trace context into response headers (via OtelInResponseLayer)
  • Measure request duration

IMPORTANT

Layer ordering matters. In Axum, layers added later in the .layer() chain wrap the outer layer, so they execute first on the request path. OtelAxumLayer must be added after OtelInResponseLayer so that it runs first on incoming requests (creating the server span and extracting traceparent), while OtelInResponseLayer runs on the response path (injecting trace context into response headers). CorsLayer goes after both, so it executes first, ensuring CORS preflight requests are handled before tracing kicks in.

Why not hand-roll with TraceLayer? Tower’s TraceLayer::new_for_http() from tower‑http is a general purpose tracing middleware. You can customize it with make_span_with() callbacks to add semantic convention attributes and trace context extraction. But OtelAxumLayer does all of this out of the box, correct attribute names, proper SpanKind::Server, W3C context propagation, without the boilerplate. For most Axum services, the library approach is both simpler and more correct.

So far, we have focused on what OtelAxumLayer gives us out of the box. The following details are informational for readers who want to understand what is happening under the hood. In practice, OtelAxumLayer handles context extraction without any custom code on your part.

Trace Context Extraction: Unlike a bare TraceLayer, OtelAxumLayer automatically extracts the traceparent header from incoming requests and sets it as the parent context on the server span. This means downstream services automatically participate in the same distributed trace without any custom MakeSpan implementation.

Automatic instrumentation captures HTTP boundaries, but not what happens inside your handlers. For business logic, use #[tracing::instrument].

The #[instrument] macro is a procedural macro that wraps your function in a span. It:

  • Creates a span with the function name (or custom name)
  • Automatically records function arguments as span attributes
  • Handles async functions correctly (span stays active across await points)
  • Closes the span when the function returns (even on error)

Without #[instrument], you’d need to manually create, enter, and exit spans, which is error-prone and verbose.

#[tracing::instrument(
name = "reserve_stock",
skip(state),
fields(
otel.kind = "client",
product.id = %product_id,
quantity = quantity,
db.system.name = "postgresql",
)
)]
pub async fn reserve_stock(
state: &AppState,
product_id: Uuid,
quantity: i32,
) -> Result<StockReservation, InventoryError> {
// This entire function is wrapped in a span named "reserve_stock"
// ...
// Add event for lock acquisition
tracing::info!("Acquiring row lock");
let result = sqlx::query_as!(...);
match result {
Some(reservation) => {
tx.commit().await?;
tracing::info!("Stock reserved successfully");
Ok(reservation)
}
None => {
tx.rollback().await?;
tracing::warn!("Insufficient stock");
// Mark span as error for observability platforms
Span::current().record("error", true);
Span::current().record("error.type", "InsufficientStock");
Err(InventoryError::InsufficientStock)
}
}
}
ScenarioApproachReason
HTTP server endpointsAutomatic (OtelAxumLayer)Consistent, no code changes needed
HTTP client callsAutomatic (reqwest‑tracing)Middleware handles context injection
Database queriesManualCapture query details, timing
Business logicManualDomain-specific naming and attributes
Third-party librariesDependsCheck if the library has OTel support
Simple utility functionsSkipAdds noise without insight (e.g., format_email, parse_uuid)

Table 4.11 – When to use automatic instrumentation, manual instrumentation, or skip instrumentation altogether

The goal is meaningful instrumentation, not maximum instrumentation. A trace with 100 spans for a simple checkout is harder to read than one with 10 well named spans.

HTTP Client Instrumentation: We’ll cover this in detail in section 4.7, but the key insight is that reqwest‑tracing middleware handles context injection automatically:

use reqwest_middleware::ClientBuilder;
use reqwest_tracing::{TracingMiddleware, SpanBackendWithUrl};
// Wrap your reqwest client once at startup
let http_client = ClientBuilder::new(reqwest::Client::new())
.with(TracingMiddleware::<SpanBackendWithUrl>::new())
.build();
// Then use it like a normal client; tracing + propagation happen automatically
let response = http_client.get(url).send().await?;

The middleware creates a client span, injects the traceparent header, and records the response status, ensuring the downstream service’s span becomes a child of the current span.

Combining Automatic and Manual Instrumentation

Section titled “Combining Automatic and Manual Instrumentation”

Here’s how they work together in a typical request flow:

Generated ASCII Image

Figure 4.6 – Automatic HTTP instrumentation and manual business-logic instrumentation combined in a single trace

The OtelAxumLayer middleware creates the outer server span for each service, reqwest‑tracing creates client spans for outgoing calls, and manual #[instrument] adds visibility into business logic. Together, they create a complete picture of the request flow.

One of #[instrument] ‘s most powerful features is its seamless handling of async functions. In async Rust, functions can suspend at await points and resume later, potentially on different threads. Without proper instrumentation, span context would be lost across these suspension points.

The Problem Without #[instrument]:

// ❌ BROKEN: Span bleeds into other tasks across await
pub async fn fetch_product(id: Uuid) -> Result<Product> {
let span = tracing::span!(Level::INFO, "fetch_product");
let _enter = span.enter(); // Span entered on this thread
let product = db::get_product(id).await; // ⚠️ Guard stays alive across .await!
// Other tasks scheduled on this thread now run inside our span
Ok(product)
}

The _enter guard is not dropped at the .await point. It stays alive, keeping the span entered on the thread. In async runtimes like Tokio, multiple tasks share the same OS thread. When Task A suspends at .await with the guard still held, Tokio may schedule Task B on that thread. Task B’s spans and log events now appear as children of Task A’s span in Jaeger, producing misleading traces where unrelated work is attributed to the wrong request.

How #[instrument] Solves This:

// ✅ CORRECT: Span context preserved across await
#[instrument(skip(state), fields(product.id = %id))]
pub async fn fetch_product(state:&AppState,id:Uuid)-> Result<Product> {
tracing::info!("Fetching product");
let product = db::get_product(&state.pool,id).await; // ✅ Span stays active
// Span is still active - database query is correctly linked
Ok(product)
}

The #[instrument] macro wraps the async function body with tracing::Instrument, which enters the span at the start of each poll() call and exits it when the poll completes. The span is only active while the future is executing on the thread, not while it’s suspended. This approach is runtime-agnostic (works with Tokio, async-std, or any executor) and prevents the span from bleeding into unrelated tasks between await points.

Why This Matters for Distributed Tracing:

In a typical handler, you might have multiple async operations:

#[instrument(name = "create_order", skip(state))]
pub async fn create_order(state:&AppState,req:OrderRequest)-> Result<Order> {
// All of these .await points preserve the span context
let product = fetch_product(state, req.product_id).await?;
let reservation = reserve_inventory(state, req.product_id, req.quantity).await?;
let order = insert_order(state,&req).await?;
Ok(order)
}

Without #[instrument], each await would break the span hierarchy. With it, you get a clean parent-child relationship:

Generated ASCII Image

Figure 4.7 – The parent-child span structure of create_order with fetch_product, reserve_inventory, and insert_order child spans

Always use #[instrument] on async functions that perform I/O operations. Manual span management in async code is error-prone and easy to get wrong.

When operations fail, recording the error in the span provides crucial debugging context. Use tracing::error!() to log the error as a span event, and set_status() to mark the span as failed in OpenTelemetry. This ensures that observability backends like Jaeger highlight failed spans in red and allow filtering by error status.

Setting Span Status:

Use set_status() from OpenTelemetrySpanExt to explicitly mark a span as failed. This is what makes Jaeger highlight the span in red:

use opentelemetry::trace::Status;
use tracing_opentelemetry::OpenTelemetrySpanExt;
#[instrument(skip(state))]
pub async fn reserve_inventory(state: &AppState, product_id: Uuid, qty: i32) -> Result<()> {
match try_reserve(state, product_id, qty).await {
Ok(_) => {
// Don't set Status::Ok; the spec recommends leaving status as Unset
// on success. Unset already means "no error occurred."
Ok(())
}
Err(e) if e.is_insufficient_stock() => {
// Business logic error - not a system failure
Span::current().set_status(Status::error("Insufficient stock"));
tracing::warn!(product.id = %product_id, "Insufficient stock");
Err(e)
}
Err(e) => {
// System error - database failure, network issue, etc.
Span::current().set_status(Status::error(format!("Database error: {}", e)));
tracing::error!(error = %e, "Failed to reserve inventory");
Err(e)
}
}
}

Error Propagation in Distributed Traces:

When an error occurs deep in a service call chain, the error status propagates up the span hierarchy:

Generated ASCII Image

Figure 4.8 – Error status propagating from the failing Inventory reservation up to the root checkout span

In Jaeger, you can filter traces by error status to find failures quickly, and the span hierarchy shows exactly where the error originated.

I MPORTANT

Treat system errors (database down, network timeout) differently from business errors (out of stock, invalid input). Mark a span as failed only when the system is broken. If the system worked correctly but has declined the request (e.g., “invalid password”), log it as a warning instead.

With instrumentation in place, we need to ensure traces flow correctly across service boundaries. Server-side instrumentation captures incoming requests, but distributed tracing requires linking those requests across services. Now we’ll instrument the outgoing HTTP calls.

The magic of distributed tracing spans from different services connecting into a unified trace. This requires context propagation passing trace identity across process boundaries via HTTP headers.

Here’s what propagation looks like:

Generated ASCII Image

Figure 4.9 – Trace context propagating between Orders and Inventory services through the traceparent HTTP header

Without propagation, Span C would be a new root span, disconnected from the Orders Service trace.

When the Orders Service calls the Inventory Service, how does the Inventory Service know it should create a child span of the Orders span? The services are separate processes; they don’t share memory.

The answer is HTTP headers. The Orders Service injects its SpanContext into the outgoing request headers. The Inventory Service extracts that context and uses it as the parent for its spans.

What gets propagated? TraceID, SpanID, TraceFlags, TraceState.

This data is encoded in the traceparent header using the W3C Trace Context format we saw in section 4.2.

Injection: Adding Context to Outgoing Requests

Section titled “Injection: Adding Context to Outgoing Requests”

When makes HTTP calls to other services, we need to inject the current trace context into the outgoing request’s headers. Rather than doing this manually for every call, we use reqwest‑tracing middleware that wraps a standard reqwest::Client:

use reqwest_middleware::ClientBuilder;
use reqwest_tracing::{TracingMiddleware, SpanBackendWithUrl};
// Build the instrumented HTTP client (once, at startup)
let reqwest_client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.build()?;
let http_client = ClientBuilder::new(reqwest_client)
.with(TracingMiddleware::<SpanBackendWithUrl>::new())
.build();

Now every HTTP call made through http_client is automatically:

  1. Creates a client span with HTTP semantic convention attributes
  2. Injects the traceparent and tracestate headers
  3. Records the response status code on span completion

Using the client in a handler follows a familiar pattern:

#[tracing::instrument(
name = "reserve_inventory",
skip(state, items),
)]
async fn reserve_inventory(
state: &AppState,
items: &[OrderItem],
) -> Result<Vec<Reservation>, OrderError> {
// The TracingMiddleware automatically creates a client span
// and injects traceparent/tracestate headers
let response = state.http_client
.post("http://inventory:3002/reserve")
.json(items)
.send()
.await?;
// ... handle response
}

📁 Code Reference: See code/chapter_4/orders/src/main.rs for the HTTP client setup with reqwest‑tracing, and code/chapter_4/orders/src/handlers/orders.rs for how handlers use the instrumented client.

After injection, the request headers contain:

traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
tracestate: (optional vendor-specific data)

Why SpanBackendWithUrl? The TracingMiddleware is generic over a span backend. SpanBackendWithUrl includes the request URL in the span name (e.g., HTTP GET http://products:3001/products/...), which is useful for debugging. For production, you might prefer a custom backend that uses the route template for lower cardinality.

ℹ️ Context Timing: With reqwest‑tracing, you don’t need to worry about the context timing pitfall described in many OpenTelemetry guides (extracting context before the client span exists). The middleware creates the client span before injecting headers, ensuring the correct parent-child relationship every time.

Extraction: Reading Context from Incoming Requests

Section titled “Extraction: Reading Context from Incoming Requests”

On the receiving service, the incoming traceparent header must be extracted and set as the parent context for the server span. This is a subtle operation: the parent must be set before the span is entered (made active), because OpenTelemetry’s span model doesn’t allow reparenting active spans.

Why this matters: If you tried to write Axum middleware that calls Span::current().set_parent(), it would run after the server span has already been created and entered. The set_parent() call would silently fail, producing disconnected traces.

OtelAxumLayer handles this correctly. Internally, it extracts the traceparent header and sets the parent context during span creation, before the span is entered. All you need is two lines on your router:

use axum_tracing_opentelemetry::middleware::{OtelAxumLayer, OtelInResponseLayer};
pub fn create_router(state: AppState) -> Router {
Router::new()
.route("/reserve", post(reserve_stock))
.with_state(state)
.layer(OtelInResponseLayer::default())
.layer(OtelAxumLayer::default()) // Extracts traceparent + creates server span
.layer(CorsLayer::permissive())
}

What OtelAxumLayer does under the hood: It uses the W3C TraceContextPropagator we configured in init_telemetry to extract the parent context from the traceparent header. If no header is present (e.g., the request came directly from a browser), the span becomes a new root span, which is correct behavior for external requests.

In Chapter 3, we manually passed X‑Correlation‑ID headers:

// Old approach (Chapter 3)
let correlation_id = Uuid::new_v4();
client.post(&url)
.header("X-Correlation-ID", correlation_id.to_string())
.send()
.await?;

You can now remove all manual handling of the X‑Correlation‑ID header from your services. With reqwest‑tracing on the client side and OtelAxumLayer on the server side, the traceparent header is automatically injected and extracted:

// New approach (Chapter 4)
// Just use the instrumented client; context propagation is automatic
let response = state.http_client
.post("http://inventory:3002/reserve")
.json(&items)
.send()
.await?;
// traceparent header is automatically added by reqwest-tracing

The trace context carries more information than a simple correlation ID:

  • TraceID: Equivalent to our correlation ID
  • SpanID: Identifies the specific operation, not just the request
  • TraceFlags: Sampling decisions
  • TraceState: Vendor-specific context

To verify that propagation is working correctly, check the Jaeger UI:

  1. Single TraceID: All spans across all services should share the same TraceID
  2. Parent-Child Relationships: The Inventory service’s span should be a child of the Orders service’s client span
  3. No Orphaned Spans: Every span except the root should have a parent

If you see multiple traces instead of one unified trace, propagation is broken. Common causes:

  • Missing OtelAxumLayer on the receiving service’s router
  • Using a bare reqwest::Client instead of ClientWithMiddleware for outgoing calls
  • RUST_LOG not including otel::tracing=trace (causes SpanDisabled errors)

With context propagation in place, we have all the building blocks for distributed tracing. The patterns we’ve covered (OtelAxumLayer for server-side instrumentation, reqwest‑tracing for client-side instrumentation, and #[instrument] for business logic) apply consistently across all services.

📁 Repository Reference: Complete service implementations demonstrating these patterns are available in the code folder:

code/chapter_4/products/ - Basic HTTP server with database queries

code/chapter_4/inventory/ - Database transactions with error recording

code/chapter_4/orders/ - HTTP client calls with automatic context injection

code/chapter_4/otelmart/ - API gateway proxying requests across services

All four services follow the same pattern: telemetry::init_telemetry() -> OtelAxumLayer + OtelInResponseLayer -> instrumented handlers. Services that make outgoing HTTP calls (Orders and OtelMart) wrap their reqwest::Client in ClientWithMiddleware with TracingMiddleware for automatic context propagation.

Our services are now instrumented, but we need somewhere to send the traces. We’ll add Jaeger to our Docker Compose setup.

Why Jaeger?

  • All-in-one: Single container includes collector, storage, and UI
  • Industry standard: Widely used CNCF project with a strong community
  • Free and self-hosted: No vendor lock-in or usage costs
  • OTLP support: Native support for OpenTelemetry Protocol

The jaegertracing/all‑in‑one image is perfect for development, but uses in-memory storage (traces disappear on restart). For production, see the Jaeger documentation https://www.jaegertracing.io/docs/latest/deployment/ for persistent storage options.

Here’s how to add Jaeger to the docker‑compose.yml:

services:
# Jaeger for distributed tracing
jaeger:
image: jaegertracing/all-in-one:latest
container_name: jaeger
environment:
- COLLECTOR_OTLP_ENABLED=true # Enable OTLP gRPC/HTTP receivers
ports:
- "16686:16686" # Jaeger UI (web interface)
- "4317:4317" # OTLP gRPC receiver (our services use this)
- "4318:4318" # OTLP HTTP receiver (alternative to gRPC)
networks:
- app-network
# Services use these OTEL environment variables:
products:
build:
context: .
dockerfile: products/Dockerfile
environment:
- APP_DATABASE_URL=postgres://opentel_user:opentel_pass@postgres:5432/opentel_db
- OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4317
- OTEL_SERVICE_NAME=products
- RUST_LOG=info,otel::tracing=trace
depends_on:
postgres:
condition: service_healthy
jaeger:
condition: service_started
# ... ports, networks, etc.
inventory:
# Similar configuration with OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4317
orders:
# Similar configuration with OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4317
otelmart:
# Similar configuration with OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4317

The depends_on ensures services wait for Jaeger to start before attempting to export spans. Without this, services might crash into startup if they can’t reach the OTLP endpoint.

This configuration matches the code/chapter_4/docker‑compose.yml file in the code folder.

Build and start all services:

docker-compose up --build

The ‑‑build flag ensures Docker rebuilds images with the latest code changes.

Verify Jaeger is running:

  1. Open http://localhost:16686 in your browser
  2. You should see the Jaeger UI with a “Search” page
  3. The service dropdown will be empty until you generate your first trace (covered in the next section)

Troubleshooting:

  • If Jaeger UI doesn’t load: Check docker‑compose logs jaeger for errors
  • If services fail to start: Ensure OTEL_EXPORTER_OTLP_ENDPOINT is set correctly

For production, the OpenTelemetry Collector provides advantages over direct-to-Jaeger export:

  • Reliability: Buffers and retries failed exports
  • Flexibility: Route traces to multiple backends (Jaeger, Tempo, Honeycomb, etc.)
  • Processing: Sample, filter, or enrich traces before storage
  • Vendor-neutral: Swap backends without changing application code

Add the Collector service to docker‑compose.yml:

otel-collector:
image: otel/opentelemetry-collector-contrib:latest # Use specific version in production
container_name: otel-collector
command: ["--config=/etc/otel-collector-config.yaml"]
volumes:
- ./otel-collector-config.yaml:/etc/otel-collector-config.yaml
ports:
- "4317:4317" # OTLP gRPC (for services)
- "4318:4318" # OTLP HTTP
networks:
- app-network

Create otel‑collector‑config.yaml:

receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317 # Accept traces from services
http:
endpoint: 0.0.0.0:4318
processors:
batch:
timeout: 5s # Batch spans for 5s before exporting
send_batch_size: 512 # Or when 512 spans accumulate
exporters:
otlp/jaeger:
endpoint: jaeger:4317 # Forward to Jaeger
tls:
insecure: true # No TLS in dev (use TLS in production!)
logging:
loglevel: debug # Log traces to collector stdout (for debugging)
service:
pipelines:
traces:
receivers: [otlp] # Receive from services
processors: [batch] # Batch before export
exporters: [otlp/jaeger, logging] # Send to Jaeger + logs

Change service environment variables from:

- OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4317

to:

- OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317

The collector will handle forwarding to Jaeger, and you can add more exporters (DataDog, Honeycomb, etc.) without changing service code.

Start the stack and make a checkout request:

# Start all services
docker-compose up --build
# In another terminal, get a valid product UUID from the database:
docker exec -it opentel-postgres psql -U opentel_user -d opentel_db \
-c "SELECT uuid, product_name FROM products.products LIMIT 1;"
# Then place a guest-checkout order through the gateway (port 4200).
# The body must include items, shipping_address, and payment —
# see CreateOrderRequest in code/chapter_4/orders/src/models/order.rs.
curl -X POST http://localhost:4200/api/orders \
-H "Content-Type: application/json" \
-d '{
"customer_email": "[email protected]",
"items": [{
"product_uuid": "YOUR_PRODUCT_UUID_HERE",
"product_name": "Sample Product",
"quantity": 1,
"unit_price": "19.99"
}],
"shipping_address": {
"first_name": "Test",
"last_name": "User",
"address_line1": "123 Main St",
"city": "Seattle",
"state": "WA",
"postal_code": "98101",
"country": "US"
},
"payment": {
"payment_method": "credit_card",
"card_last4": "4242",
"card_brand": "visa"
}
}'

Expected response (HTTP 201 Created):

{
"success": true,
"order_number": "ORD-20260510-0001",
"order_uuid": "a7f3c5...",
"message": "Order created successfully"
}

If the request fails:

  • Connection refused: Services aren’t running yet (wait ~30s after docker‑compose up).
  • 404 Not Found: Check the endpoint is /api/orders (not /orders).
  • 400 Bad Request: the shipping_address and payment blocks are required — don’t omit them. unit_price must equal the product’s current final_price.
  • Product not found: Use a valid product UUID from the SQL query above.

Open http://localhost:16686 in in your browser.

Navigate to your trace:

  1. Select Service: In the left sidebar, find the “Service” dropdown and choose “otelmart”
  2. Set Time Range: The default “Last Hour” should work, or click “Lookback” and select “Last 15 Minutes”
  3. Find Traces: Click the blue “Find Traces” button at the bottom of the sidebar
  4. Identify Your Trace: Look for a trace with:
    • Operation: HTTP request
      • Duration: ~800-1000ms (depending on your system)
      • Spans: 10+ spans across 4 services
  5. View Details: Click on the trace to see the waterfall diagram

Every layer we added throughout this chapter, the telemetry module, the Axum middleware, the reqwest-tracing wrapper, the #[instrument] annotations, converges here. You’ll see a waterfall diagram showing:

Generated ASCII Image

Figure 4.10 – The realized end-to-end checkout trace in Jaeger, highlighting the slow Inventory UPDATE query as the bottleneck

Compared to Chapter 3 ‘s println! logging:

Before (Chapter 3)After (Chapter 4)
Grep 4 log filesSingle trace view
Guess timestampsPrecise durations
Manual correlation IDsAutomatic propagation
“Which service is slow?”Obvious from the waterfall
“What is called what?”Parent-child spans

Table 4.12 – What we can do after Chapter 4 versus what was possible with Chapter 3 ‘s println! logging

In our trace, we can immediately see that inventory: db.query took 550ms, which is 65% of the total request time. Without distributed tracing, we would have had to:

  1. Check OtelMart logs: “Checkout took 850ms”
  2. SSH into Orders, grep for correlation ID
  3. SSH into Inventory, grep for the same ID
  4. Manually calculate time differences
  5. Guess where the delay occurred

With tracing, we click once and see the answer.

Before trusting your traces in production, check for these patterns:

Signs of healthy traces:

  • Clear parent-child nesting visible in the waterfall
  • Consistent span naming across services
  • Single TraceID spans all four services in one request
  • Client spans from Orders connect to Server spans in Products/Inventory

Signs of broken traces:

  • Flat timeline with no hierarchy (missing parent links)
  • Multiple TraceIDs for one logical request (propagation failure)
  • Gaps between services (missing client spans)
  • Excessive micro-spans creating visual noise

If your checkout trace shows four disconnected root spans rather than a single unified tree, context propagation is broken; revisit S ection 4.7.

How to fix broken traces:

SymptomLikely CauseFix
Flat timeline (no hierarchy)Missing OtelAxumLayer on receiverEnsure all services have OtelAxumLayer in their router
Multiple TraceIDs for one requestUsing bare reqwest::ClientWrap client with reqwest‑tracing middleware
Gaps between servicesMissing client spansEnsure outgoing calls use ClientWithMiddleware
Excessive micro-spansOver-instrumentationRemove #[instrument] from utility functions

Table 4.13 – Symptoms of broken traces, their likely causes, and how to fix them

We have built the telemetry skeleton for OpenTel E-Commerce:

What We Implemented:

  • A shared telemetry module with TracerProvider initialization
  • Automatic server-side HTTP instrumentation via axum‑tracing‑opentelemetry (OtelAxumLayer)
  • Automatic client-side HTTP instrumentation via reqwest‑tracing (TracingMiddleware)
  • Manual instrumentation for business logic using #[tracing::instrument]
  • Context propagation across service boundaries (automatic via middleware)
  • Jaeger integration for trace visualization
  • Graceful shutdown to ensure spans are flushed

The Trace Taxonomy:

  • Operation-centric span names (low cardinality)
  • OpenTelemetry semantic conventions for HTTP and database operations
  • Custom otelmart.* attributes for business context

Key Concepts:

  • TraceID links all spans in a request
  • SpanID + ParentID creates hierarchy
  • SpanContext propagates via W3C traceparent headers
  • The tracing -> tracing‑opentelemetry -> OTLP pipeline
  • Library middleware (OtelAxumLayer, reqwest‑tracing) handles HTTP instrumentation and context propagation automatically, freeing you to focus #[instrument] usage on business logic

The “chaos” we built in Chapter 3 is no longer a black box. We can now see inside. This foundation supports everything we’ll build next.

In Chapter 5, we continue this request journey into the data layer by instrumenting SQLx operations as first-class database spans under these HTTP parent spans. That is where query timing, lock waits, and transaction behavior become visible in the same trace.