liveBook · Manning

Caching

As explained in Latency

Caching is a technique that stores temporary copies of data closer to where it is accessed to reduce data-retrieval delay.

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

How Latency covers it

How deep it goes
Explains cache strategies, freshness, replacement, and trade-offs, then implements and benchmarks an in-application cache.
Examples
Uses user profiles, session state, a product catalog, and a cached PostgreSQL query result as examples.
What it assumes
Assumes a PostgreSQL server for the benchmark but does not require Rust for latency optimization generally.
What you can do after
Apply it via Moka to a Rust REST API and compare latency against PostgreSQL without caching.
How it connects
Connects caching with replication, cache coherence, materialized views, and memoization.

Also explained in

Compare how 39 books explain caching →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Latency. The section links point to the parts of the book it draws on.