In-memory response caching

Learn how to cache slow responses in server memory with a shared map and an expiry time, when that helps, and when the cache becomes stale or wrong

A cache is a place to keep an answer so the next identical question does not need the full work again. In-memory response caching keeps those answers in the server's own memory, in a map from request to response, with an expiry time after which the answer is thrown away and recomputed. It is the simplest cache there is: no extra service, no network call, just a data structure the handlers already share. It fits answers that are slow to compute, safe to repeat, and fine to be a little out of date.

Where This Fits

Some handlers do slow work for the same input over and over. A weather lookup that calls an outside service, a report that scans a table, or a page that renders the same content for every visitor will produce the same answer for minutes at a time, yet recompute it on every request. The work is wasted, and the outside service or the database feels it first. A cache in front of that work turns the second request into a map lookup, which is effectively free.

Think of a shopkeeper who writes the day's prices on a board each morning. The first customer asks the price of rice, and the shopkeeper works it out. The next fifty customers ask the same question, and the shopkeeper reads the board instead of working it out again. The board is rewritten when the prices change, or when the day ends. The cache is the board, the expiry time is the end of the day, and the slow work is the calculation.

The Smallest Working Version

One route, one slow function, one map. The weather function pretends to be slow by sleeping for 300 milliseconds, the way a real call to an outside service would be.

Cargo.toml
[package]
name = "weather-api"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
src/lib.rs
use axum::{Json, Router, extract::State, routing::get};
use serde::Serialize;
use std::{collections::HashMap, sync::Arc, time::{Duration, Instant}};
use tokio::sync::RwLock;

#[derive(Serialize, Clone)]
struct Weather {
    city: String,
    temp_c: f64,
}

struct Entry {
    body: Weather,
    stored_at: Instant,
}

type Cache = Arc<RwLock<HashMap<String, Entry>>>;

async fn slow_weather(city: &str) -> Weather {
    tokio::time::sleep(Duration::from_millis(300)).await;
    Weather { city: city.to_string(), temp_c: 21.5 }
}

async fn weather(
    State(cache): State<Cache>,
    axum::extract::Path(city): axum::extract::Path<String>,
) -> Json<Weather> {
    {
        let guard = cache.read().await;
        if let Some(entry) = guard.get(&city) {
            if entry.stored_at.elapsed() < Duration::from_secs(60) {
                return Json(entry.body.clone());
            }
        }
    }
    let fresh = slow_weather(&city).await;
    cache
        .write()
        .await
        .insert(city, Entry { body: fresh.clone(), stored_at: Instant::now() });
    Json(fresh)
}

pub fn app() -> Router {
    let cache: Cache = Arc::new(RwLock::new(HashMap::new()));
    Router::new()
        .route("/weather/{city}", get(weather))
        .with_state(cache)
}
src/main.rs
use weather_api::app;

#[tokio::main]
async fn main() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app()).await.unwrap();
}

Run it and ask for the same city twice:

curl -w "\nfirst: %{time_total}s\n" http://127.0.0.1:3000/weather/paris
curl -w "\nsecond: %{time_total}s\n" http://127.0.0.1:3000/weather/paris

On the machine used to check this page, the answers were:

{"city":"paris","temp_c":21.5}
first: 0.368s
{"city":"paris","temp_c":21.5}
second: 0.005s

The first request took about a third of a second, because it ran the slow function. The second took about five milliseconds, because it read the map. The bodies are identical. The client cannot tell the difference, except by speed.

Working Setup:

If the first request takes a noticeable fraction of a second and the second request for the same city comes back almost instantly with the same body, the cache is working. If both requests are slow, the lookup is missing, usually because the key used to store the entry is not the key used to read it.

The Three Pieces, One at a Time

The handler has three parts, and each one is a separate decision.

1. The map and its key

type Cache = Arc<RwLock<HashMap<String, Entry>>>;

A HashMap maps a key to a value. The key here is the city name, because the city is the whole input to the slow function. Two requests for the same city have the same key and share one entry. Two requests for different cities have different keys and different entries. The key must capture everything the answer depends on. If the answer also depended on the units, metric or imperial, then the city alone would be the wrong key, and a request for imperial units could receive a metric answer stored by an earlier request. The rule is that the key must include every input that changes the output.

Arc lets the map be shared between the tasks that handle requests. RwLock is a lock that allows many readers at once but only one writer, which fits a cache: most operations are reads, and writes are rare. The combination Arc<RwLock<HashMap>> is the standard shape for shared mutable state in an Axum handler, and it arrives through State, the same way a database pool does.

2. The read path and the expiry check

{
    let guard = cache.read().await;
    if let Some(entry) = guard.get(&city) {
        if entry.stored_at.elapsed() < Duration::from_secs(60) {
            return Json(entry.body.clone());
        }
    }
}

The handler first takes the read lock and looks the city up. If an entry exists and it is younger than 60 seconds, the handler returns a clone of the stored body at once. elapsed() measures the time since the entry was stored, using Instant, which is a clock for measuring durations, not wall clock time. The braces around this block matter: the read lock is released when the block ends, before the slow function runs. Holding the read lock across the slow call would block every other reader for 300 milliseconds, which would defeat the purpose of the cache.

An expired entry is not deleted here. It is simply ignored, and the fresh value overwrites it a moment later. Deleting it would need the write lock, and there is no point taking the write lock twice.

3. The write path

let fresh = slow_weather(&city).await;
cache
    .write()
    .await
    .insert(city, Entry { body: fresh.clone(), stored_at: Instant::now() });
Json(fresh)

When the cache has no fresh entry, the handler runs the slow function, takes the write lock, and stores the result with the current time. The stored body is a clone, because the handler also returns the original. Cloning a small struct is cheap. Cloning a large response on every hit is worth thinking about, and a later section covers sharing the body without cloning.

The Cache Key Must Capture Every Input:

A cache key that leaves out an input that changes the answer serves the wrong answer. City alone is right only when the answer depends on the city alone. Add the units, the language, or the user id to the key whenever the answer depends on them. A wrong key is worse than no cache, because the server answers quickly and wrongly.

The Concept Behind It

A cache trades freshness for speed. Freshness is how close the answer is to the truth right now. Speed is how quickly the answer arrives. A cache entry is a bet that the truth has not changed since the answer was computed. The expiry time is the size of that bet. A 60 second expiry says the weather from a minute ago is good enough. A 60 minute expiry says the same about an hour old answer. There is no expiry that is right in general. The right one depends on how fast the truth changes and how much a stale answer costs.

This trade is the whole subject. Everything else, the map, the lock, the key, is plumbing. When a cache causes a bug, the bug is almost always a freshness bug: the truth changed and the cache kept serving the old answer. The fixes are always about freshness too: a shorter expiry, an explicit invalidation, or not caching that answer at all.

Why Cache in Memory

An in-memory cache is the fastest cache possible, because there is no network round trip to reach it. It is also the simplest to operate, because there is no second service to run, no connection to configure, and no failure mode where the cache service is down. For a single server process, it is usually the right first cache.

Its limits follow from where it lives. The cache dies with the process, so a restart empties it. The cache is per process, so two servers behind a load balancer each have their own copy, and a request can get a fresh answer from one server and a cached answer from the other. The cache shares memory with the application, so an unbounded map grows until the process runs out of memory. The next topic covers a cache that lives outside the process, which removes the first two limits and adds a network call to every lookup.

Showing Hits and Misses with a Header

A cache that works silently is hard to debug. A response header that says whether the answer came from the cache makes the behaviour visible to anyone with curl.

async fn weather(
    State(cache): State<Cache>,
    axum::extract::Path(city): axum::extract::Path<String>,
) -> (HeaderMap, Json<Weather>) {
    let mut headers = HeaderMap::new();
    {
        let guard = cache.read().await;
        if let Some(entry) = guard.get(&city) {
            if entry.stored_at.elapsed() < Duration::from_secs(60) {
                headers.insert("x-cache", "HIT".parse().unwrap());
                return (headers, Json(entry.body.clone()));
            }
        }
    }
    let fresh = slow_weather(&city).await;
    cache
        .write()
        .await
        .insert(city, Entry { body: fresh.clone(), stored_at: Instant::now() });
    headers.insert("x-cache", "MISS".parse().unwrap());
    (headers, Json(fresh))
}

The handler now returns a tuple of headers and body. Axum turns a (HeaderMap, Json<T>) tuple into a response with those headers, so no other change is needed. The header name x-cache is a convention, not a standard, and the values HIT and MISS are plain words. Checking it looks like this:

curl -s -D - -o /dev/null http://127.0.0.1:3000/weather/paris | grep -i x-cache

The first call prints x-cache: MISS and the second prints x-cache: HIT. The -D - flag tells curl to print the response headers, and -o /dev/null discards the body. This header is also the simplest way to prove the cache works in a test, because the test can read the header instead of timing the response.

Invalidating One Entry

An expiry time handles freshness passively: old answers die on their own. Sometimes freshness needs to be active: the underlying data changed, and the cached answer must go now, not in a minute. A DELETE route that removes one entry does that.

async fn invalidate(
    State(cache): State<Cache>,
    axum::extract::Path(city): axum::extract::Path<String>,
) -> StatusCode {
    if cache.write().await.remove(&city).is_some() {
        StatusCode::NO_CONTENT
    } else {
        StatusCode::NOT_FOUND
    }
}

Register it on the same path with a different method:

.route("/weather/{city}", get(weather).delete(invalidate))

The handler takes the write lock, removes the entry, and answers 204 when something was removed and 404 when the city was not cached at all. Checked live, the first DELETE answers 204 and the second answers 404, because the entry is already gone. The next GET after a DELETE is a MISS again and recomputes the answer. Invalidation is the escape hatch for every staleness bug: when the data changes, call the invalidation route as part of the same change, and the cache can never serve the old value afterwards.

Invalidation Belongs with the Change:

A cache invalidation that lives in a separate manual step will be forgotten. The reliable shape is to invalidate in the same code that changes the data, so the two cannot drift apart. If the data changes through a different service, the invalidation has to travel with that change too, which is the point where an in-memory cache starts to strain and an external cache starts to look better.

What Not to Cache

Three kinds of responses should not be cached, and the reasons are different for each. Responses that depend on who is asking, such as a personal dashboard or a shopping basket, must never be shared between users, and a cache keyed only by path would do exactly that. Responses that change the world, such as a POST that creates an order, must never be replayed from a cache, because the second request would create a second order or return a success for work that never happened. Only GET-like reads with no side effects belong in a response cache.

Responses that must be fresh, such as a stock price or a seat count, can be cached only with an expiry the business accepts, and often the answer is that it cannot. And responses that are already fast do not need a cache. A map lookup for an answer that takes a millisecond to compute adds complexity for no measurable gain. The cache earns its place only when the work it skips is slow enough to matter.

Bounding the Map

The map in the examples grows without limit. Every new city adds an entry, and entries are never removed except by invalidation. A server that serves many distinct keys will eventually hold them all in memory. Three defences exist, in increasing order of effort. The simplest is to store only a fixed number of entries, evicting the least recently used one when the map is full, which is what dedicated cache crates do. The next is to run a background task that sweeps expired entries out of the map on a timer. The simplest of all is to accept the growth for a small, bounded key space, such as a few dozen cities, and to revisit the decision when the key space grows. An unbounded map with an unbounded key space is a memory leak with a friendly name, and it deserves a note in the code saying which defence was chosen and why.

What the Flow Looks Like

Request for /weather/paris arrives
        |
        v
Take read lock, look up "paris"
        |
   +----+----------------+
   | entry fresh?        |
   +----+----------------+
   | yes                 | no
   v                     v
Return stored body   Run slow function
(x-cache: HIT)         |
                       v
                 Take write lock, store result
                       |
                       v
                 Return fresh body
                 (x-cache: MISS)

The read lock is held only for the lookup. The slow work runs with no lock held. The write lock is held only for the insert. That ordering is what keeps the cache from becoming a bottleneck of its own.

Testing It

A test can prove the cache works by reading the x-cache header on two identical requests, without timing anything.

tests/app_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use weather_api::app;
use tower::ServiceExt;

#[tokio::test]
async fn second_request_for_same_city_is_a_hit() {
    let app = app();
    let first = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/weather/paris")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(first.status(), StatusCode::OK);
    assert_eq!(first.headers().get("x-cache").unwrap(), "MISS");

    let second = app
        .oneshot(
            Request::builder()
                .uri("/weather/paris")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(second.status(), StatusCode::OK);
    assert_eq!(second.headers().get("x-cache").unwrap(), "HIT");
}

#[tokio::test]
async fn different_cities_do_not_share_entries() {
    let app = app();
    let response = app
        .oneshot(
            Request::builder()
                .uri("/weather/berlin")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.headers().get("x-cache").unwrap(), "MISS");
}

The test needs tower as a dev dependency:

Cargo.toml
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

The first test sends two requests for Paris and checks the headers change from MISS to HIT. The router is cloned between the two requests because oneshot consumes the service it is called on, and cloning shares the same underlying cache. The second test asks for Berlin and expects a MISS, proving the entries are per city. Both tests avoid timing, which would be flaky, and check the header instead, which is exact.

Common Beginner Mistakes

Holding the lock across the slow call

// Wrong - every other request waits for the slow call
let guard = cache.read().await;
if guard.get(&city).is_none() {
    let fresh = slow_weather(&city).await;
    // ...
}

A read lock held while slow_weather runs blocks all other readers for the full 300 milliseconds, and a write lock would block everyone. The cache would still return right answers, but the server would handle one slow request at a time. The fix is the scoped block in the example: look the entry up, drop the lock, then do the slow work with no lock held.

Caching the error too

A handler that stores whatever the slow function returned, including an error body, will serve that error for the full expiry time, even after the outside service recovers. Only successful answers belong in the cache. An error should be returned without storing anything, so the next request retries the slow call at once. The examples store only the success path, and that is deliberate.

Using a mutable global instead of State

A static mut map or a global behind a lazy lock works, but it cannot be replaced in tests, cannot hold different data per application instance, and fights the borrow checker in ways State does not. State is the mechanism Axum provides for exactly this, and the cache is ordinary application state. Use it.

Forgetting that a restart empties the cache

The first requests after a deploy are all MISSes, and the slow service feels the full load at once. That burst is normal for an in-memory cache, and it is worth knowing about before a deploy, not discovering from a spike in the slow service. A short expiry makes the burst shorter, because entries are recomputed anyway.

Never Cache Per User Data Under a Shared Key:

A response that contains one user's data, stored under a key that another user's request can hit, leaks that data to the other user. The failure is silent and the leak is real. Per user answers need the user in the key, or they need no cache at all. When in doubt, do not cache it.

Final Complete Example

Here is everything from the page put together: the weather type, the cache, the handler with its HIT and MISS headers, the invalidation route, the server, and the tests.

src/lib.rs
use axum::{Json, Router, extract::State, http::{HeaderMap, StatusCode}, routing::get};
use serde::Serialize;
use std::{collections::HashMap, sync::Arc, time::{Duration, Instant}};
use tokio::sync::RwLock;

#[derive(Serialize, Clone)]
struct Weather {
    city: String,
    temp_c: f64,
}

struct Entry {
    body: Weather,
    stored_at: Instant,
}

type Cache = Arc<RwLock<HashMap<String, Entry>>>;
const TTL: Duration = Duration::from_secs(60);

async fn slow_weather(city: &str) -> Weather {
    tokio::time::sleep(Duration::from_millis(300)).await;
    Weather { city: city.to_string(), temp_c: 21.5 }
}

async fn weather(
    State(cache): State<Cache>,
    axum::extract::Path(city): axum::extract::Path<String>,
) -> (HeaderMap, Json<Weather>) {
    let mut headers = HeaderMap::new();
    {
        let guard = cache.read().await;
        if let Some(entry) = guard.get(&city) {
            if entry.stored_at.elapsed() < TTL {
                headers.insert("x-cache", "HIT".parse().unwrap());
                return (headers, Json(entry.body.clone()));
            }
        }
    }
    let fresh = slow_weather(&city).await;
    cache
        .write()
        .await
        .insert(city, Entry { body: fresh.clone(), stored_at: Instant::now() });
    headers.insert("x-cache", "MISS".parse().unwrap());
    (headers, Json(fresh))
}

async fn invalidate(
    State(cache): State<Cache>,
    axum::extract::Path(city): axum::extract::Path<String>,
) -> StatusCode {
    if cache.write().await.remove(&city).is_some() {
        StatusCode::NO_CONTENT
    } else {
        StatusCode::NOT_FOUND
    }
}

pub fn app() -> Router {
    let cache: Cache = Arc::new(RwLock::new(HashMap::new()));
    Router::new()
        .route("/weather/{city}", get(weather).delete(invalidate))
        .with_state(cache)
}
src/main.rs
use weather_api::app;

#[tokio::main]
async fn main() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app()).await.unwrap();
}
Cargo.toml
[package]
name = "weather-api"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

Run the server with cargo run, ask for a city twice, and watch the first answer come back with x-cache: MISS and the second with x-cache: HIT. Delete the entry and watch the next request miss again.

Summary

The single most important insight is that caching is a freshness decision wearing a performance costume. The map and the lock are easy. The hard part is deciding how long an answer is allowed to be wrong, what key makes two requests the same question, and what happens when the truth changes before the expiry runs out. Get those three decisions right and the cache is a quiet win. Get any of them wrong and the cache serves fast, confident, wrong answers.

The decision framework follows from that. Cache a read that is slow, repeated, and safe to be briefly stale, with a key that captures every input and an expiry the data can tolerate. Invalidate in the same place the data changes. And when the cache needs to survive a restart, or be shared between servers, the map in memory has reached its limit, and the answer is a cache that lives outside the process.