---
title: "Data crates"
description: "Database, date and time, identifier, caching, encoding, and randomness 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.

# Data crates

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`](https://docs.rs/sqlx)                     | Async SQL with compile-time checks | [crates.io](https://crates.io/crates/sqlx) · [lib.rs](https://lib.rs/crates/sqlx) · [GitHub](https://github.com/launchbadge/sqlx)                                |
| [`tokio-postgres`](https://docs.rs/tokio-postgres) | Low-level async Postgres client    | [crates.io](https://crates.io/crates/tokio-postgres) · [lib.rs](https://lib.rs/crates/tokio-postgres) · [GitHub](https://github.com/rust-postgres/rust-postgres) |

`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.

```rust
#[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](https://codex.mirio.dev/databases/postgres/) and [Migrations](https://codex.mirio.dev/databases/migrations/).

## Date and time

| Crate                                    | Use                                 | Links                                                                                                                                      |
| ---------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| [`jiff`](https://docs.rs/jiff)           | Time zone aware date and time       | [crates.io](https://crates.io/crates/jiff) · [lib.rs](https://lib.rs/crates/jiff) · [GitHub](https://github.com/BurntSushi/jiff)           |
| [`jiff-sqlx`](https://docs.rs/jiff-sqlx) | `sqlx` encode and decode for `jiff` | [crates.io](https://crates.io/crates/jiff-sqlx) · [lib.rs](https://lib.rs/crates/jiff-sqlx) · [GitHub](https://github.com/BurntSushi/jiff) |
| [`chrono`](https://docs.rs/chrono)       | Date and time, widest ecosystem     | [crates.io](https://crates.io/crates/chrono) · [lib.rs](https://lib.rs/crates/chrono) · [GitHub](https://github.com/chronotope/chrono)     |
| [`time`](https://docs.rs/time)           | Date and time, small API surface    | [crates.io](https://crates.io/crates/time) · [lib.rs](https://lib.rs/crates/time) · [GitHub](https://github.com/time-rs/time)              |

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.

```rust
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-safe
```

Store and transmit `Timestamp`, and convert to `ZonedDateTime` only where a human-facing time zone applies. See [Timestamps](https://codex.mirio.dev/databases/table-design/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`](https://docs.rs/uuid)   | Generate and parse UUIDs       | [crates.io](https://crates.io/crates/uuid) · [lib.rs](https://lib.rs/crates/uuid) · [GitHub](https://github.com/uuid-rs/uuid)     |
| [`bytes`](https://docs.rs/bytes) | Reference-counted byte buffers | [crates.io](https://crates.io/crates/bytes) · [lib.rs](https://lib.rs/crates/bytes) · [GitHub](https://github.com/tokio-rs/bytes) |

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](https://codex.mirio.dev/databases/table-design/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`](https://docs.rs/moka)       | Bounded concurrent cache | [crates.io](https://crates.io/crates/moka) · [lib.rs](https://lib.rs/crates/moka) · [GitHub](https://github.com/moka-rs/moka)           |
| [`dashmap`](https://docs.rs/dashmap) | Sharded concurrent map   | [crates.io](https://crates.io/crates/dashmap) · [lib.rs](https://lib.rs/crates/dashmap) · [GitHub](https://github.com/xacrimon/dashmap) |

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.

```rust
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.

:::caution
A `dashmap` `Ref` or `RefMut` holds a synchronous shard lock. Holding one across an `.await`
blocks every other task that touches the same shard and can deadlock the runtime. Clone the value
out, or scope the guard so it drops before the next `.await`.
:::

## Encoding

| Crate                              | Use                      | Links                                                                                                                                           |
| ---------------------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| [`base64`](https://docs.rs/base64) | Base64 encode and decode | [crates.io](https://crates.io/crates/base64) · [lib.rs](https://lib.rs/crates/base64) · [GitHub](https://github.com/marshallpierce/rust-base64) |
| [`hex`](https://docs.rs/hex)       | Hex encode and decode    | [crates.io](https://crates.io/crates/hex) · [lib.rs](https://lib.rs/crates/hex) · [GitHub](https://github.com/KokaKiwi/rust-hex)                |

`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.

```rust
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](https://codex.mirio.dev/web/rest-apis/pagination/). For base32 or other alphabets, use [`data-encoding`](https://crates.io/crates/data-encoding) ([lib.rs](https://lib.rs/crates/data-encoding), [GitHub](https://github.com/ia0/data-encoding)).

## Random numbers

| Crate                          | Use                                        | Links                                                                                                                             |
| ------------------------------ | ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |
| [`rand`](https://docs.rs/rand) | Ranges, sampling, shuffling, seedable RNGs | [crates.io](https://crates.io/crates/rand) · [lib.rs](https://lib.rs/crates/rand) · [GitHub](https://github.com/rust-random/rand) |

Split randomness by purpose. Keys, tokens, nonces, and salts come from `aws_lc_rs::rand::fill` (see [Cryptography](https://codex.mirio.dev/rust/crates/security/#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:

```rust
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](https://codex.mirio.dev/reliability/retries/) for the jitter strategy.

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