Cache
- Introduction
- Configuration
- Using the cache
- Atomic locks
- Logging
- Failure modes and limits
- Custom drivers
- Testing
Introduction
Some of the work your application performs can be slow or expensive, such as generating a multi-second report or calling a rate-limited external API. When that data doesn't change on every request, you can cache it for a period of time so subsequent requests read the stored value instead of repeating the work.
dust-framework provides a single, unified API across every cache backend, allowing you to start with the in-memory store and move to a database or Redis without changing your application code. For example, this dashboard handler counts users at most once every 10 minutes:
use dust::cache;use dust::prelude::*;use crate::models::User;pub async fn show() -> dust::Result<String> { let users: u64 = cache::remember("users:count", 10.minutes(), async || { User::query().count().await }) .await?; Ok(format!("{users} users"))}Configuration
The CACHE_STORE environment variable selects the default store used by the functions in dust::cache. dust-framework includes several built-in stores:
| Store | Storage |
|---|---|
memory |
In each process's memory for the lifetime of the process. dust-framework uses it when CACHE_STORE isn't set. |
database |
In a shared database table configured for the database store. |
redis |
In a shared Redis server configured for the Redis store. |
failover |
In the database store, falling back to memory when failing over. |
discard |
Nowhere. Every read misses, effectively disabling caching. |
| Store | Shared across servers | Survives a restart | Atomic locks | Best for |
|---|---|---|---|---|
memory |
No | No | In-process only | Local development and tests |
database |
Yes | Yes | Yes | Applications that already have a database |
redis |
Yes | Yes | Yes | High-traffic caches and locks |
failover |
Yes, for the first store | Yes, for the first store | First store only | Staying up when the primary store fails |
discard |
No | No | No | Disabling caching in an environment |
New applications use the database store, so every process and server shares cached data:
CACHE_STORE=databaseThe memory store works well when your application runs on a single server and doesn't need its cache to survive a restart.
CACHE_PREFIX is prepended to every cache key so multiple applications sharing a store don't collide. It defaults to a prefix derived from your application's name, such as my_app_cache_.
The database store
The database store keeps cached values in a cache table and atomic locks in a cache_locks table. New applications create both tables in their create_cache_table migration, which holds only the cache::tables! macro:
// database/migrations/0001_01_01_000001_create_cache_table.rsdust::cache::tables!();Run your migrations before using the database store:
dust migrateBy default, the database store uses your default database connection. You may point it at another connection or table using DB_CACHE_CONNECTION and DB_CACHE_TABLE, and customize locks independently with DB_CACHE_LOCK_CONNECTION and DB_CACHE_LOCK_TABLE. If you rename a table, replace the macro with the migration it stands for and change the table names to match:
// database/migrations/0001_01_01_000001_create_cache_table.rsuse dust::db::AnyTransaction;pub async fn migrate(tx: &mut AnyTransaction<'_>) -> dust::Result<()> { tx.schema() .create("cache", |table| { table.string("key").primary(); table.medium_text("value"); table.timestamp("expiration").index(); }) .await?; tx.schema() .create("cache_locks", |table| { table.string("key").primary(); table.string("owner"); table.timestamp("expiration").index(); }) .await}dust-framework automatically prunes expired rows roughly once an hour, so no scheduled task is required. To prune expired entries immediately, run cache:prune (passing an optional store name to target a specific store):
dust cache:prunedust cache:prune reports[!NOTE] Inside a database transaction on the store's connection, cache writes participate in the transaction and roll back if the transaction fails. To keep cache writes independent of your transactions, assign the cache store a separate connection via
DB_CACHE_CONNECTION.
The Redis store
The redis store keeps cached values on the cache Redis connection and locks on the default connection. It is also fully compatible with Valkey, including managed dust-framework Valkey on DUST Cloud. After enabling dust-framework's redis Cargo feature (covered in the Redis guide), select the redis store in your .env file:
CACHE_STORE=redisUse REDIS_CACHE_CONNECTION and REDIS_CACHE_LOCK_CONNECTION if you want to route values or locks to different Redis connections. Redis expires keys automatically, so no pruning is needed.
[!WARNING] Flushing the
redisstore deletes every key in that connection's Redis database, regardless of prefix. Keep thecacheconnection on its own Redis database, as the default configuration does. When values and locks share a database (such as on a cluster), a cached value and a lock with the same name share the same Redis key, so give them distinct names.
Failing over
If your primary cache store becomes unavailable, requests that read or write the cache will fail unless you configure failover. A failover store tries a list of stores in order, falling back to the next store whenever an operation fails. The built-in failover store tries database first, then memory:
CACHE_STORE=failoverTo fail over between other stores, define a custom failover store:
cache.add_store("failover", StoreConfig::failover(["redis", "database"]));dust-framework logs a warning whenever a store starts failing. Values are not copied between stores during failover, and atomic locks never fail over: locks always target the first store in the list so locking fails cleanly while that store is down.
Defining your own stores
Most applications only need the built-in stores. When you need an additional store, such as a dedicated table for cached reports, create a src/config/cache.rs configuration file starting from Cache::from_env and add your store:
// src/config/cache.rsuse dust::config::cache::{Cache, DatabaseStore};use dust::config::{self, Env};#[config::section]fn cache(env: &Env) -> Cache { let mut cache = Cache::from_env(env); cache.add_store( "reports", DatabaseStore::new() .connection("reporting") .table("report_cache"), ); cache}Register the module in src/config/mod.rs:
mod cache;You can then access the store by name using cache::store("reports").
Using the cache
The top-level functions in dust::cache operate on your default cache store. To interact with another store, call cache::store with the store's name; it returns a repository with the same methods:
use dust::cache;let report: Option<String> = cache::store("reports")?.get("monthly").await?;You may use the cache from handlers, middleware, console commands, queued jobs, and anywhere else your application runs. If you spawn your own async task and want to access the cache inside it, use dust::task::spawn rather than tokio::spawn.
Retrieving items
Use cache::get to retrieve a value as the requested type. If the key is missing or expired, get returns None. You may check whether a key exists using cache::has:
use dust::cache;let name: Option<String> = cache::get("user:42:name").await?;if cache::has("user:42:name").await? { // ...}To retrieve a value and immediately remove it from the cache, use cache::pull:
let token: Option<String> = cache::pull("invite:42").await?;To fetch several keys in a single call, use cache::many, which returns values in the same order as the requested keys:
let names: Vec<Option<String>> = cache::many(["user:1:name", "user:2:name"]).await?;Retrieve and store
Frequently, you'll want to read an item from the cache and compute it when it's missing. cache::remember handles both in one call: it returns the cached value if present, or runs your closure and stores the returned value for the given duration. For example, this caches published post titles for an hour:
use dust::cache;use dust::prelude::*;use crate::models::Post;let titles: Vec<String> = cache::remember("posts:titles", 1.hour(), async || { Post::query() .filter(!Post::published_at.is_null()) .pluck(Post::title) .await}).await?;Because the closure returns a dust::Result, you may use ? inside it. If the closure returns an error, remember propagates the error without caching anything.
If several concurrent requests miss the cache at the same time, each runs the closure. When the work should only run once at a time, coordinate it with an atomic lock.
Stale while revalidate
With remember, the first request that sees an expired entry must wait while the closure recomputes it. For slow queries or API calls, cache::flexible avoids that latency spike by serving the stale value immediately while refreshing it in the background. Pass both the fresh duration and the total grace duration:
use dust::cache;use dust::prelude::*;use crate::models::Post;let posts: u64 = cache::flexible("posts:count", 5.minutes(), 10.minutes(), async || { Post::query().count().await}).await?;For the first 5 minutes, flexible returns the cached value directly. Between 5 and 10 minutes, it returns the stale value immediately while managed background work recomputes the fresh value so the request doesn't block. After 10 minutes, the entry expires and the next request recomputes it inline like remember.
Because the closure may execute after the HTTP response is sent, move or clone any captured data into the closure.
Storing items
Use cache::put to store a value for a given lifetime. Every cached item requires an expiration duration, so give values that rarely change a longer lifetime:
use dust::cache;use dust::prelude::*;use serde_json::json;cache::put("user:42:name", "Taylor", 10.minutes()).await?;cache::put("settings", json!({ "theme": "dark" }), 1.day()).await?;Values are serialized as JSON, so you may store any type implementing Serialize and read it back as any type implementing Deserialize. If get finds a stored value that cannot deserialize into the requested type, it returns an error rather than None. By contrast, remember and flexible treat incompatible cached values as a miss and recompute them, so deploys that change a struct's shape recover gracefully.
Use cache::add to store a value only if the key does not already exist. The check and write happen atomically, returning true if the value was stored and false if another request beat it:
if cache::add("report:monthly:started", true, 10.minutes()).await? { // This request generates the report...}Use cache::put_many to store several key-value pairs with a shared lifetime, and cache::touch to extend an existing key's lifetime without rewriting its value:
cache::put_many([("user:1:name", "Taylor"), ("user:2:name", "Abigail")], 10.minutes()).await?;cache::touch("report:monthly", 30.minutes()).await?;Counters
Use cache::increment_or_add to increment an integer counter, creating it with the given initial amount and lifetime if it doesn't exist yet, and returning the new value. For example, this counts a client's requests within a one-minute window:
use dust::cache;use dust::prelude::*;let hits = cache::increment_or_add("hits:203.0.113.7", 1, 1.minute()).await?;cache::increment and cache::decrement adjust an existing counter without changing its expiration, returning None if the key does not exist:
let visits: Option<i64> = cache::increment("visits", 1).await?;let remaining: Option<i64> = cache::decrement("credits", 1).await?;Removing items
Use cache::forget to remove a single key, or cache::flush to clear every entry in the store:
use dust::cache;cache::forget("user:42:name").await?;cache::flush().await?;You may also flush the default store, or a specific store by name, using the cache:clear command:
dust cache:cleardust cache:clear reportsEach running process keeps a separate memory store, so cache:clear cannot clear the in-memory cache of a running web server. Restart the server to clear a memory store instead.
[!WARNING] Flushing ignores
CACHE_PREFIX. Flushing adatabasestore empties the entire cache table, including entries written by other applications sharing that table.
Memoizing reads
When a single request reads the same cache key multiple times, such as a configuration value needed across several components, cache::memo() avoids redundant round trips to the store. It wraps the default store and keeps read results in memory for the remainder of the current request:
use dust::cache;let cache = cache::memo()?;let theme: Option<String> = cache.get("settings:theme").await?; // Reads the store...let theme: Option<String> = cache.get("settings:theme").await?; // Served from memory...To memoize another store, call .memo() on it, such as cache::store("reports")?.memo(). Writing or forgetting a key clears its memoized entry so the request always sees its own writes.
Atomic locks
Atomic locks allow you to coordinate distributed work so only one process executes a critical section at a time, such as generating an expensive report requested simultaneously by multiple users. Locks on the database and redis stores are shared across all processes and servers. Locks on the memory store only coordinate within a single process, and the discard store does not enforce locks.
Managing locks
Call cache::lock with a lock name and a maximum duration to hold the lock. Calling acquire attempts to claim the lock immediately and returns true if successful:
use dust::cache;use dust::prelude::*;let lock = cache::lock("reports", 10.seconds())?;if lock.acquire().await? { // Lock acquired for 10 seconds... lock.release().await?;}Alternatively, pass a closure to get. dust-framework acquires the lock, runs your closure, and automatically releases the lock afterward, even if the closure returns an error. If another process already holds the lock, get returns None without running the closure:
let sent: Option<()> = cache::lock("invoices", 2.minutes())? .get(async || { // Send the invoices... Ok(()) }) .await?;If the lock is unavailable, you may instruct dust-framework to wait for a given number of seconds using block. If the lock cannot be acquired before the timeout expires, block fails with a LockTimeout error, which dust-framework renders as a 423 Locked response if returned from a handler:
let report: String = cache::lock("reports", 10.seconds())? .block(5.seconds()) .get(async || { // Generate the report... Ok(String::from("...")) }) .await?;To handle a timeout yourself, await block directly and check the error with is::<LockTimeout>():
use dust::cache::{self, LockTimeout};use dust::prelude::*;let lock = cache::lock("reports", 10.seconds())?;match lock.block(5.seconds()).await { Ok(()) => { // Lock acquired after waiting up to 5 seconds... lock.release().await?; } Err(error) if error.is::<LockTimeout>() => { // Unable to acquire the lock... } Err(error) => return Err(error),}When protecting a database transaction with a lock, acquire the lock before starting the transaction so the lock is released only after the transaction commits.
[!WARNING] Locks acquired via
acquireor by awaitingblockmust be released explicitly withrelease. Dropping a lock or panicking does not release it, so it remains held until its duration expires. Choose a duration longer than the protected work, or refresh the lock as work progresses. Usinggetreleases the lock automatically, even if the request is cancelled.
Managing locks across processes
Sometimes you need to acquire a lock in one process and release it in another, such as acquiring a lock in an HTTP handler and releasing it when a queued job completes. Pass the lock's owner token to the job:
use dust::cache;use dust::prelude::*;use crate::jobs::ProcessPodcast;pub async fn process(Params(podcast_id): Params<i64>) -> dust::Result<Redirect> { let lock = cache::lock("processing", 2.minutes())?; if lock.acquire().await? { let owner = lock.owner().to_owned(); ProcessPodcast { podcast_id, owner }.dispatch().await?; } Ok(Redirect::back())}Inside the job, restore the lock with the owner token and release it:
// src/jobs/process_podcast.rsuse dust::cache;use dust::queue::{Queueable, job};#[derive(Queueable)]pub struct ProcessPodcast { pub podcast_id: i64, pub owner: String,}#[job]impl ProcessPodcast { async fn handle(self) -> dust::Result<()> { // Process the podcast... cache::restore_lock("processing", &self.owner)?.release().await?; Ok(()) }}To release a lock regardless of its current owner, call force_release.
Refreshing locks
For long-running tasks, acquire a short-lived lock and extend it as work progresses rather than guessing an overly long duration up front. refresh resets the lock's expiration to its original duration from the current time, returning false if the lock has already expired or is held by another owner:
use dust::cache;use dust::prelude::*;let lock = cache::lock("yearly-reports", 1.minute())?;if lock.acquire().await? { for month in 1..=12 { // Generate the month's report... lock.refresh().await?; } lock.release().await?;}Because a restored lock does not know its original duration, extend it with refresh_for(1.minute()) instead.
Failure modes and limits
A cache is an optimization. Every read must be correct when the value is missing, and every value must be safe to lose at any moment:
- Entries can disappear early. A Redis eviction policy, a
cache:clear, or an application restart with amemorystore can remove a key before its expiration. Treat a hit as a bonus, never as a guarantee. - Stale data is still data. A cached model may no longer match the database. Keep lifetimes short for values that change often, or include a version in the key and bump it after a migration.
- A stampede is not a miss. When a hot key expires, every request recomputes it at once. Wrap the recomputation in a lock or use
cache::flexible. - A type change is not a miss for
get.cache::getreturns an error when stored JSON does not match the requested type, whilerememberandflexibletreat it as a miss and recompute. Version keys when you change a cached struct's shape. - Shared stores are readable by every application that reaches them. Do not cache secrets, tokens, or personal data unless the store and its credentials are trusted.
flushignoresCACHE_PREFIX. It is a blunt instrument for local recovery, not a per-application reset.
Logging
The cache writes a debug log line under the dust::cache target for every key it reads, writes, or removes. Each entry includes the store name and unprefixed key, without logging cached values. Enable these logs by raising the dust::cache log level:
LOG_LEVEL=info,dust::cache=debug| Message | Written when |
|---|---|
Cache hit |
A read finds a value. |
Cache missed |
A read finds no value. |
Cache key written |
A value is stored. |
Cache key forgotten |
A key is removed. |
Cache flushed |
A store is flushed. |
Custom drivers
To store cached values in a backend without a built-in driver, such as Memcached, implement the dust::cache::Store trait. Your driver only needs to store and retrieve encoded strings by key; dust-framework handles JSON serialization, key prefixes, durations, and logging for you:
use std::time::Duration;use dust::cache::Store;pub struct MemcachedStore { pub server: String,}impl Store for MemcachedStore { async fn get(&self, key: &str) -> dust::Result<Option<String>> { // Return the value stored under the key... todo!() } async fn put(&self, key: &str, value: String, ttl: Duration) -> dust::Result<()> { // Store the value under the key, and expire it after the TTL... todo!() } async fn add(&self, key: &str, value: String, ttl: Duration) -> dust::Result<bool> { // Store the value only if the key is missing, and return whether you stored it... todo!() } async fn increment(&self, key: &str, by: i64) -> dust::Result<Option<i64>> { // Add to an existing counter and return its new value, or `None` when the key is missing... todo!() } async fn forget(&self, key: &str) -> dust::Result<bool> { // Delete the key, and return whether it existed... todo!() } async fn flush(&self) -> dust::Result<()> { // Delete every key... todo!() }}Support for atomic locks and rate limiting is optional. To support locks on your custom store, also implement acquire_lock, release_lock, force_release_lock, refresh_lock, and lock_owner on Store. To support rate limiting, implement compare_and_swap:
async fn acquire_lock(&self, name: &str, owner: &str, ttl: Duration) -> dust::Result<bool> { // Acquire the lock for `owner` until `ttl` elapses if it is currently free... todo!()}async fn release_lock(&self, name: &str, owner: &str) -> dust::Result<bool> { // Release the lock only if `owner` holds it... todo!()}async fn force_release_lock(&self, name: &str) -> dust::Result<()> { // Release the lock regardless of owner... todo!()}async fn refresh_lock(&self, name: &str, owner: &str, ttl: Duration) -> dust::Result<bool> { // Extend an unexpired lock held by `owner` to `ttl` from now... todo!()}async fn lock_owner(&self, name: &str) -> dust::Result<Option<String>> { // Return the current owner if the lock is held and unexpired... todo!()}async fn compare_and_swap( &self, key: &str, current: Option<&str>, new: String, ttl: Duration,) -> dust::Result<bool> { // Atomically store `new` for `ttl` only if the current value matches `current`... todo!()}Register your driver by name in src/app.rs. dust-framework invokes the factory lazily the first time your application accesses a store using that driver:
Application::configure() .with_services(|app| { app.cache().extend("memcached", async |_app, _definition| { Ok(MemcachedStore { server: "127.0.0.1:11211".into(), }) }); })A package can register its driver inside its service provider's register method. Next, define a store referencing your driver name and select it in .env:
cache.add_store("memcached", StoreConfig::custom("memcached"));CACHE_STORE=memcachedIf multiple stores share one driver with different settings, such as two Memcached servers, attach per-store settings with StoreConfig::custom("memcached").settings(..) and read them inside your factory via definition.settings::<T>().
Testing
Tests use the memory store by default, as described in configuring your tests. Each test runs with an isolated application and starts with an empty cache, so you can interact with the cache directly inside your tests:
use dust::cache;use dust::testing::prelude::*;#[dust::test]async fn reports_are_cached(app: Application) -> dust::Result<()> { app.get("/reports/monthly").await.assert_ok(); assert!(cache::has("report:monthly").await?); Ok(())}Cache expirations follow the application's clock, so you can test expiration behavior using time travel instead of sleeping.