Caching speeds up data retrieval by keeping temporary copies closer to where they are accessed. A backing store, such as a database, retains the primary data; the cache holds a subset for faster reuse. This reduces access latency but requires extra storage and can return stale data. section 6.0 section 6.2
An application looks up a value by cache key. A hit returns the cached value; a miss requires retrieval from the backing store. A high hit ratio is important for low latency, but misses can still produce a heavy latency tail. section 6.2 section 6.10
Caching is useful when a key–value interface is sufficient, an existing system cannot easily be changed, or storage constraints make full replication impractical. Examples include user profiles, session state, query results, and a subset of a product catalog. More complex queries or transaction requirements can make caching a poor fit. section 6.1
Design choices determine the latency and consistency trade-offs:
- Choose a strategy for reads and writes. Cache-aside, read-through, write-through, and write-behind differ in how the cache integrates with the backing store; on a miss, either the application or the cache retrieves the data. section 6.3 section 6.11
- Set a time-to-live (TTL) for freshness. A TTL that is too short can lower the hit ratio; one that is too long can allow stale reads. Multiple cache copies also require a coherence approach unless the application tolerates incoherence. section 6.11
- Limit capacity and choose a replacement policy. LRU, LFU, and FIFO evict entries when the cache is full; the best choice for hit ratio depends on the workload. section 6.6 section 6.11
- Choose where to store the cache. In-memory caches are typically lost on restart; persistent caches can avoid cold starts but add complexity and potential consistency issues. Client-side caching avoids a network round trip to a cache server but consumes application memory. section 6.2 section 6.3.5
Cache-aside with Moka
A Rust REST API can use Moka to cache a PostgreSQL query result in memory. The handler checks a fixed key, returns the value on a hit, and on a miss queries PostgreSQL, inserts the result, and returns it. Entries expire after five seconds. An HTTP benchmark compares latency with and without caching; database queries on misses still contribute to tail latency. section 6.10
Listing 6.3 HTTP request handler
const CACHE_KEY: &str = "RESULT_KEY";
async fn say_hello(
data: web::Data<Arc<AppState>>,
) -> anyhow::Result<String, Error> {
if let Some(result) = data.cache.get(CACHE_KEY) {
Ok(result)
} else {
let result = fetch_value(&data.pool).await?;
data.cache.insert(CACHE_KEY.to_owned(), result.to_owned());
Ok(result)
}
}
Inspect the request handler’s cache lookup and miss path. section 6.10






































