Crates for the data a service stores, caches, and moves: SQL access, time, identifiers, caches, encodings, and non-cryptographic randomness.
Database
| Crate | Use | Links |
|---|---|---|
sqlx |
Async SQL with compile-time checks | crates.io · lib.rs · GitHub |
tokio-postgres |
Low-level async Postgres client | crates.io · lib.rs · GitHub |
sqlx is the default. It ships a connection pool, a migration runner, and query! macros that type-check SQL against the schema at compile time, for Postgres, MySQL, and SQLite.
#[derive(Debug)]
struct User {
id: uuid::Uuid,
email: String,
created_at: jiff_sqlx::Timestamp,
}
let user = sqlx::query_as!(
User,
r#"SELECT id, email, created_at AS "created_at: jiff_sqlx::Timestamp" FROM users WHERE id = $1"#,
id
)
.fetch_optional(&pool)
.await?;The macros need a database at build time. Run cargo sqlx prepare, commit the .sqlx/ directory, and set SQLX_OFFLINE=true in CI so builds use the cached query metadata.
Use tokio-postgres for a Postgres-only service that needs pipelining, COPY, or control over statement preparation. It has no pool; pair it with deadpool-postgres.
See Postgres and Migrations.
Date and time
| Crate | Use | Links |
|---|---|---|
jiff |
Time zone aware date and time | crates.io · lib.rs · GitHub |
jiff-sqlx |
sqlx encode and decode for jiff |
crates.io · lib.rs · GitHub |
chrono |
Date and time, widest ecosystem | crates.io · lib.rs · GitHub |
time |
Date and time, small API surface | crates.io · lib.rs · GitHub |
Default to jiff. IANA time zones, DST-safe arithmetic, and calendar spans are first-class types, and RFC 3339 and RFC 9557 parsing and formatting are built in.
use jiff::{Timestamp, ToSpan, ZonedDateTime};
let now = Timestamp::now();
let local: ZonedDateTime = now.in_tz("America/Vancouver")?;
let same_time_next_week = local.checked_add(7.days())?; // DST-safeStore and transmit Timestamp, and convert to ZonedDateTime only where a human-facing time zone applies. See Timestamps.
sqlx has no built-in jiff support. jiff-sqlx provides wrapper types (jiff_sqlx::Timestamp, Date, DateTime, Span): override the column type in the query as shown above, then call .to_jiff(), and call .to_sqlx() from the ToSqlx trait when binding. It deliberately has no ZonedDateTime wrapper, because Postgres timestamptz stores an instant and would silently drop the zone.
Use chrono or time when a dependency exposes its types in a public API. sqlx supports both directly through its chrono and time features. tokio-postgres supports jiff only through with-jiff-0_2, which targets the pre-1.0 release.
Identifiers and buffers
| Crate | Use | Links |
|---|---|---|
uuid |
Generate and parse UUIDs | crates.io · lib.rs · GitHub |
bytes |
Reference-counted byte buffers | crates.io · lib.rs · GitHub |
Each UUID version is behind a feature flag. Use Uuid::now_v7() for primary keys: the timestamp prefix keeps B-tree inserts close to append-only. See Identities.
Bytes::clone bumps a reference count instead of copying, and slice returns a view into the same allocation. Use Bytes for payloads shared across tasks or handed to hyper and axum bodies, both of which take it without a copy.
Caching and shared state
| Crate | Use | Links |
|---|---|---|
moka |
Bounded concurrent cache | crates.io · lib.rs · GitHub |
dashmap |
Sharded concurrent map | crates.io · lib.rs · GitHub |
Use moka when entries need a size bound, a TTL, or an idle timeout. The async cache lives behind the future feature. get_with coalesces concurrent misses on the same key into one load, which prevents a stampede on a cold entry.
use moka::future::Cache;
use std::{sync::Arc, time::Duration};
let users: Cache<uuid::Uuid, Arc<User>> = Cache::builder()
.max_capacity(10_000)
.time_to_live(Duration::from_secs(300))
.build();
// try_get_with does not cache the error; the next caller retries the load.
let user: Arc<User> = users
.try_get_with(id, async { load_user(&pool, id).await.map(Arc::new) })
.await?;The error comes back as Arc<E> because every coalesced waiter receives the same one. Store Arc<V> for anything larger than a few words: every read clones the value out of the cache.
Use dashmap for an unbounded map with no eviction, such as a registry of live connections or subscriptions.
Encoding
| Crate | Use | Links |
|---|---|---|
base64 |
Base64 encode and decode | crates.io · lib.rs · GitHub |
hex |
Hex encode and decode | crates.io · lib.rs · GitHub |
base64 has no default alphabet: every call goes through an explicit engine, which forces the padding and alphabet choice to be visible at the call site.
use base64::prelude::*;
// Tokens, cursors, and anything placed in a URL or header
let token = BASE64_URL_SAFE_NO_PAD.encode(bytes);
let bytes = BASE64_URL_SAFE_NO_PAD.decode(&token)?;
// MIME, PEM bodies, and specs that call for RFC 4648 section 4
let body = BASE64_STANDARD.encode(bytes);
// Digests in logs, ETags, and fixtures
let etag = hex::encode(digest.as_ref());Decoding is strict: a padded input fails against a NO_PAD engine and the reverse. Match the engine to what the producer emits, and use URL-safe without padding for every value this service generates, as in the pagination cursors. For base32 or other alphabets, use data-encoding (lib.rs, GitHub).
Random numbers
Split randomness by purpose. Keys, tokens, nonces, and salts come from aws_lc_rs::rand::fill (see Cryptography). rand covers the rest: retry jitter, sampling, shuffling, test data.
rand 0.10 moved the user-facing methods (random, random_range, random_bool, fill) to the RngExt trait. One-off draws use the free functions, which run on the thread-local generator:
use rand::seq::SliceRandom;
use rand::RngExt;
use std::time::Duration;
// Full jitter for a retry backoff
let delay = Duration::from_millis(rand::random_range(0..=base.as_millis() as u64));
// Several draws from one generator
let mut rng = rand::rng();
let sampled = rng.random_bool(0.01);
endpoints.shuffle(&mut rng);rand::rng() returns a ThreadRng, which is !Send. Holding it across an .await makes the future !Send and tokio::spawn rejects it; draw the values first, then await. For reproducible tests, seed a StdRng with SeedableRng::seed_from_u64 instead of using the thread-local generator. See Retries for the jitter strategy.