In-Memory Store with Application State in Axum

Learn how to create, share, and update in-memory data stores across Axum handlers using application state, with practical examples and common pitfalls.

When you build a web application, you often need to keep some data that multiple requests can read and change. That data could be a counter, a list of users, cached results, or any temporary information. Instead of writing to a database every time, you might want to keep it in the computer's memory for quick access. Axum makes this easy through its state mechanism.

This page is about in-memory stores, the pattern of putting a data structure (like a HashMap or a Vec) into your application state, sharing it across all handlers, and safely reading from and writing to it. Think of an AppState as a bundle of data that Axum passes to your handlers automatically.

We will start with the absolute basics, build a simple shared counter, then move to a more realistic key-value store. Along the way, we will cover the two main locking choices, show multiple ways to store different kinds of data, and point out the mistakes beginners usually make.

What Is an In-Memory Store?

An in-memory store is just a piece of data that lives in your program's RAM while it runs. It is not saved to disk. If you stop the program, the data disappears. That sounds like a limitation, and for persistent storage it is. But many tasks do not need permanent storage.

Common uses for an in-memory store include:

  • Caching frequently requested data so you do not hit a database every time.
  • Rate limiting - keeping a count of how many requests a client has made in the last minute.
  • Sessions - storing temporary user information between requests.
  • Prototyping - building an API quickly without setting up a database.
  • Shared counters or flags that all requests need to see and possibly change.

In Axum, an in-memory store becomes part of your application state. You create the store before starting the server, pass it to your router with .with_state(), and then every handler can access it through the State extractor.

Think of the state as a box that all handlers share. The box contains your store. Because many requests can arrive at the same time, you cannot let them all write to the store at once without coordination. That is where Arc and a lock come in.

Why Use an In-Memory Store in Axum?

Axum is built for high concurrency. That means your server can handle many requests simultaneously, possibly on different threads. If two threads modified a shared HashMap at the same time without coordination, they could corrupt it. Rust's ownership rules will not even let you share a plain HashMap across handler functions in safe code, so you need a pattern that makes the sharing explicit and safe.

Axum's state system solves the sharing problem. You wrap your store in an Arc, which allows multiple threads to own the same data. Then you wrap it in a lock (like Mutex or RwLock), which ensures only one thread can modify the data at a time. This combination is the standard pattern for an in-memory store in Axum.

The alternative is to use a database or an external cache like Redis. Those persist data and are better for production systems with multiple servers. But for learning, small apps, or single-instance deployments, an in-memory store is often perfect. It is simple, fast, and requires no extra setup.

Preparing an In-Memory Store for Sharing

Before we write any handler, we need to understand the two building blocks: Arc and a lock.

Arc<T> stands for Atomically Reference Counted. It lets multiple owners share the same value. When you clone an Arc, you do not copy the inner data; you just increase a reference count. The data is dropped only when the last Arc is gone. Because it uses atomic operations, it is safe to share across threads.

Mutex<T> stands for Mutual Exclusion. It allows only one thread to access the inner data at a time. A thread must call lock() to get access. If another thread already holds the lock, the second thread waits. When the first thread is done, it releases the lock, and the second can proceed.

RwLock<T> (Read-Write Lock) is a more flexible lock. It allows many readers at the same time but only one writer. This can improve performance when reads are more frequent than writes.

For an absolute beginner, a Mutex is simpler to reason about. We will start with std::sync::Mutex and later discuss the async-friendly tokio::sync::Mutex.

Here is how you create an in-memory store for a simple counter and put it into an AppState struct:

use std::sync::{Arc, Mutex};
// Our application state holds the shared counter.
#[derive(Clone)]
struct AppState {
    counter: Arc<Mutex<i32>>,
}
impl AppState {
    fn new() -> Self {
        Self {
            counter: Arc::new(Mutex::new(0)),
        }
    }
}

In this code, counter is an Arc<Mutex<i32>>. The Arc allows the state to be cloned and passed to multiple handlers without copying the actual i32. The Mutex ensures that only one handler can read or write the integer at a time. The #[derive(Clone)] is needed because Axum will clone the state for each request, but the clone is cheap because it only clones the Arc, not the inner data.

Why Clone the State?:

Axum's .with_state() requires the state to implement Clone. When you derive Clone, you get a shallow copy: the Arc's reference count increases, but the underlying data remains the same. That is exactly what we want for shared state.

A First Complete Example - Shared Counter

Let us build a complete Axum application with one endpoint that increments a counter and returns its new value. This is the simplest possible in-memory store.

First, create a new Rust project and add the dependencies to Cargo.toml:

[package]
name = "in-memory-counter"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }

Now write src/main.rs:

use axum::{
    extract::State,
    routing::get,
    Router,
};
use std::sync::{Arc, Mutex};
// Our shared state.
#[derive(Clone)]
struct AppState {
    counter: Arc<Mutex<i32>>,
}
async fn increment_counter(
    State(state): State<AppState>,
) -> String {
    // Lock the mutex to get exclusive access.
    let mut counter = state.counter.lock().unwrap();
    *counter += 1;
    format!("Counter is now: {}", *counter)
}
#[tokio::main]
async fn main() {
    let state = AppState {
        counter: Arc::new(Mutex::new(0)),
    };
    let app = Router::new()
        .route("/", get(increment_counter))
        .with_state(state);
    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();
}

When you run this with cargo run and open http://127.0.0.1:3000 in a browser, you will see:

Counter is now: 1

Refresh the page a few times:

Counter is now: 2
Counter is now: 3

Every request locks the mutex, increments the integer, and releases the lock. The next request then sees the updated value.

Let me break down what happens mechanically. The handler increment_counter receives State<AppState>. Axum has already cloned the Arc, but the mutex inside is still the same one. We call .lock().unwrap(), which blocks the current thread until the mutex is available. Then we dereference the MutexGuard to get a mutable i32, add one, and the guard goes out of scope at the end of the function, releasing the lock automatically. The format! macro builds the response string while we still hold the guard, but that is fine because it is fast and does not await anything.

Lock Held Across Await:

In this example we used std::sync::Mutex and did not have any .await while holding the lock. That is important. If you try to hold a std::sync::Mutex guard across an .await inside an Axum handler, the code will not compile: the guard is not Send, so the handler future is not Send and does not satisfy the Handler trait. In async handlers, prefer tokio::sync::Mutex if you must await while locking, or keep the critical section very short and free of awaits.

Storing More Complex Data - A Key-Value Store

A counter is fine, but most real applications need to store collections like a HashMap. Let us build a small in-memory key-value store where you can set a key to a value and later retrieve it.

We will use a HashMap<String, String> as the inner data. The state will be wrapped in Arc<Mutex<HashMap<String, String>>>.

First, a plain text version:

use axum::{
    extract::{Path, State},
    response::IntoResponse,
    routing::{get, post},
    Router,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct AppState {
    store: Arc<Mutex<HashMap<String, String>>>,
}
async fn set_value(
    State(state): State<AppState>,
    Path((key, value)): Path<(String, String)>,
) -> impl IntoResponse {
    let mut store = state.store.lock().unwrap();
    store.insert(key.clone(), value.clone());
    format!("Set {} = {}", key, value)
}
async fn get_value(
    State(state): State<AppState>,
    Path(key): Path<String>,
) -> impl IntoResponse {
    let store = state.store.lock().unwrap();
    match store.get(&key) {
        Some(value) => format!("{} = {}", key, value),
        None => format!("Key '{}' not found", key),
    }
}
#[tokio::main]
async fn main() {
    let state = AppState {
        store: Arc::new(Mutex::new(HashMap::new())),
    };
    let app = Router::new()
        .route("/set/{key}/{value}", post(set_value))
        .route("/get/{key}", get(get_value))
        .with_state(state);
    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();
}

To test it, start the server and use curl:

curl -X POST http://127.0.0.1:3000/set/name/Alice
# Output: Set name = Alice
curl http://127.0.0.1:3000/get/name
# Output: name = Alice
curl http://127.0.0.1:3000/get/missing
# Output: Key 'missing' not found

In set_value, we extract two path parameters key and value as a tuple. Then we lock the mutex, insert the pair into the HashMap, and return a confirmation message. In get_value, we lock the mutex, look up the key, and return either the value or a not-found message. Notice that we hold the lock only for the duration of the lookup. There is no .await inside the lock, so std::sync::Mutex works fine.

This pattern works, but returning plain strings is not very API-friendly. Let us upgrade to JSON responses using axum::Json and serde.

Add serde and serde_json to Cargo.toml:

serde = { version = "1", features = ["derive"] }
serde_json = "1"

Now rewrite the handlers to return Json responses. We also need a struct for the response.

use axum::{
    extract::{Path, State},
    routing::{get, post},
    Json, Router,
};
use serde::Serialize;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct AppState {
    store: Arc<Mutex<HashMap<String, String>>>,
}
#[derive(Serialize)]
struct SetResponse {
    key: String,
    value: String,
}
#[derive(Serialize)]
struct GetResponse {
    key: String,
    value: Option<String>,
}
async fn set_value(
    State(state): State<AppState>,
    Path((key, value)): Path<(String, String)>,
) -> Json<SetResponse> {
    let mut store = state.store.lock().unwrap();
    store.insert(key.clone(), value.clone());
    Json(SetResponse { key, value })
}
async fn get_value(
    State(state): State<AppState>,
    Path(key): Path<String>,
) -> Json<GetResponse> {
    let store = state.store.lock().unwrap();
    let value = store.get(&key).cloned();
    Json(GetResponse { key, value })
}
#[tokio::main]
async fn main() {
    let state = AppState {
        store: Arc::new(Mutex::new(HashMap::new())),
    };
    let app = Router::new()
        .route("/set/{key}/{value}", post(set_value))
        .route("/get/{key}", get(get_value))
        .with_state(state);
    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();
}

Now when you curl -X POST ... you will receive JSON like {"key":"name","value":"Alice"}. For get, if the key exists you get {"key":"name","value":"Alice"}, otherwise {"key":"missing","value":null}.

This is a complete, realistic in-memory store. The same pattern can be extended to more complex data types, like a Vec of custom structs or a HashSet for unique values.

Multiple Ways to Store Data - Choosing the Right Collection

The in-memory store is not limited to HashMap or i32. You can store any Send + Sync type inside the lock. Here are common options and when to use them.

Vec<T> - Ordered List

Use a Vec when you need to keep items in insertion order and often iterate over all of them. For example, a list of to-do items.

use axum::{
    extract::State,
    routing::{get, post},
    Json, Router,
};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct AppState {
    todos: Arc<Mutex<Vec<Todo>>>,
}
#[derive(Serialize, Deserialize, Clone)]
struct Todo {
    id: u32,
    text: String,
    done: bool,
}
async fn list_todos(State(state): State<AppState>) -> Json<Vec<Todo>> {
    let todos = state.todos.lock().unwrap().clone();
    Json(todos)
}
async fn add_todo(
    State(state): State<AppState>,
    Json(new_todo): Json<NewTodo>,
) -> Json<Todo> {
    let mut todos = state.todos.lock().unwrap();
    let id = todos.len() as u32 + 1;
    let todo = Todo {
        id,
        text: new_todo.text,
        done: false,
    };
    todos.push(todo.clone());
    Json(todo)
}
#[derive(Deserialize)]
struct NewTodo {
    text: String,
}
#[tokio::main]
async fn main() {
    let state = AppState {
        todos: Arc::new(Mutex::new(Vec::new())),
    };
    let app = Router::new()
        .route("/todos", get(list_todos).post(add_todo))
        .with_state(state);
    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();
}

This code shows a Vec<Todo> stored in Arc<Mutex<Vec<Todo>>>. In list_todos, we clone the entire Vec so that we can return it after releasing the lock. Cloning a Vec of small structs is cheap enough for a prototype, but be careful with very large lists. For a large list, you might want to return only the fields you need, or use RwLock to allow multiple readers. Run the server and send a POST request with a JSON body like {"text": "write docs"} to /todos, then GET /todos and you will see your new item in the returned list, for example [{"id":1,"text":"write docs","done":false}].

HashMap<K, V> - Key-Value Lookup

We already saw HashMap. It is great when you need to retrieve items by a unique key quickly. Use it for caches, session stores, or any indexed data.

HashSet<T> - Unique Values

If you need to keep track of unique identifiers (like active users or used tokens), a HashSet works well.

use std::collections::HashSet;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct AppState {
    active_users: Arc<Mutex<HashSet<String>>>,
}

Custom Structs with Multiple Fields

You can also store more complex state that is not just a collection. For example, a struct holding configuration and a cache.

#[derive(Clone)]
struct AppState {
    config: Arc<Config>,
    cache: Arc<Mutex<HashMap<String, String>>>,
}

The key is that any data you want to mutate concurrently must be behind a lock. Immutable data can be shared with just Arc and no lock at all, since nobody needs to change it.

Choosing a Lock - std::sync::Mutex vs tokio::sync::Mutex

We have used std::sync::Mutex in all examples so far. That is the standard library mutex. It works perfectly fine as long as you never hold the lock across an .await point. In many Axum handlers, you do not need to await while holding the lock because you only do quick in-memory operations.

However, sometimes you might need to perform an asynchronous operation while the lock is held. For example, suppose you want to update a counter and then send a message over a channel, or call an async database function that requires the lock to be held to ensure consistency. In an Axum handler you cannot do that with a std::sync::Mutex at all: holding its guard across an .await makes the handler future not Send, and the compiler rejects the handler. The std mutex also blocks the thread while waiting for the lock, which stalls other tasks on that thread in async code that is not protected by the same Send requirement.

The solution is to use tokio::sync::Mutex, which is designed for async code. Its lock() method returns a future that you .await. While waiting for the lock, the current task yields to the runtime, allowing other tasks to run.

Here is the same counter example using tokio::sync::Mutex:

use axum::{
    extract::State,
    routing::get,
    Router,
};
use std::sync::Arc;
use tokio::sync::Mutex;
#[derive(Clone)]
struct AppState {
    counter: Arc<Mutex<i32>>,
}
async fn increment_counter(
    State(state): State<AppState>,
) -> String {
    // tokio::sync::Mutex::lock() returns a future, so we await it.
    let mut counter = state.counter.lock().await;
    *counter += 1;
    format!("Counter is now: {}", *counter)
}
#[tokio::main]
async fn main() {
    let state = AppState {
        counter: Arc::new(Mutex::new(0)),
    };
    let app = Router::new()
        .route("/", get(increment_counter))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Notice the only difference is the import of tokio::sync::Mutex and the .await after lock(). The rest is identical.

Which one should you use? The decision is a one-time configuration choice for your entire application. If you are unsure, follow this rule:

Use std::sync::Mutex when your critical sections are short, synchronous, and never contain .await. This is the most common case for in-memory stores. It is slightly faster because it does not require the async runtime, and it can be used in non-async contexts as well. If you hold a std mutex guard across an .await inside an Axum handler, the compiler will stop you: the guard is not Send, so the handler future is not Send and does not implement Handler. Keep your locked sections tiny.

Do Not Mix Lock Types:

Pick one lock type for each piece of data and stick with it. Mixing std::sync::Mutex and tokio::sync::Mutex on the same data is impossible because they are different types. Also, never try to hold a std::sync::Mutex guard across an .await inside an Axum handler; the compiler rejects it because the guard is not Send.

Building a Simple In-Memory Store Step by Step

Let us walk through creating a small but complete in-memory store application from scratch, using the patterns we have learned. This will reinforce the steps and give you a runnable project.

1

Step 1: Create a new Rust project

Open your terminal and run:

cargo new in-memory-store-demo
cd in-memory-store-demo
2

Step 2: Add dependencies to Cargo.toml

Edit Cargo.toml to include axum, tokio, serde, and serde_json:

[package]
name = "in-memory-store-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
3

Step 3: Write the main.rs with a shared counter

Replace the contents of src/main.rs with the counter example using tokio::sync::Mutex:

use axum::{
    extract::State,
    routing::get,
    Router,
};
use std::sync::Arc;
use tokio::sync::Mutex;
#[derive(Clone)]
struct AppState {
    counter: Arc<Mutex<i32>>,
}
async fn increment(State(state): State<AppState>) -> String {
    let mut count = state.counter.lock().await;
    *count += 1;
    format!("Count: {}", *count)
}
#[tokio::main]
async fn main() {
    let state = AppState {
        counter: Arc::new(Mutex::new(0)),
    };
    let app = Router::new()
        .route("/", get(increment))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}
4

Step 4: Run the server and test

Start the server:

cargo run

Then open your browser at http://127.0.0.1:3000 and refresh a few times. Each refresh increments the counter. You should see Count: 1, then Count: 2, and so on.

It Works!:

If you see the counter increasing with each request, your in-memory store is functioning correctly. The state is shared across all requests, and the mutex is preventing race conditions.

Updating State Safely - Lock, Modify, Unlock

The pattern for updating an in-memory store is always the same:

  1. Acquire the lock (.lock() or .lock().await).
  2. Modify the data.
  3. Release the lock (automatically when the guard goes out of scope).

It is tempting to lock and then forget to keep the guard alive long enough, or to lock twice by mistake. Here is a common mistake: calling lock() and immediately dropping the guard without modifying.

// WRONG: The lock is acquired and immediately released.
state.counter.lock().unwrap();
// The guard is dropped here because it is not bound to a variable.

To actually modify the data, you must bind the guard to a variable:

// RIGHT
let mut counter = state.counter.lock().unwrap();
*counter += 1;

The guard must remain in scope while you modify the data. Once it goes out of scope, the lock is released.

Another mistake is holding the lock longer than necessary. For example, if you build a large response string inside the locked section, you block other requests from accessing the store even though you no longer need exclusive access. It is better to extract the needed data, release the lock, and then build the response.

// Bad: holding lock while building string
let mut counter = state.counter.lock().unwrap();
*counter += 1;
let response = format!("Counter: {}", *counter);
// lock still held here
Json(response)
// Better: release lock before building response
let new_value = {
    let mut counter = state.counter.lock().unwrap();
    *counter += 1;
    *counter
};
Json(format!("Counter: {}", new_value))

The second version releases the lock as soon as new_value is obtained, then builds the response outside the critical section.

Common Mistakes and Misconceptions

Beginners often run into a few recurring issues when working with in-memory stores in Axum. Let us address them directly.

Forgetting to wrap the store in Arc

If you try to put a Mutex<HashMap<...>> directly into your AppState and derive Clone, you will get a compile error because Mutex does not implement Clone. Even if you manually implement Clone by cloning the Mutex, that would create a separate lock guarding a separate piece of data - not shared state. The correct approach is Arc<Mutex<...>>, where cloning the Arc gives you another handle to the same lock.

Using std::sync::Mutex across .await

We have mentioned this before, but it is worth repeating. The std::sync::Mutex is a blocking lock, and its guard is not Send. If you try to hold the guard across an .await inside an Axum handler, the handler does not compile, because Axum requires handler futures to be Send. If you must await while holding a lock, switch to tokio::sync::Mutex.

Locking in a loop or forgetting to unlock

Rust's ownership system prevents most of these issues because the guard is automatically dropped when it goes out of scope. However, if you store the guard in a variable and then forget to drop it (e.g., by returning early from a function before the guard's scope ends), you could accidentally hold the lock. In Rust, early returns still drop local variables, so this is rare. Just be mindful of scope.

Cloning the entire store unnecessarily

If your store is a large Vec or HashMap, cloning it on every read to return it to the client can be expensive. In prototypes, that is fine. In production, you might want to use RwLock to allow multiple readers at the same time, or return only the fields you need. Axum handlers return owned responses, so you cannot return a reference tied to the state's lifetime. For most beginner projects, cloning small data is acceptable.

Not handling lock poisoning

When using std::sync::Mutex, if a thread panics while holding the lock, the mutex becomes poisoned. Subsequent calls to lock() will return an Err instead of panicking. Our examples use .unwrap(), which will panic if the mutex is poisoned. In a production application, you might want to handle the error by recovering or logging. For simplicity, .unwrap() is acceptable in tutorials, but you can also use .lock().unwrap_or_else(|poisoned| poisoned.into_inner()) to recover the data even if the mutex is poisoned.

Use RwLock for Read-Heavy Workloads:

If your handlers read from the store much more often than they write, consider using std::sync::RwLock or tokio::sync::RwLock instead of Mutex. RwLock allows multiple readers at the same time, which can improve performance. The APIs differ slightly: std::sync::RwLock uses the synchronous .read() and .write(), while tokio::sync::RwLock uses .read().await and .write().await.

Real-World Usage Patterns

In-memory stores show up in many production systems, even though they are not persistent. Here are a few places you might see them.

  • Caching: A handler might first check an in-memory HashMap for a result. If it finds it, it returns immediately. If not, it queries the database, stores the result in the HashMap, and returns it. This avoids repeated database hits for popular data.
  • Rate limiting: A middleware or handler can keep a HashMap<String, Vec<Instant>> mapping client IPs to their recent request timestamps. On each request, it prunes old timestamps and checks if the client has exceeded a limit. This is a classic in-memory store.
  • Session management: For single-instance applications, session data can be stored in a HashMap<String, SessionData> keyed by a session ID. The session ID is usually stored in a cookie, and the handler looks up the session in the store.
  • Temporary feature flags: If you need to toggle a feature at runtime without redeploying, you can keep a flag in an in-memory store that an admin endpoint can change.

The important thing to remember is that all of these stores disappear when the process restarts. If you need data to survive restarts, you must use a database or persistent cache.

Summary

In-memory stores are a simple and powerful way to share mutable data across Axum handlers. The pattern is always the same: create a data structure, wrap it in Arc<Mutex<...>> or Arc<RwLock<...>>, put it in your AppState, pass it with .with_state(), and access it via the State extractor. Lock the mutex, modify or read the data, and let the guard drop to release the lock.

The choice between std::sync::Mutex and tokio::sync::Mutex comes down to whether you need to hold the lock across an .await. For quick in-memory operations, std::sync::Mutex works fine. For async critical sections, use the Tokio version.

The single most important insight from this page is that sharing data in a concurrent web server requires both shared ownership (Arc) and mutual exclusion (a lock). Without both, your code will not compile or will be unsafe. Once you understand that combination, you can build any kind of in-memory store for your Axum application.

From here, you are ready to explore more advanced state patterns, such as using RwLock for read-heavy stores, storing more complex structures, and integrating an in-memory store with a database fallback. The fundamentals you have learned here apply to all of them.