Cache-aside caching is an application-managed read strategy: look up data in a cache first, fetch missing or expired data from a backing store, then insert the result before returning it. Hits usually avoid backing-store latency; misses leave fetching and cache updates to the application. section 6.3.1
A typical cache-aside read proceeds as follows:
- Construct a cache key identifying the requested data. section 6.3.1
- Return the cached value when the key exists and has not expired. section 6.3.1
- On a miss, query the backing store, transform the result into a cacheable representation, insert it, and return it. section 6.3.1
- Choose expiration and capacity policies carefully: short TTLs can reduce hit ratio, while long TTLs can expose stale data. section 6.11
User data and REST API responses
An application can use a user ID as the cache key, serialize database results as JSON, and store that representation. A Rust REST API example uses PostgreSQL as the backing store and Moka as an in-memory cache: the handler checks CACHE_KEY, queries PostgreSQL on a miss, inserts the result, and returns it. A five-second TTL limits entry lifetime. section 6.3.1 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 pattern that branches between a cache hit and a backing-store fetch followed by insertion. section 6.10
