Redis & Key-Value
Use Redis for caches, rate-limit counters, pub/sub, and ephemeral session state alongside your primary SQL database.
Busca en todas las páginas de la documentación
Use Redis for caches, rate-limit counters, pub/sub, and ephemeral session state alongside your primary SQL database.
Quick-reference recipe card - copy-paste ready.
use redis::AsyncCommands;
let client = redis::Client::open(redis_url)?;
let mut conn = client.get_multiplexed_async_connection().await?;
let _: () = conn.set_ex("user:1:session", session_id, 3600).await?;
let cached: Option<String> = conn.get("user:1:profile").await?;When to reach for this: Read-heavy hot keys, TTL-based eviction, distributed locks, or cross-instance pub/sub - not primary source of truth for money.
use redis::AsyncCommands;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct Profile { name: String }
async fn cached_profile(
conn: &mut redis::aio::MultiplexedConnection,
user_id: u64,
loader: impl FnOnce() -> Profile,
) -> redis::RedisResult<Profile> {
let key = format!("profile:{user_id}");
if let Ok(json) = conn.get::<_, String>(&key).await {
if let Ok(p) = serde_json::from_str(&json) {
return Ok(p);
}
}
let profile = loader();
let _: () = conn.set_ex(&key, serde_json::to_string(&profile).unwrap(), 300).await?;
Ok(profile)
}What this demonstrates:
redis crate.set_ex with TTL.| Pattern | Redis type | Use |
|---|---|---|
| Cache | String (JSON) | Profile, config |
| Rate limit | String INCR | Per-IP counters |
| Lock | String SET NX | Short critical sections |
| Queue | List / Stream | Simple job buffer |
| Pub/Sub | Channels | Cache invalidation fan-out |
// fred or deadpool-redis for connection pooling at scale| Alternative | Use When | Don't Use When |
|---|---|---|
| In-process moka cache | Single instance, microsecond latency | Multi-instance consistency needed |
| Memcached | Simple TTL cache only | Pub/sub, structures, persistence |
| PostgreSQL UNLOGGED | Small team, one database | Dedicated cache tier already exists |
redis crate with async features; fred for cluster-heavy setups.
deadpool-redis or multiplexed connection per process.
Use cluster-aware client; hash tags for multi-key ops.
rediss:// URL with rustls feature on client.
JSON for debuggability; MessagePack for size at scale.
Pub/sub channel or version suffix in key on writes.
INCR with EXPIRE window - see Rate Limiting page.
Random session ID key with TTL; store user ID as value.
testcontainers Redis module or embedded mock implementing trait.
Track key patterns per user; delete by SCAN prefix on account erasure.
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 19 jul 2026