---
title: "Core crates"
description: "Runtime, HTTP server and client, errors, serialization, and observability crates for Rust services."
---

> Documentation Index
> Fetch the complete documentation index at: https://codex.mirio.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Core crates

The crates every service touches: the runtime and HTTP stack, error types, serialization, and instrumentation. Feature flags for all of them are in the [combined Cargo.toml](https://codex.mirio.dev/rust/crates/#cargotoml).

## Runtime and HTTP server

| Crate                            | Use                         | Links                                                                                                                             |
| -------------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| [`tokio`](https://docs.rs/tokio) | Async runtime               | [crates.io](https://crates.io/crates/tokio) · [lib.rs](https://lib.rs/crates/tokio) · [GitHub](https://github.com/tokio-rs/tokio) |
| [`axum`](https://docs.rs/axum)   | HTTP routing and extractors | [crates.io](https://crates.io/crates/axum) · [lib.rs](https://lib.rs/crates/axum) · [GitHub](https://github.com/tokio-rs/axum)    |

`axum` is a thin layer over `hyper` and `tower`, so any `tower` middleware applies directly; `tower-http` supplies tracing, timeouts, CORS, and compression layers. Enable Tokio features individually rather than `full`, which compiles `fs`, `process`, and `io-std` into every service.

```rust
use axum::{routing::get, Router};
use std::sync::Arc;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let state = Arc::new(AppState::new().await?);

    let app = Router::new()
        .route("/users/{id}", get(get_user))
        .with_state(state);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await?;
    axum::serve(listener, app)
        .with_graceful_shutdown(shutdown_signal())
        .await?;
    Ok(())
}
```

Path parameters use `{id}` in `axum` 0.8; the `:id` syntax from 0.7 panics at router construction. See [Graceful shutdown](https://codex.mirio.dev/reliability/graceful-shutdown/) for `shutdown_signal`.

## HTTP client

| Crate                                | Use               | Links                                                                                                                                      |
| ------------------------------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| [`reqwest`](https://docs.rs/reqwest) | Async HTTP client | [crates.io](https://crates.io/crates/reqwest) · [lib.rs](https://lib.rs/crates/reqwest) · [GitHub](https://github.com/seanmonstar/reqwest) |

`reqwest` 0.13 defaults to `rustls` with `aws-lc-rs` and verifies certificates against the operating system trust store through `rustls-platform-verifier`. The default `system-proxy` feature honors `HTTP_PROXY` and `HTTPS_PROXY`. Response `.json()` needs the `json` feature.

```rust
use secrecy::ExposeSecret;
use std::time::Duration;

let client = reqwest::Client::builder()
    .connect_timeout(Duration::from_secs(2))
    .timeout(Duration::from_secs(10))
    .pool_idle_timeout(Duration::from_secs(90))
    .user_agent(concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")))
    .build()?;

let user: User = client
    .get(format!("{base_url}/users/{id}"))
    .bearer_auth(api_token.expose_secret())
    .send()
    .await?
    .error_for_status()?
    .json()
    .await?;
```

A `Client` holds the connection pool and is an `Arc` internally. Build one at startup, store it in application state, and clone it into tasks; a client per request pays a TCP and TLS handshake every time.

`reqwest` sets no request timeout by default. `timeout` is the deadline for the whole exchange, body included; `connect_timeout` bounds the connect and TLS handshake separately so a dead host fails fast. A non-2xx status is not an error until `error_for_status` turns it into one. See [Timeouts](https://codex.mirio.dev/reliability/timeouts/) and [Retries](https://codex.mirio.dev/reliability/retries/).

To use the bundled `webpki-roots` instead of the system store, build a `rustls::ClientConfig` as in [TLS](https://codex.mirio.dev/rust/crates/security/#client) and pass it to `ClientBuilder::tls_backend_preconfigured`.

## Errors

| Crate                                    | Use                       | Links                                                                                                                                        |
| ---------------------------------------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| [`thiserror`](https://docs.rs/thiserror) | Typed errors in libraries | [crates.io](https://crates.io/crates/thiserror) · [lib.rs](https://lib.rs/crates/thiserror) · [GitHub](https://github.com/dtolnay/thiserror) |
| [`anyhow`](https://docs.rs/anyhow)       | Opaque errors in binaries | [crates.io](https://crates.io/crates/anyhow) · [lib.rs](https://lib.rs/crates/anyhow) · [GitHub](https://github.com/dtolnay/anyhow)          |

Use `thiserror` where a caller matches on the variant: library crates and a service's domain layer. Use `anyhow` where the error is only logged or turned into a 500: `main`, background jobs, CLI entry points.

```rust
use anyhow::Context;

#[derive(Debug, thiserror::Error)]
pub enum UserError {
    #[error("user {0} not found")]
    NotFound(uuid::Uuid),
    #[error(transparent)]
    Database(#[from] sqlx::Error),
}

async fn run(config: &Config) -> anyhow::Result<()> {
    let pool = sqlx::PgPool::connect(&config.database_url)
        .await
        .context("connecting to postgres")?;
    sqlx::migrate!().run(&pool).await.context("running migrations")?;
    Ok(())
}
```

Add `.context(...)` at each `?` that crosses a subsystem boundary. Format with `{:#}` for a one-line chain or `{:?}` for the multi-line chain, which includes a backtrace when `RUST_BACKTRACE=1`.

## Serialization

| Crate                                      | Use                              | Links                                                                                                                                      |
| ------------------------------------------ | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| [`serde`](https://docs.rs/serde)           | Derive serialize and deserialize | [crates.io](https://crates.io/crates/serde) · [lib.rs](https://lib.rs/crates/serde) · [GitHub](https://github.com/serde-rs/serde)          |
| [`serde_json`](https://docs.rs/serde_json) | JSON format for `serde`          | [crates.io](https://crates.io/crates/serde_json) · [lib.rs](https://lib.rs/crates/serde_json) · [GitHub](https://github.com/serde-rs/json) |

Keep request and response types separate from database rows and domain types, even when the fields match today. The wire format then changes only when the type annotated for it changes.

```rust
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CreateUser {
    pub email: String,
    #[serde(default)]
    pub display_name: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct UserResponse {
    pub id: uuid::Uuid,
    pub email: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    pub created_at: jiff::Timestamp,
}
```

Rust field names are already `snake_case`, which matches the JSON conventions in [Endpoints](https://codex.mirio.dev/web/rest-apis/endpoints/), so no `rename_all` is needed. `deny_unknown_fields` turns a misspelled field in a request into a 400 instead of a silently ignored value; leave it off response types a client deserializes, so new fields stay backward compatible. `jiff::Timestamp` and `uuid::Uuid` serialize as RFC 3339 and hyphenated strings through their `serde` features.

`axum::Json<T>` uses `serde_json` for both extraction and responses. Reach for `serde_json::Value` only for payloads with no fixed shape, such as stored webhook bodies.

## Observability

| Crate                                                      | Use                               | Links                                                                                                                                                                                      |
| ---------------------------------------------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [`tracing`](https://docs.rs/tracing)                       | Spans and structured events       | [crates.io](https://crates.io/crates/tracing) · [lib.rs](https://lib.rs/crates/tracing) · [GitHub](https://github.com/tokio-rs/tracing)                                                    |
| [`tracing-subscriber`](https://docs.rs/tracing-subscriber) | Filtering and layer composition   | [crates.io](https://crates.io/crates/tracing-subscriber) · [lib.rs](https://lib.rs/crates/tracing-subscriber) · [GitHub](https://github.com/tokio-rs/tracing/tree/main/tracing-subscriber) |
| [`tracing-ndjson`](https://docs.rs/tracing-ndjson)         | Newline-delimited JSON output     | [crates.io](https://crates.io/crates/tracing-ndjson) · [lib.rs](https://lib.rs/crates/tracing-ndjson) · [GitHub](https://github.com/cmackenzie1/tracing-ndjson)                            |
| [`prometheus`](https://docs.rs/prometheus)                 | Prometheus metrics and exposition | [crates.io](https://crates.io/crates/prometheus) · [lib.rs](https://lib.rs/crates/prometheus) · [GitHub](https://github.com/tikv/rust-prometheus)                                          |

`tracing` is the instrumentation API that libraries call. `tracing-subscriber` decides which events are kept and where they go, and `tracing-ndjson` is the output layer that writes one JSON object per line for a log shipper. `EnvFilter` needs the `env-filter` feature.

```rust
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};

tracing_subscriber::registry()
    .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")))
    .with(tracing_ndjson::layer())
    .init();
```

`#[tracing::instrument]` records every argument with `Debug` unless skipped. Skip state, connection pools, request bodies, and anything holding a secret: `#[tracing::instrument(skip_all, fields(user_id = %id))]`.

Cross-language patterns: [Logging](https://codex.mirio.dev/observability/logging/), [Metrics](https://codex.mirio.dev/observability/metrics/), [Tracing](https://codex.mirio.dev/observability/tracing/).

Source: https://codex.mirio.dev/rust/crates/core/index.mdx
