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.
Runtime and HTTP server
| Crate | Use | Links |
|---|---|---|
tokio |
Async runtime | crates.io · lib.rs · GitHub |
axum |
HTTP routing and extractors | crates.io · lib.rs · GitHub |
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.
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 for shutdown_signal.
HTTP client
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.
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 and Retries.
To use the bundled webpki-roots instead of the system store, build a rustls::ClientConfig as in TLS and pass it to ClientBuilder::tls_backend_preconfigured.
Errors
| Crate | Use | Links |
|---|---|---|
thiserror |
Typed errors in libraries | crates.io · lib.rs · GitHub |
anyhow |
Opaque errors in binaries | crates.io · lib.rs · GitHub |
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.
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 |
Derive serialize and deserialize | crates.io · lib.rs · GitHub |
serde_json |
JSON format for serde |
crates.io · lib.rs · GitHub |
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.
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, 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 |
Spans and structured events | crates.io · lib.rs · GitHub |
tracing-subscriber |
Filtering and layer composition | crates.io · lib.rs · GitHub |
tracing-ndjson |
Newline-delimited JSON output | crates.io · lib.rs · GitHub |
prometheus |
Prometheus metrics and exposition | crates.io · lib.rs · GitHub |
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.
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))].