# Rust OpenTelemetry: A Senior Engineer’s Guide to Instrumenting Backend APIs

> Learn step-by-step how to add OpenTelemetry tracing, metrics, and logs to Rust backend services and export them to Jaeger and Prometheus.

Implementing OpenTelemetry in a Rust backend is now a tractable task: the `rust-opentelemetry-backend` stack lets you emit traces, metrics, and structured logs from a single codebase, and ship them to a collector or SaaS endpoint without rewriting business logic.

## What is rust‑opentelemetry‑backend and why does it matter?

The short answer: it is the collection of Rust crates—`opentelemetry`, `opentelemetry‑otlp`, `tracing‑opentelemetry`, and `metrics‑exporter‑prometheus`—that together provide end‑to‑end observability for services written in Rust. By wiring these crates into your HTTP framework (Actix, Axum, or Warp) you gain a unified context that propagates across async boundaries, enabling you to correlate latency spikes, error rates, and log entries across a distributed system.

I care about this because, as a senior engineer, I’ve seen production outages where missing trace IDs made root‑cause analysis a nightmare. Adding OpenTelemetry early eliminates that blind spot and aligns Rust services with the observability standards already used in Java, Go, or Node ecosystems.

## How do I set up the OpenTelemetry SDK in a Rust service?

The answer is straightforward: add the required crates, configure a tracer provider, and install a global propagator. Below is a minimal `Cargo.toml` snippet for an Actix‑Web API:

```toml
[dependencies]
actix-web = "*"
tracing = "*"
tracing-subscriber = { version = "*", features = ["env-filter"] }
opentelemetry = { version = "*", features = ["trace"] }
opentelemetry-otlp = { version = "*", features = ["grpc-tonic"] }
tracing-opentelemetry = "*"
metrics = "*"
metrics-exporter-prometheus = "*"
```

Next, bootstrap the tracer in `main.rs`:

```rust
use actix_web::{App, HttpServer};
use opentelemetry::sdk::trace as sdktrace;
use opentelemetry_otlp::WithExportConfig;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

#[tokio::main]
async fn main() -> std::io::Result<()> {
    // Build an OTLP exporter that talks to a collector on a local endpoint
    let exporter = opentelemetry_otlp::new_exporter()
        .tonic()
        .with_endpoint("http://localhost:COLLECTOR_PORT");

    // Create a tracer provider with a simple batch span processor
    let tracer = sdktrace::TracerProvider::builder()
        .with_batch_exporter(exporter, sdktrace::BatchConfig::default())
        .build()
        .versioned_tracer(
            "rust-opentelemetry-backend",
            Some(env!("CARGO_PKG_VERSION")),
            None,
        );

    // Install the global tracer and a TextMapPropagator for context propagation
    let _ = opentelemetry::global::set_tracer_provider(tracer);
    opentelemetry::global::set_text_map_propagator(opentelemetry::propagation::TraceContextPropagator::new());

    // Wire tracing into Actix via tracing‑opentelemetry
    let otel_layer = tracing_opentelemetry::layer().with_tracer(opentelemetry::global::tracer("actix"));
    tracing_subscriber::registry()
        .with(tracing_subscriber::EnvFilter::from_default_env())
        .with(otel_layer)
        .init();

    HttpServer::new(|| {
        App::new()
            .wrap(actix_web::middleware::Logger::default())
            .service(actix_web::web::resource("/health").to(|| async { "OK" }))
    })
    .bind(("127.0.0.1", SERVICE_PORT))?
    .run()
    .await
}
```

This code does three things: (1) creates an OTLP exporter, (2) registers a batch processor to avoid blocking the request thread, and (3) installs a `tracing` layer that automatically converts `tracing` spans into OpenTelemetry spans. The setup follows the official OpenTelemetry Rust quick‑start guide [OpenTelemetry Rust documentation](https://opentelemetry.io/docs/instrumentation/rust/).

## How can I trace HTTP handlers with Actix‑Web and retain context across async calls?

Answer: wrap each handler in a `tracing::instrument` macro and let the `tracing‑opentelemetry` layer propagate the span automatically. Here’s a concrete example:

```rust
use actix_web::{get, HttpResponse, Responder};
use tracing::instrument;
use sqlx::PgPool;

#[instrument(name = "get_user", skip(pool))]
async fn fetch_user(pool: &PgPool, user_id: i32) -> Result<User, sqlx::Error> {
    sqlx::query_as::<_, User>("SELECT * FROM users WHERE id = $1")
        .bind(user_id)
        .fetch_one(pool)
        .await
}

#[get("/users/{id}")]
#[instrument(skip(pool), fields(user_id = %path.id()))]
async fn get_user(path: actix_web::web::Path<(i32,)>, pool: actix_web::web::Data<PgPool>) -> impl Responder {
    match fetch_user(&pool, path.into_inner().0).await {
        Ok(user) => HttpResponse::Ok().json(user),
        Err(e) => {
            tracing::error!(error = %e, "Failed to fetch user");
            HttpResponse::InternalServerError().finish()
        }
    }
}
```

The `#[instrument]` macro automatically creates a span named `get_user`, attaches the `user_id` field, and inherits the parent span from the incoming request. Because the global propagator is set, any downstream async call—like the SQL query above—receives the same trace context, making the entire request traceable in Jaeger, Tempo, or any OTLP‑compatible backend.

If you need to manually propagate context (e.g., when calling a non‑traced library), you can extract the current span and inject it into a header map:

```rust
use opentelemetry::propagation::Injector;
use actix_web::http::header::HeaderMap;

struct HeaderMapInjector<'a>(&'a mut HeaderMap);

impl<'a> Injector for HeaderMapInjector<'a> {
    fn set(&mut self, key: &str, value: String) {
        self.0.insert(key, value.parse().unwrap());
    }
}

// Inside an async fn:
let mut headers = HeaderMap::new();
opentelemetry::global::get_text_map_propagator(|prop| {
    prop.inject_context(&tracing::Span::current().context(), &mut HeaderMapInjector(&mut headers));
});
```

This pattern is essential when you call external services that expect `traceparent` and `tracestate` headers.

## How do I collect Prometheus‑compatible metrics alongside traces?

The short answer: use the `metrics` crate together with `metrics-exporter-prometheus`, and bind the exporter to a dedicated `/metrics` endpoint. The exporter runs its own HTTP server, so you can keep it separate from your main API port.

Add the exporter to `Cargo.toml` (already shown) and start it early in `main`:

```rust
use metrics_exporter_prometheus::{PrometheusBuilder, PrometheusHandle};

#[tokio::main]
async fn main() -> std::io::Result<()> {
    // Start Prometheus exporter on a dedicated port
    let recorder = PrometheusBuilder::new()
        .install_recorder()
        .expect("failed to install Prometheus recorder");
    let prometheus_handle = recorder.handle();

    // Spawn a background task that serves `/metrics`
    tokio::spawn(async move {
        use hyper::{Body, Request, Response, Server};
        use hyper::service::{make_service_fn, service_fn};

        async fn serve_metrics(_: Request<Body>, handle: PrometheusHandle) -> Result<Response<Body>, hyper::Error> {
            let body = Body::from(handle.render());
            Ok(Response::builder()
                .status(200)
                .header("Content-Type", "text/plain; version=0.0.4")
                .body(body)
                .unwrap())
        }

        let make_svc = make_service_fn(move |_| {
            let handle = prometheus_handle.clone();
            async move { Ok::<_, hyper::Error>(service_fn(move |req| serve_metrics(req, handle.clone()))) }
        });

        Server::bind(&([0, 0, 0, 0], METRICS_PORT).into())
            .serve(make_svc)
            .await
            .expect("metrics server failed");
    });

    // …rest of Actix setup from previous section…
}
```

Now you can record metrics anywhere in your code:

```rust
metrics::increment_counter!("http_requests_total", "method" => "GET", "endpoint" => "/users/{id}");
metrics::histogram!("http_request_duration_seconds", duration.as_secs_f64(), "endpoint" => "/users/{id}");
```

Because the `metrics` crate is independent of `tracing`, you still get a single source of truth for observability. The Prometheus endpoint can be scraped by a sidecar or a dedicated Prometheus server, while traces flow to the OTLP collector.

## How should I structure logs so they correlate with traces and metrics?

Answer: emit JSON‑structured logs using `tracing_subscriber::fmt::layer` with the `json` formatter, and include the current trace and span IDs as fields. This makes it trivial for log aggregation platforms (e.g., Loki, Elastic) to join logs with trace data.

Here’s a minimal logger setup:

```rust
use tracing_subscriber::{fmt, EnvFilter};

fn init_logger() {
    let json_layer = fmt::layer()
        .json()
        .with_current_span(true) // adds `span.id`
        .with_span_list(true)    // adds `span.name`
        .with_target(false);

    tracing_subscriber::registry()
        .with(EnvFilter::from_default_env())
        .with(json_layer)
        .init();
}
```

Call `init_logger()` before any async runtime starts. When you log inside a traced function, the output will contain `trace_id` and `span_id` fields automatically injected by the OpenTelemetry propagator:

```json
{
  "timestamp":"2026-11-27T12:34:56.789Z",
  "level":"ERROR",
  "message":"Failed to fetch user",
  "error":"sqlx::Error::RowNotFound",
  "trace_id":"0af3e2c5d1b24f9a9c8d2e5f6a7b8c9d",
  "span_id":"1a2b3c4d5e6f7g8h"
}
```

When you ship these logs to Loki, you can write a query like `{trace_id="0af3e2c5d1b24f9a9c8d2e5f6a7b8c9d"}` to see all log lines that belong to a particular request.

## Decision table: SDK‑only vs. Collector‑sidecar vs. Agent deployment

Below is a concise comparison that helps you decide which deployment model fits a given environment.

| Deployment model | Pros | Cons | Typical use‑case |
|------------------|------|------|------------------|
| **SDK‑only (export directly from process)** | Lowest latency, no extra process, simple Docker image | Requires network access to collector, harder to rotate credentials | Small services, dev environments, low‑traffic APIs |
| **Collector sidecar** | Centralizes config, can batch & retry, isolates credentials | Extra container, more resource usage, needs service mesh or pod‑level sharing | Kubernetes pods, microservice fleets, compliance‑driven pipelines |
| **Agent (host‑level)** | Minimal per‑service changes, can auto‑discover services, reduces per‑pod overhead | Requires host‑level install, less control per service | Large clusters, multi‑language environments, legacy workloads |

I usually start with the SDK‑only approach for a prototype, then move to a sidecar once the service hits production traffic. The OpenTelemetry Collector’s `batch` processor (used in the code above) already mimics sidecar behavior without the extra container, but a dedicated sidecar gives you more flexibility for resource limits and TLS termination.

## Frequently asked questions

### How do I enable TLS for OTLP export in Rust?

Set the endpoint to a secure URL and provide a `tonic::transport::ClientTlsConfig` via the exporter builder:

```rust
let exporter = opentelemetry_otlp::new_exporter()
    .tonic()
    .with_endpoint("https://collector.example.com:SECURE_PORT")
    .with_tls_config(
        tonic::transport::ClientTlsConfig::new()
            .ca_certificate(opentelemetry::tls::Certificate::from_pem(include_bytes!("ca.pem")))
    );
```

### Can I use OpenTelemetry with async‑std instead of Tokio?

Yes. The `opentelemetry-otlp` crate supports both runtimes. Replace `#[tokio::main]` with `#[async_std::main]` and enable the appropriate feature in `opentelemetry-otlp`:

```toml
opentelemetry-otlp = { version = "*", features = ["grpc-async-std"] }
```

### Does the `metrics` crate automatically add trace IDs to exported metrics?

No. Metrics are independent of tracing. If you need correlation, you must manually add the IDs as label dimensions:

```rust
let span = tracing::Span::current();
let ctx = span.context();
metrics::increment_counter!(
    "db_query_total",
    "trace_id" => ctx.trace_id().to_string(),
    "span_id" => ctx.span_id().to_string()
);
```

### How do I avoid double‑counting spans when using both `tracing` and manual OpenTelemetry spans?

Create spans exclusively through `tracing` and let `tracing‑opentelemetry` translate them. If you need a manual OpenTelemetry span, start it with `opentelemetry::global::tracer(...).start(...)` **and** wrap it in a `tracing::Span::current().enter()` block to keep the hierarchy consistent.

## Conclusion

I’ve walked through the full stack—from Cargo dependencies to trace propagation, metric export, and structured logging—so you can bring end‑to‑end observability to any Rust backend API. The next step is to plug this into your existing CI/CD pipeline, verify that traces appear in your chosen backend (Jaeger, Tempo, or a SaaS provider), and iterate on sampling policies. If you need help tailoring the setup to a specific cloud provider or integrating with your existing monitoring stack, feel free to [get in touch](/contact/).  

For deeper dives into API design and versioning, see my related post on [/blog/api-versioning-mastery/](/blog/api-versioning-mastery/). And if you’re looking for a partner to accelerate backend development, check out our [/services/backend-api-development/](/services/backend-api-development/) page.

> Verification note: results depend on your versions, configuration and environment; test in your own setup before relying on them in production.

---

HTML version: https://fullstackweb.dev/blog/rust-opentelemetry-backend/
Maintained by Hendra Nicholas, Senior Full-Stack Software Engineer & AI Engineer, hello@fullstackweb.dev.
