dust

Redis

Introduction

Redis is an open source, in-memory key-value store that supports strings, hashes, lists, sets, and sorted sets, making it a great fit for shared counters, leaderboards, and distributed locks across multiple application servers. dust-framework provides named Redis connections, configured similarly to database connections, on top of the redis crate.

Redis support is enabled through the redis Cargo feature, which is off by default. Enable it in your Cargo.toml:

toml
[dependencies]dust-framework = { version = "0.1", features = ["redis"] }

Without the feature, the dust::redis module is not compiled. Enabling it also allows the cache, sessions, and queues to store their data in Redis.

Redis is a tool, not a database. Use it for the things it is good at:

Need Reach for
A shared cache with automatic expiry The redis cache store
A job queue that survives restarts The redis queue connection
Shared sessions Redis-backed sessions
Counters, leaderboards, and rate windows The command helpers on this page
Locks shared across servers Cache locks
Records you cannot afford to lose Your database

Configuration

Your application's Redis settings live in config.redis, which is also fully compatible with Valkey, including managed dust-framework Valkey on DUST Cloud. It defines two connections: default, which most code uses, and cache, which the cache store uses. Both read the same environment variables, with defaults preconfigured for a local Redis server:

Connection URL Default database
default REDIS_URL, or redis://127.0.0.1:6379 REDIS_DB, or 0
cache REDIS_URL, or redis://127.0.0.1:6379 REDIS_CACHE_DB, or 1

The cache uses its own database, so clearing the cache doesn't erase your application's data. A database in the URL, such as the 2 in redis://redis.internal:6379/2, applies to both connections instead, so leave it out unless you want them to share one.

The URL also holds the scheme, the host, and any credentials. redis:// connects over TCP, rediss:// over TLS, and redis+unix:///run/redis.sock over a Unix socket:

ini
REDIS_URL=rediss://app:secret@redis.internal:6380

Percent-encode the characters that mean something in a URL, such as @, :, /, and #, so the password p@ss becomes p%40ss.

When you need an additional Redis connection beyond default and cache, create a src/config/redis.rs configuration file. Start from Redis::from_env, which already includes those two connections, and add yours. This one adds a reports connection on database 2:

rust
// src/config/redis.rsuse dust::config::redis::{ConnectionConfig, Redis};use dust::config::{self, Env};#[config::section]fn redis(env: &Env) -> Redis {    let mut redis = Redis::from_env(env);    redis.add_connection(        "reports",        ConnectionConfig::new("redis://reports.internal:6379").database(2),    );    redis}

Then add the file to src/config/mod.rs:

rust
mod redis;

By default, connections use a 1-second connect timeout and a 5-second response timeout. You can override either on ConnectionConfig, such as .response_timeout(10.seconds()).

[!WARNING] Queue keys, such as queues:{default}, and the keys you store yourself have no application prefix. If your production and staging environments share a Redis server, give each its own databases with REDIS_DB and REDIS_CACHE_DB. Otherwise one environment's queue workers run the other's jobs.

Clusters

If your application uses a Redis Cluster, list one or more seed nodes in src/config/redis.rs and the client will discover the rest of the topology automatically:

rust
redis.add_connection("sessions", ConnectionConfig::cluster([    "redis://10.0.0.1:6379",    "redis://10.0.0.2:6379",]));

Redis Cluster supports only database 0. Multi-key commands and transactions require all involved keys to live in the same hash slot, so group related keys with a hash tag such as {user:42}:name and {user:42}:email. Cluster connections do not support Pub / Sub or blocking commands.

Running commands

Call everyday Redis commands directly on dust::redis to run them against your default connection. For example, this handler increments a post's view counter and returns the updated count:

rust
use dust::prelude::*;use dust::redis;pub async fn view(Params(id): Params<i64>) -> dust::Result<Json<isize>> {    let views = redis::incr(format!("post:{id}:views"), 1).await?;    Ok(Json(views))}

Each helper returns a concrete Rust type, such as Option<String> for get, Vec<String> for lrange, isize for incr, bool for exists, and HashMap<String, String> for hgetall. Looking up a missing key returns None or an empty collection rather than an error:

rust
redis::set("name", "Taylor").await?;let name = redis::get("name").await?;let names = redis::lrange("names", 5, 10).await?;

Top-level helpers cover strings and keys (get, set, set_ex, set_nx, del, exists, expire, ttl, incr, decr), hashes (hget, hset, hdel, hgetall), lists (lpush, rpush, lpop, rpop, lrange, llen), sets (sadd, srem, smembers, sismember), and sorted sets (zadd, zrem, zrange, zscore). To run any other Redis command on the default connection, import Commands and call it on redis::default_connection()?:

rust
use dust::redis::{self, Commands};let mut redis = redis::default_connection()?;let names = redis.mget(&["user:1:name", "user:2:name"]).await?;let token = redis.get_del("invite:42").await?;

To expire a key automatically, pass a duration such as 5.minutes() to set_ex or expire:

rust
redis::expire("name", 5.minutes()).await?;

Because Redis values are stored as strings, serialize structured Rust types yourself when storing them. For example, these handlers store and retrieve a user's preferences as JSON:

rust
use dust::prelude::*;use dust::redis;use serde::Serialize;#[dust::input]#[derive(Serialize)]pub struct Preferences {    pub theme: String,}pub async fn update(    Params(id): Params<i64>,    Json(preferences): Json<Preferences>,) -> dust::Result<()> {    let json = serde_json::to_string(&preferences)?;    redis::set(format!("user:{id}:preferences"), json).await?;    Ok(())}pub async fn show(Params(id): Params<i64>) -> dust::Result<Json<Option<Preferences>>> {    let json = redis::get(format!("user:{id}:preferences")).await?;    Ok(Json(json.map(|json| serde_json::from_str(&json)).transpose()?))}

Adopt a key convention such as resource:id:field (user:42:preferences, post:7:views) and keep it in one place. Redis has no namespaces, and dust-framework does not prefix your keys, so two applications sharing a server share every key. When environments share a server, give each its own database.

Choosing a connection

Call redis::default_connection() to access the default connection, or redis::connection(name) to access another configured connection:

rust
use dust::redis::{self, Commands};let mut reports = redis::connection("reports")?;reports.hset("report:42", "status", "done").await?;reports.expire("report:42", 3600).await?;

Lookups are cheap and return a lightweight handle to the shared connection, so look connections up wherever you need them rather than storing them on structs. dust-framework waits until your first command to connect to Redis, so you won't see connection errors until a command actually runs.

Other commands and return types

To decode a reply into a different type, such as raw bytes, invoke the command through client::AsyncCommands:

rust
use dust::redis::{self, client::AsyncCommands};let mut redis = redis::default_connection()?;let avatar: Option<Vec<u8>> = AsyncCommands::get(&mut redis, "avatar:42").await?;

For commands without a typed helper method, build the command with command, attach arguments with arg, and await it. Annotate the expected return type, or bind the reply with let () = to ignore it:

rust
let info: String = redis.command("CLIENT").arg("INFO").await?;

Pipelines and transactions

When you need to send many commands to Redis at once, use pipeline to batch them into a single round trip instead of awaiting each command individually. Redis executes pipelined commands in order, though commands from other clients may interleave between them. For example, this pipeline resets the view counters of a thousand posts (calling ignore on each command so its reply is discarded):

rust
use dust::redis;let () = redis::default_connection()?    .pipeline(|pipe| {        for id in 1..=1000 {            pipe.set(format!("post:{id}:views"), 0).ignore();        }    })    .await?;

When your commands must execute atomically without other clients interleaving between them, use transaction instead. It sends all commands in a single MULTI / EXEC block and returns their results as a tuple:

rust
let (user_visits, total_visits): (i64, i64) = redis::default_connection()?    .transaction(|tx| {        tx.incr("user_visits", 1).incr("total_visits", 1);    })    .await?;

Because Redis executes every command in a transaction together after receiving the entire block, one command cannot inspect the result of an earlier command in the same transaction. Use a Lua script when you need conditional logic based on intermediate values.

Lua scripts

Lua scripts execute atomically on the Redis server while allowing you to read values and branch on the results. Pass the script to eval, attach key names with key (exposed as KEYS in Lua) and additional arguments with arg (exposed as ARGV). For example, this script increments one counter and also increments a second counter once the first exceeds five:

rust
use dust::redis;let counter: i64 = redis::default_connection()?    .eval(r#"        local counter = redis.call("incr", KEYS[1])        if counter > 5 then            redis.call("incr", KEYS[2])        end        return counter    "#)    .key("first-counter")    .key("second-counter")    .await?;

To learn more about writing Redis scripts, check out the Redis Lua scripting documentation.

Pub / Sub

Redis Pub / Sub lets one process broadcast messages to any number of listening processes. For example, a handler may publish an event when an order ships so every process subscribed to the orders channel receives it. Call publish with any Serialize value; strings and numbers are sent as plain text, while structs are serialized as JSON:

rust
use dust::redis;use serde::{Deserialize, Serialize};#[derive(Serialize, Deserialize)]pub struct OrderShipped {    pub id: i64,}redis::default_connection()?.publish("orders", OrderShipped { id: 42 }).await?;redis::default_connection()?.publish("news", "We're open").await?;

Calling subscribe opens a dedicated connection and returns an async stream of incoming messages. Because a subscriber listens indefinitely until stopped, run it inside a console command:

rust
use dust::redis;use dust::stream::StreamExt;let mut messages = redis::default_connection()?.subscribe("orders").await?;while let Some(message) = messages.next().await {    let order: OrderShipped = message.json()?;    // Handle the shipped order...}

Each Message provides these methods:

Method Returns
channel() The channel the message was published on
pattern() The pattern it matched for a pattern subscription, or None
body() The raw message bytes as published
text() The message payload as UTF-8 text
json::<T>() The message payload deserialized from JSON

You may pass a slice such as &["orders", "refunds"] to subscribe to multiple channels at once, or call psubscribe("users.*") to subscribe to every channel matching a glob pattern. Dropping the stream unsubscribes automatically.

If a subscription loses its connection, it attempts to reconnect for up to 30 seconds before ending the stream and exiting your while let loop. Because Redis does not buffer messages while a subscriber is disconnected, messages published during a reconnect are lost. For guaranteed delivery, use a queue instead.

Blocking commands

By default, every request shares a single multiplexed connection per named Redis connection. Running a blocking command such as BLPOP on that shared connection would stall other requests waiting on it, and WATCH would interfere with other requests' transactions. Run blocking commands on a dedicated connection instead.

For example, this worker waits up to 5 seconds for an item on the uploads list, returning the list name and item or None on timeout:

rust
use dust::redis::{self, Commands};let mut worker = redis::default_connection()?.dedicated().await?;let upload: Option<[String; 2]> = worker.blpop("uploads", 5.0).await?;

dedicated opens a standalone connection to the same server and database with no response timeout and closes it when dropped. Dedicated connections do not reconnect automatically, so open a new one if an error occurs.

Failure modes

Symptom Likely cause What to do
connection refused The server is down, or the URL is wrong Check the URL; the next command opens a fresh connection
A command hangs until the response timeout The server is slow or the network stalls Raise response_timeout for that connection, or investigate the server
WRONGTYPE The key already holds a different Redis type Use a distinct key name; do not reuse a key across data shapes
OOM command not allowed The server reached maxmemory with no eviction Free keys or configure an eviction policy
A cluster command fails on multiple keys The keys live in different hash slots Group them with a hash tag such as {user:42}:name
Other requests stall behind one command A blocking command ran on the shared connection Use dedicated()
A subscriber misses messages It lost its connection and Redis does not buffer Use a queue when delivery must be guaranteed

Lost connections

When Redis restarts or fails over, dust-framework automatically opens a fresh connection on the next command. Read commands such as GET that were in flight when the connection dropped are retried once, while write commands return an error because the server may already have executed them.

Some Redis servers and proxies close idle connections. If the server hasn't answered for over five seconds, dust-framework sends a PING before the next command. If the connection is lost, dust-framework opens a new one before sending the command.

Adding connections at runtime

When a Redis connection's URL is not known until startup, such as a connection loaded from your database, you may add or replace connections inside a booted hook in src/app.rs:

rust
use dust::config::redis::ConnectionConfig;use dust::redis::RedisManager;Application::configure().booted(async |app| {    app.resolve::<RedisManager>().await?.add_connection(        "reports",        ConnectionConfig::new("redis://reports.internal:6379"),    );    Ok(())});

You can also call redis::manager().add_connection(..) and redis::manager().remove_connection(..) directly from handlers or console commands. Any requests already using a replaced or removed connection will finish normally, and the old connection closes once they're done. Because registered connections stay in memory until removed, be sure to call remove_connection when retiring dynamic connections such as per-tenant servers.