Redis as external cache

Learn how to move a response cache out of server memory into Redis, share it between servers, survive restarts, and handle Redis being down

Redis is a separate program that stores data in memory and answers requests over the network. As a cache, it plays the same role as the map in server memory, with three differences that matter: it survives a server restart, it is shared between every server process that connects to it, and it can expire entries on its own. The price is a network call on every lookup and a second service to run. This page moves the weather cache from the previous topic into Redis, keeping the same handler shape and the same expiry, and shows what changes and what stays the same.

Where This Fits

The in-memory cache works until the deployment grows past one process. Two servers behind a load balancer each keep their own map, so the same question can get a fresh answer from one and a stale answer from the other. A restart empties the map, so the first requests after a deploy all hit the slow service at once. Redis fixes both by moving the map out of the process and into a shared service. Every server reads and writes the same entries, and a restart of any one server leaves the entries untouched.

Think of the shopkeeper's price board again, but now there is a chain of shops. A board in one shop helps only that shop. A board in a shared back room, which every shop can read, helps all of them, and repainting one board updates every shop at once. Redis is the shared back room. The cost is the walk to the back room on every question.

The Smallest Working Version

Redis must be running before the server starts. Install it from the system packages and start it:

apt-get install -y redis-server
redis-server --daemonize yes --port 6379
redis-cli ping

The last command should answer PONG. The version used to check this page was Redis server 7.0.15. The server in this page connects to redis://127.0.0.1:6379/, which is the default address and port, with database zero, the default database.

Create the project with the redis crate. The tokio-comp feature gives the crate an async client that works with Tokio.

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

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
redis = { version = "1", features = ["tokio-comp"] }
src/lib.rs
use axum::{Json, Router, extract::State, http::StatusCode, routing::get};
use redis::AsyncCommands;
use serde::{Deserialize, Serialize};
use std::time::Duration;

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

#[derive(Clone)]
struct AppState {
    redis: redis::Client,
}

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

async fn weather(
    State(state): State<AppState>,
    axum::extract::Path(city): axum::extract::Path<String>,
) -> Result<Json<Weather>, (StatusCode, String)> {
    let key = format!("weather:{city}");
    let mut con = match state.redis.get_multiplexed_async_connection().await {
        Ok(con) => con,
        Err(error) => {
            return Err((StatusCode::SERVICE_UNAVAILABLE, format!("redis unavailable: {error}")))
        }
    };
    if let Ok(cached) = con.get::<_, String>(&key).await {
        if let Ok(mut value) = serde_json::from_str::<Weather>(&cached) {
            value.source = "redis cache".into();
            return Ok(Json(value));
        }
    }
    let fresh = slow_weather(&city).await;
    let _ = con
        .set_ex::<_, _, ()>(&key, serde_json::to_string(&fresh).unwrap(), 60)
        .await;
    Ok(Json(fresh))
}

pub fn app() -> Router {
    let client = redis::Client::open("redis://127.0.0.1:6379/").unwrap();
    Router::new()
        .route("/weather/{city}", get(weather))
        .with_state(AppState { redis: client })
}
src/main.rs
use weather_redis::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,"source":"fresh"}
first: 0.41s
{"city":"paris","temp_c":21.5,"source":"redis cache"}
second: 0.012s

The first request took about four tenths of a second, because it ran the slow function. The second took about twelve milliseconds, because it read from Redis. Twelve milliseconds is slower than the five milliseconds an in-memory map took, and the difference is the network round trip to Redis and back. That is the price of the shared cache, and for most answers it is small next to the slow work it replaces.

The stored value is visible from the Redis command line:

redis-cli GET "weather:paris"
redis-cli TTL "weather:paris"
{"city":"paris","temp_c":21.5,"source":"fresh"}
60

The value is the weather struct serialised to JSON, and the time to live is 60 seconds, counting down from the moment it was stored. Restarting the Axum server leaves this entry in place, which is the first thing the in-memory cache could not do.

Working Setup:

If the second request answers with "source": "redis cache" and redis-cli GET "weather:paris" shows the stored JSON, the round trip works. If the second request says "source": "fresh" again, the store or the lookup is failing, and the set_ex call is the place to look.

The Pieces, One at a Time

The handler keeps the same shape as the in-memory version, read, then compute, then store, but every piece is now a network operation.

1. The client is built once and shared

#[derive(Clone)]
struct AppState {
    redis: redis::Client,
}

redis::Client holds the address and the connection settings. It is cheap to clone, because the clone shares the same configuration, and it is the value stored in State. Client::open only parses the address. It does not connect. A wrong address is not an error here. The error appears later, when the handler asks for a connection.

2. A multiplexed connection is borrowed per request

let mut con = match state.redis.get_multiplexed_async_connection().await {
    Ok(con) => con,
    Err(error) => {
        return Err((StatusCode::SERVICE_UNAVAILABLE, format!("redis unavailable: {error}")))
    }
};

A multiplexed connection is a single network connection that carries many requests at once, interleaving them safely. The handler borrows one from the client for the duration of the request. If Redis is down, this is the call that fails, and the handler answers 503 instead of panicking. That choice is deliberate: a cache being down should degrade the service, not crash it. A Result return type makes the 503 easy, because the error tuple (StatusCode, String) converts into a response directly.

3. Get, parse, or fall through

if let Ok(cached) = con.get::<_, String>(&key).await {
    if let Ok(mut value) = serde_json::from_str::<Weather>(&cached) {
        value.source = "redis cache".into();
        return Ok(Json(value));
    }
}

con.get asks Redis for the string stored under the key. A missing key is not an error in the Redis sense, so the call returns an error only when the key is absent or the connection fails, and the if let Ok skips the whole block in that case. The stored string is JSON, so it is parsed back into a Weather. A value that fails to parse is treated the same as a missing value: the handler falls through to the slow function and overwrites it. Treating a corrupt entry as a miss is safer than returning an error to the client for a cache problem.

The key is weather:paris. The colon is a Redis convention for namespacing keys, and it makes keys readable in redis-cli listings: all weather entries start with weather:, all session entries would start with session:, and so on. The key must still capture every input that changes the answer, exactly as the in-memory key had to.

4. Set with an expiry, in one call

let _ = con
    .set_ex::<_, _, ()>(&key, serde_json::to_string(&fresh).unwrap(), 60)
    .await;

set_ex stores a value and an expiry in seconds in a single command, so the entry can never exist without its expiry. The value is the fresh struct serialised to JSON with serde_json::to_string. The let _ = ignores the result, because a failed store should not fail the request: the handler already has the fresh answer, and the next request will simply miss again and recompute. The type parameters ::<_, _, ()> tell the compiler the key type, the value type, and that the command returns nothing useful. They look odd, and they are the price of a generic command interface.

Redis Expiry Is Enforced by Redis:

The 60 in set_ex is enforced by the server, not by the application. Redis deletes the key when the time runs out, and a later GET finds nothing. That is different from the in-memory version, where the application checked the age itself. The application trusts the server to expire the entry, and the application code is simpler for it.

The Concept Behind It

Redis is a key value store. A key value store is a map that lives in its own process and speaks a small command language over the network: GET a key, SET a key, DELETE a key, and ask how long a key has left. Everything the handler does is one of those commands. There is no query language, no tables, and no schema. The application decides what the keys mean and what the values contain, and Redis only stores bytes and enforces expiries.

That simplicity is the point. A cache does not need a database. It needs a fast map with an expiry, shared between processes, and Redis is that map with a network socket in front of it. The values here are JSON strings, because JSON is easy to inspect with redis-cli and easy to parse back. A value could equally be a binary format, and the only change would be the serialisation calls.

Why Move the Cache Out of the Process

Three properties change when the cache leaves the process, and each one is a real operational difference. The cache survives a restart of the application, because the data lives in the Redis process. The cache is shared between application processes, because every process talks to the same Redis. And the cache can grow beyond one process's memory, because Redis has its own memory, sized and monitored separately.

The cost is also real. Every lookup is a network round trip, measured here at roughly twelve milliseconds against a local Redis, where the in-memory lookup was about five. A lookup that fails because Redis is down must be handled, where an in-memory map cannot fail that way. And there is a second service to install, run, and watch. For a single server process with a small key space, the in-memory cache is simpler and faster. The external cache earns its place when the deployment has more than one process, or when a restart must not empty the cache.

What Happens When Redis Is Down

A cache that crashes the service when it is down is worse than no cache. The handler in this page answers 503 when it cannot get a connection at all, and it ignores a failed store. A stricter shape is to skip the cache entirely when Redis is down and run the slow function instead, so the service keeps answering, just slowly. That shape looks like this in the connection step:

let mut con = match state.redis.get_multiplexed_async_connection().await {
    Ok(con) => Some(con),
    Err(_) => None,
};

With None, the handler skips the GET, runs the slow function, and skips the SET. The response is the same fresh answer, and the client never learns the cache was down. The 503 shape used in the main example is simpler to read and is honest about the failure, but the skip shape is the one most production services use, because a cache outage should not become a service outage. Choose the shape deliberately, and write down which one was chosen.

Do Not Panic on a Cache Failure:

An unwrap on a Redis connection turns a cache outage into a crashed request handler, and a panic in a handler closes the connection without an answer. Cache code should return an error or skip the cache, never panic. The slow function is the fallback, and it works without Redis at all.

Invalidating One Entry

Invalidation works the same way as the in-memory version, with a Redis DEL command instead of a map removal.

async fn invalidate(
    State(state): State<AppState>,
    axum::extract::Path(city): axum::extract::Path<String>,
) -> StatusCode {
    let key = format!("weather:{city}");
    let mut con = match state.redis.get_multiplexed_async_connection().await {
        Ok(con) => con,
        Err(_) => return StatusCode::SERVICE_UNAVAILABLE,
    };
    match con.del::<_, i64>(&key).await {
        Ok(removed) if removed > 0 => StatusCode::NO_CONTENT,
        Ok(_) => StatusCode::NOT_FOUND,
        Err(_) => StatusCode::SERVICE_UNAVAILABLE,
    }
}

Register it on the same path:

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

DEL returns the number of keys removed, so the handler can tell a removed entry from a missing one: 204 when something was deleted, 404 when the key was not there. Checked live, the first DELETE answers 204 and the next GET is fresh again, because the entry is gone from the shared cache, and every server sees the same absence. That is the second thing the in-memory cache could not do: one invalidation reaches every process.

Serialising Values, and What Else Could Be Stored

The value stored here is a JSON string, produced by serde_json::to_string and read back by serde_json::from_str. JSON is readable in redis-cli, which makes debugging easy, and it is version tolerant in the small: adding an optional field to Weather still parses old stored values, because missing fields become None. A required new field breaks old values instead, and they fall through to the slow function and get overwritten, which is the safe behaviour the parse failure path already provides.

Two alternatives are worth knowing. A binary format is smaller and faster to parse, and it is the right choice when values are large or the cache is hot. Storing each field of the struct as a Redis hash field, with HSET and HGETALL, lets one field be read or changed without touching the others, and it is the right choice when the value is updated field by field. The JSON string is the simplest shape, and it is the right default until one of those needs appears.

What the Flow Looks Like

Request for /weather/paris arrives
        |
        v
Borrow a connection, GET weather:paris
        |
   +----+----------------+
   | key found?          |
   +----+----------------+
   | yes                 | no
   v                     v
Parse JSON,           Run slow function
return cached body         |
(x-cache behaviour:     v
 source = redis cache)  SETEX weather:paris <json> 60
                       |
                       v
                 Return fresh body

The only difference from the in-memory flow is that the lookup and the store cross the network, and the expiry is set at store time instead of checked at read time.

Testing It

A test for the Redis handler needs a real Redis, because the handler talks to one. That is a real requirement, not a testing nicety. The test below assumes Redis is running on the default port, the same way the server does, and it cleans up after itself.

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

#[tokio::test]
async fn second_request_for_same_city_comes_from_redis() {
    let app = app();
    let first = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/weather/lyon")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(first.status(), StatusCode::OK);
    let first_bytes = axum::body::to_bytes(first.into_body(), usize::MAX)
        .await
        .unwrap();
    assert!(String::from_utf8(first_bytes.to_vec()).unwrap().contains("fresh"));

    let second = app
        .oneshot(
            Request::builder()
                .uri("/weather/lyon")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(second.status(), StatusCode::OK);
    let second_bytes = axum::body::to_bytes(second.into_body(), usize::MAX)
        .await
        .unwrap();
    assert!(String::from_utf8(second_bytes.to_vec()).unwrap().contains("redis cache"));
}

The test needs tower as a dev dependency:

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

The test uses a city name that is unlikely to collide with other tests, asks twice, and checks the source field changes from fresh to redis cache. It uses the response body rather than a header, because the handler carries its source in the body. A test run leaves a weather:lyon key in Redis with a 60 second expiry, which then expires on its own. A test suite that runs many such tests should use distinct keys per test, or flush the test database between runs, so tests cannot see each other's entries.

A Test That Needs Redis Is Honest About It:

A cache test that stubs out Redis tests the stub, not the cache. The test above needs Redis running, and it will fail with a clear 503 when Redis is down, which is the correct signal: the thing being tested is not available. Run the suite with Redis up, the same way the server runs with Redis up.

Common Beginner Mistakes

Opening a new client per request

// Wrong - a new client on every request, and a connection setup each time
async fn weather(State(state): State<AppState>) -> Json<Weather> {
    let client = redis::Client::open("redis://127.0.0.1:6379/").unwrap();
    // ...
}

Client::open is cheap, but building the client per request is still wasteful, and it hides the address in the handler instead of the application setup. Build the client once in app(), store it in State, and borrow connections from it per request. One client, many connections, is the intended shape.

Storing the struct without serialising it

Redis stores bytes. A Weather struct cannot be stored directly. It must be turned into bytes first, and JSON is the straightforward way. The matching mistake on the read side is to return the stored string as the response body without parsing it, which would send the client a JSON string wrapped in JSON quotes. Parse it back into the struct, then return the struct, and the response is clean.

Using GET and SET as two steps instead of SETEX

A SET followed by an EXPIRE is two commands, and a crash between them leaves a key with no expiry, which then lives forever. SETEX does both in one command, so the entry always has its expiry. The same reasoning applies to any pair of commands that must happen together: look for the single command that does both.

Treating a Redis error as a missing key

A failed GET and a missing key look the same in an if let Ok chain, and that is fine for a read, because both fall through to the slow function. But a failed connection on the first call is different from a missing key, and the handler distinguishes them by matching the connection result first and answering 503. Conflating the two hides an outage behind slow responses, which is survivable but confusing to debug.

Final Complete Example

Here is everything from the page put together: the weather type, the Redis client in state, the handler with its 503 fallback, the invalidation route, the server, and the test.

src/lib.rs
use axum::{Json, Router, extract::State, http::StatusCode, routing::get};
use redis::AsyncCommands;
use serde::{Deserialize, Serialize};
use std::time::Duration;

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

#[derive(Clone)]
struct AppState {
    redis: redis::Client,
}

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

async fn weather(
    State(state): State<AppState>,
    axum::extract::Path(city): axum::extract::Path<String>,
) -> Result<Json<Weather>, (StatusCode, String)> {
    let key = format!("weather:{city}");
    let mut con = match state.redis.get_multiplexed_async_connection().await {
        Ok(con) => con,
        Err(error) => {
            return Err((StatusCode::SERVICE_UNAVAILABLE, format!("redis unavailable: {error}")))
        }
    };
    if let Ok(cached) = con.get::<_, String>(&key).await {
        if let Ok(mut value) = serde_json::from_str::<Weather>(&cached) {
            value.source = "redis cache".into();
            return Ok(Json(value));
        }
    }
    let fresh = slow_weather(&city).await;
    let _ = con
        .set_ex::<_, _, ()>(&key, serde_json::to_string(&fresh).unwrap(), 60)
        .await;
    Ok(Json(fresh))
}

async fn invalidate(
    State(state): State<AppState>,
    axum::extract::Path(city): axum::extract::Path<String>,
) -> StatusCode {
    let key = format!("weather:{city}");
    let mut con = match state.redis.get_multiplexed_async_connection().await {
        Ok(con) => con,
        Err(_) => return StatusCode::SERVICE_UNAVAILABLE,
    };
    match con.del::<_, i64>(&key).await {
        Ok(removed) if removed > 0 => StatusCode::NO_CONTENT,
        Ok(_) => StatusCode::NOT_FOUND,
        Err(_) => StatusCode::SERVICE_UNAVAILABLE,
    }
}

pub fn app() -> Router {
    let client = redis::Client::open("redis://127.0.0.1:6379/").unwrap();
    Router::new()
        .route("/weather/{city}", get(weather).delete(invalidate))
        .with_state(AppState { redis: client })
}
src/main.rs
use weather_redis::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-redis"
version = "0.1.0"
edition = "2021"

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

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

Start Redis, run the server with cargo run, and ask for a city twice. The first answer is fresh, the second comes from Redis, and redis-cli GET "weather:paris" shows the stored JSON with a 60 second expiry.

Summary

The single most important insight is that moving the cache out of the process changes who shares it and who outlives it, and nothing else about the handler logic. The read, compute, and store steps are the same. The key still has to capture every input, the expiry still has to match how fast the truth changes, and a corrupt entry still falls through to a fresh computation. What changes is operational: the cache survives restarts, every server sees the same entries, one invalidation reaches them all, and a failed cache becomes a failure the handler must answer for.

The decision framework follows from that. Use the in-memory map while one process is enough, because it is faster and simpler. Move to Redis when the deployment has more than one process, when a restart must not empty the cache, or when the cache needs to be inspected and invalidated from outside the application. And whichever cache is chosen, decide in advance what happens when it is down, because the day it is down is the day the decision matters.