Sharing Data with RwLock in Axum
Learn how to use RwLock to share mutable state safely across multiple Axum handlers, when to prefer it over Mutex, and how to avoid common mistakes with standard and Tokio RwLock.
Axum handlers often need to share data that changes over time. A Mutex allows only one handler to access the shared data at a time, even if all handlers just want to read. RwLock is a smarter lock that lets many readers look at the data simultaneously while still guaranteeing that only one writer can modify it at any moment.
We will start with the absolute basics of RwLock, then build a small Axum app that uses it, then look at multiple ways to use it, and finally cover the mistakes that trip up most people.
What RwLock Is and Why It Exists
A RwLock (short for "read-write lock") is a synchronization primitive that allows many threads or tasks to read a piece of data at the same time, but only one thread or task to write to it at a time. The "R" and "W" stand for "read" and "write", and "Lock" means it protects the data from being accessed at the wrong time.
Think of a library. Many people can sit and read the same books at the same time. But if someone needs to rearrange the shelves, they need the whole library to themselves - no readers, no other workers. RwLock enforces exactly this rule: multiple readers, single writer.
Why does this matter in a web server? Suppose you have a shared configuration or a cache. Most requests only need to read the current value. If you use a Mutex, every read request has to wait for every other request, even though they are all only reading. That becomes a bottleneck as traffic grows. RwLock lets all those read requests run at the same time, which can make your server noticeably faster under read-heavy workloads.
On the other hand, if your shared data changes very often and readers are few, RwLock adds a little extra bookkeeping overhead compared to Mutex. That's why we choose the tool based on the access pattern.
A Small Starter Example in Rust
Before we involve Axum, let's see RwLock on its own in plain Rust. This example uses std::sync::RwLock, which is part of the standard library and works with regular threads.
use std::sync::RwLock;
fn main() {
let lock = RwLock::new(10);
// Take a read lock
{
let value = lock.read().unwrap();
println!("Current value: {}", *value);
// value goes out of scope here, releasing the read lock
}
// Take a write lock
{
let mut value = lock.write().unwrap();
*value += 5;
println!("New value: {}", *value);
// value goes out of scope, releasing the write lock
}
// Read again
println!("Final value: {}", *lock.read().unwrap());
}
When you run this, you'll see:
Current value: 10
New value: 15
Final value: 15
The read() method returns a guard that dereferences to the underlying value. The guard releases the lock automatically when it goes out of scope. The write() method returns a guard that allows mutable access. While the write guard is alive, no other thread can get a read or write guard. While any read guard is alive, no write guard can be obtained.
Notice that in the example we had to use *value to get the actual integer because read() returns a RwLockReadGuard, which dereferences to &T. Similarly, write() returns a RwLockWriteGuard, which dereferences to &mut T. The compiler helps us here.
Sharing an RwLock Across Multiple Threads
In a real Axum application, the RwLock must be shared between many handlers that run on different tasks. You cannot simply put a RwLock inside the state directly and clone it - a RwLock cannot be cloned. The solution is to wrap it in an Arc (atomic reference count). Arc<RwLock<T>> can be cloned cheaply and each clone points to the same lock and the same data.
Here is a minimal Axum application that uses an Arc<RwLock<u64>> to store a hit counter. It needs serde_json for the JSON responses, so add it to the dependencies:
# Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde_json = "1"
use axum::{
routing::get,
Router,
extract::State,
response::Json,
};
use std::sync::{Arc, RwLock};
use serde_json::json;
type SharedCounter = Arc<RwLock<u64>>;
async fn read_counter(State(counter): State<SharedCounter>) -> Json<serde_json::Value> {
let count = *counter.read().unwrap();
Json(json!({ "count": count }))
}
async fn increment_counter(State(counter): State<SharedCounter>) -> Json<serde_json::Value> {
let mut count = counter.write().unwrap();
*count += 1;
Json(json!({ "count": *count }))
}
#[tokio::main]
async fn main() {
let counter: SharedCounter = Arc::new(RwLock::new(0));
let app = Router::new()
.route("/counter", get(read_counter).put(increment_counter))
.with_state(counter);
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();
}
Let's walk through this code. SharedCounter is a type alias for Arc<RwLock<u64>>. We create an Arc that wraps the RwLock, and pass it to the router using .with_state(). Axum will store one clone of this Arc internally and give each handler its own clone when it extracts State<SharedCounter>.
In read_counter, we call counter.read(). Because this is a read lock, many incoming requests can all hold a read lock at the same time. They all get the current value and return it. In increment_counter, we call counter.write(). Only one request can hold the write lock at a time. While a write lock is held, no read locks can be obtained. This ensures that the increment is atomic: no two requests can read the same value and then both increment it to the same new value.
Now run the server and test with two terminals. In one terminal, run:
curl http://127.0.0.1:3000/counter
You'll see {"count":0}. In another terminal, run several PUT requests:
curl -X PUT http://127.0.0.1:3000/counter
curl -X PUT http://127.0.0.1:3000/counter
curl -X PUT http://127.0.0.1:3000/counter
Then read again and you'll see {"count":3}. The RwLock ensures that each PUT increments the counter by exactly one, even if they arrive at the same time.
Locking works correctly:
If your GET requests return increasing numbers and your PUT requests increment by exactly one each time, your RwLock is working as expected. No requests are lost or counted twice.
How RwLock Decides Between Reading and Writing
A RwLock has two kinds of locks: read locks and write locks. The rules are simple:
- Any number of read locks can exist at the same time.
- Only one write lock can exist at any time.
- A write lock cannot exist while any read lock exists.
- A read lock cannot be obtained while a write lock exists. Fairness is not guaranteed: with
std::sync::RwLock, a steady stream of readers can keep a waiting writer waiting, so a writer is not promised to get through promptly.
This means that if your application has many GET endpoints that only read, they will all run concurrently without blocking each other. But when a PUT endpoint wants to write, it must wait until all current readers finish. After the writer acquires the lock, new readers must wait until the writer finishes. This is the core tradeoff: readers don't block each other, but writers block everyone.
For a beginner, the mental model is a whiteboard. Many people can read what is written on it at the same time. Only one person can erase and rewrite it, and while they are doing that, nobody else can read or write.
This is different from a Mutex, which is like a single bathroom: only one person can be inside whether they are reading or writing. RwLock is like a library reading room where readers share the space, but writers need the room to themselves.
Using RwLock with a Struct Instead of a Primitive
Real applications rarely share just a number. Usually you share a struct with several fields, like a configuration object or a small in-memory store. RwLock works with any type.
Here is an example of a shared Config that can be read by anyone but only updated by an admin endpoint. We'll use serde for JSON serialization.
First, add serde and serde_json to your Cargo.toml if you haven't already:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
Now the code:
use axum::{
routing::{get, put},
Router,
extract::State,
response::Json,
http::StatusCode,
};
use std::sync::{Arc, RwLock};
use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize)]
struct AppConfig {
site_name: String,
max_upload_size: u64,
maintenance_mode: bool,
}
impl Default for AppConfig {
fn default() -> Self {
Self {
site_name: "My Site".to_string(),
max_upload_size: 10 * 1024 * 1024, // 10 MB
maintenance_mode: false,
}
}
}
type SharedConfig = Arc<RwLock<AppConfig>>;
async fn get_config(State(config): State<SharedConfig>) -> Json<AppConfig> {
let cfg = config.read().unwrap();
Json(cfg.clone())
}
async fn update_config(
State(config): State<SharedConfig>,
Json(new_config): Json<AppConfig>,
) -> Json<AppConfig> {
let mut cfg = config.write().unwrap();
*cfg = new_config;
Json(cfg.clone())
}
async fn toggle_maintenance(State(config): State<SharedConfig>) -> StatusCode {
let mut cfg = config.write().unwrap();
cfg.maintenance_mode = !cfg.maintenance_mode;
StatusCode::OK
}
#[tokio::main]
async fn main() {
let config: SharedConfig = Arc::new(RwLock::new(AppConfig::default()));
let app = Router::new()
.route("/config", get(get_config).put(update_config))
.route("/config/maintenance", put(toggle_maintenance))
.with_state(config);
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();
}
In this example, get_config obtains a read lock and clones the AppConfig because AppConfig implements Clone. Cloning the data while holding the read lock is fine because the lock is released when the guard goes out of scope at the end of the function. The clone is then returned as JSON. If AppConfig were not Clone, we would have to either return a reference (which is difficult in async functions) or copy the fields individually.
update_config takes a write lock and replaces the entire config with the JSON body. toggle_maintenance takes a write lock and flips one field. Both write operations are exclusive, so they cannot run at the same time as each other or as any read.
Cloning while holding a lock:
When you read from a RwLock, you often need to clone the data to return it. Cloning inside the lock guard is safe as long as it doesn't take too long. If cloning is expensive, consider alternative designs, but for small configs it's perfectly fine.
Multiple Readers at the Same Time
The main advantage of RwLock over Mutex is that multiple readers can hold the lock at the same time. We can show this directly with a handler that simulates a slow read: it takes a read lock, waits 200 milliseconds, and then returns the value. Holding the lock across the wait is fine here because this is tokio::sync::RwLock, whose guard is Send.
// src/main.rs
use axum::{
extract::State,
routing::get,
Router,
};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;
type SharedData = Arc<RwLock<String>>;
async fn slow_read(State(data): State<SharedData>) -> String {
// Hold the read lock while simulating slow work.
let text = data.read().await;
tokio::time::sleep(Duration::from_millis(200)).await;
text.clone()
}
#[tokio::main]
async fn main() {
let data: SharedData = Arc::new(RwLock::new("hello".to_string()));
let app = Router::new()
.route("/", get(slow_read))
.with_state(data);
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();
}
Fire five requests at the same time and time the whole batch:
time (for i in 1 2 3 4 5; do curl -s http://127.0.0.1:3000/ & done; wait)
All five return hello, and the batch finishes in about 0.21 seconds, barely more than a single 200 millisecond read, because all five readers held the lock together. Repeat the same test with a tokio::sync::Mutex in place of the RwLock and the same five requests take about 1.02 seconds, because each read waits for the previous one to finish. That gap is the whole point of RwLock: readers do not block each other.
This demo deliberately holds the lock during the wait to make the difference visible. In a real handler, you generally want to release the lock as quickly as possible, so clone the data and drop the guard before doing slow work. The lesson is about what the lock allows, not a pattern to copy into production code.
std::sync::RwLock vs tokio::sync::RwLock
You might have seen two different RwLock types: std::sync::RwLock and tokio::sync::RwLock. They are similar in concept but behave differently in async code.
std::sync::RwLock is a low-level primitive designed for synchronous code and OS threads. When you call read() or write(), it blocks the current thread until the lock is available. In an async runtime like Tokio, blocking a thread is bad because it prevents other tasks on that thread from running. However, for very short critical sections (like incrementing a counter or cloning a small struct), std::sync::RwLock is often fine because the lock is never held long enough to cause noticeable blocking.
tokio::sync::RwLock is designed for async code. Its read() and write() methods are async and do not block the thread; they yield to the runtime until the lock is available. This is essential if you need to hold the lock across an .await point, such as while doing I/O or waiting for a database response.
Axum handlers are async functions, so you may wonder why we used std::sync::RwLock in the previous examples. The answer: the critical sections in those examples are tiny and do not contain .await. The lock is acquired and released within a few nanoseconds, so the chance of blocking a Tokio worker thread for any meaningful time is negligible. For such cases, std::sync::RwLock is acceptable and often faster because it avoids the overhead of an async primitive.
But if you ever need to hold the lock while doing something that may wait (e.g., performing a database query, making an HTTP request, or sleeping), you must use tokio::sync::RwLock. A std guard is not Send, so holding it across an .await in a handler is a compile error, not a slowdown you can work around.
Here is a comparison of the two approaches side by side using Tabs. Choose the one that matches your needs.
use axum::{
routing::get,
Router,
extract::State,
};
use std::sync::{Arc, RwLock};
type SharedData = Arc<RwLock<String>>;
async fn handler(State(data): State<SharedData>) -> String {
// Lock is held for a very short time; no await inside.
let text = data.read().unwrap();
text.clone()
}
#[tokio::main]
async fn main() {
let data: SharedData = Arc::new(RwLock::new("hello".to_string()));
let app = Router::new()
.route("/", get(handler))
.with_state(data);
// ... serve app
}
Notice that in the Tokio version, read() is called with .await. The guard returned is also different: tokio::sync::RwLockReadGuard. The important distinction is whether you need to hold the lock across an await point. If yes, use Tokio; if no, std is usually sufficient.
Never hold a std lock across an await:
Holding a std::sync::RwLock (or Mutex) guard across an .await in an Axum handler does not compile: the guard is not Send, so the handler's future cannot satisfy the Handler trait. If you must hold a lock while awaiting, use tokio::sync::RwLock (or tokio::sync::Mutex).
A Complete Example with tokio::sync::RwLock and Async I/O
Let's build a realistic example that demonstrates why you might need the async RwLock. Suppose we have a shared cache of user profiles. The cache is a HashMap<String, String>. A handler receives a username, checks the cache, and if not found, it queries a slow external service (simulated with a sleep) and then inserts the result into the cache. The cache check, the slow query, and the insert all happen inside one async handler, with .await points between them, so the locks involved must be usable in async code. Using tokio::sync::RwLock is the correct choice. Notice the code still never holds any lock while it awaits: the read lock is dropped before the sleep, and the write lock is taken only after it.
use axum::{
routing::get,
Router,
extract::{State, Path},
response::Json,
};
use std::sync::Arc;
use tokio::sync::RwLock;
use std::collections::HashMap;
use serde_json::json;
use tokio::time::{sleep, Duration};
type Cache = Arc<RwLock<HashMap<String, String>>>;
async fn get_profile(
State(cache): State<Cache>,
Path(username): Path<String>,
) -> Json<serde_json::Value> {
// First, try to read from cache without waiting.
{
let read_guard = cache.read().await;
if let Some(profile) = read_guard.get(&username) {
return Json(json!({ "username": username, "profile": profile }));
}
} // read guard dropped here
// Not in cache; we need to fetch it from the "database".
// Simulate slow database query.
sleep(Duration::from_millis(100)).await;
let fetched_profile = format!("Profile for {} fetched from DB", username);
// Now we need to insert into cache. Acquire write lock.
let mut write_guard = cache.write().await;
write_guard.insert(username.clone(), fetched_profile.clone());
// write guard dropped at end of scope
Json(json!({ "username": username, "profile": fetched_profile }))
}
#[tokio::main]
async fn main() {
let cache: Cache = Arc::new(RwLock::new(HashMap::new()));
let app = Router::new()
.route("/profile/{username}", get(get_profile))
.with_state(cache);
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();
}
In this handler, we first take a read lock to check the cache. If the user is present, we return immediately, and the read lock is released when read_guard goes out of scope (the inner block ensures it's dropped before the await). If the user is not present, we release the read lock (by exiting the block) and then perform the slow query without holding any lock. After the query completes, we take a write lock and insert the result. This pattern is important: we do not hold the read lock while waiting for the database, because that would block all writers for the whole wait. With tokio::sync::RwLock, holding a read guard across an await is safe but still prevents writers from acquiring the write lock, so it's often better to drop the read lock before doing I/O.
If we had used a std::sync::RwLock here, the code would not compile. Its read() is synchronous, so cache.read().await is already a type error, and a std guard is not Send, so any future holding one across the sleep().await fails the handler's Send requirement. tokio::sync::RwLock is necessary for this kind of logic because its guards are Send and its locking itself is async.
Drop read lock before writing:
In the example above, we explicitly dropped the read guard before awaiting the database query. This allows other readers to continue while we wait, and it avoids holding a read lock during a write operation later. If you keep the read lock while waiting, writers will be blocked, which can reduce concurrency.
Handling Lock Poisoning
Only std::sync::RwLock has a concept called "poisoning". When a thread panics while holding a std lock, the lock becomes "poisoned". Subsequent attempts to read() or write() return an Err instead of a guard. This is a safety mechanism to prevent using data that might be in an inconsistent state because the panic interrupted a write operation.
tokio::sync::RwLock has no poisoning at all: its read() and write() methods are async and return the guard directly, never a Result. There is nothing to unwrap and no poisoned state to recover from.
In the examples above, we used .unwrap() on read() and write() for the std lock. If the lock is poisoned, .unwrap() will panic inside the handler. Axum does not turn that panic into a 500 response: the panic unwinds the task handling the connection, so the client gets an empty reply and the connection is dropped. (Add tower_http::catch_panic::CatchPanicLayer if you want panics to become 500 responses.) For a production application, you should decide what to do when the lock is poisoned. The simplest approach is to treat the data as still valid and recover by ignoring the poison flag. You can do this by calling .unwrap_or_else(|e| e.into_inner()), which returns the guard even if poisoned.
Here is a helper function that recovers from poisoning:
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
fn read_recover<T>(lock: &RwLock<T>) -> RwLockReadGuard<'_, T> {
match lock.read() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
}
}
fn write_recover<T>(lock: &RwLock<T>) -> RwLockWriteGuard<'_, T> {
match lock.write() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
}
}
Then in your handlers you can call read_recover(&counter) instead of counter.read().unwrap(). This makes your application more robust. However, for simple examples and learning, .unwrap() is acceptable because panics in handlers are rare and you can handle them with middleware later.
Ignoring poisoning can hide real bugs:
If a panic happened during a write, the data might be partially updated. Recovering from poisoning and using the data anyway could expose inconsistent state. In many cases it's better to let the handler panic and drop that one request, or reset the data to a known good state, than to serve data that might be half-updated. For simplicity, beginners often use .unwrap() and accept the risk.
Common Mistakes and How to Avoid Them
The most common mistakes with RwLock in Axum are related to lock scope, deadlocks, and using the wrong lock type. Let's go through each one.
Holding a Lock Longer Than Necessary
A lock should be held for the shortest possible time. In the cache example, we released the read lock before doing the slow query. If you hold a write lock while doing I/O, all other requests that need the data will be blocked, even readers. That can cause a traffic jam. Always ask: can I do this work before taking the lock, or after releasing it?
Deadlock When Acquiring Multiple Locks
If you have two RwLocks and you acquire them in a different order in different handlers, you can create a deadlock. For example:
- Handler A locks
lock1thenlock2. - Handler B locks
lock2thenlock1.
If both run at the same time, A holds lock1 and waits for lock2, while B holds lock2 and waits for lock1. Neither can proceed. To avoid this, always acquire multiple locks in the same order everywhere, or use a single RwLock that contains all the data you need to modify atomically.
Using std::sync::RwLock Across an Await
We already warned about this. If you hold a std::sync::RwLock guard across an .await in an Axum handler, the code does not compile: the guard is not Send, so the handler's future cannot satisfy the Handler trait. There is no way to accidentally do this in a handler, because the compiler rejects it. A struct that stores a guard is itself not Send either, so wrapping the guard does not smuggle it past the check. If your code compiles, no std guard is alive across an .await.
Writer Starvation
Some RwLock implementations can starve writers if there is a constant stream of readers. std::sync::RwLock does not guarantee fairness by default, but in practice it usually allows writers through eventually. However, if your workload is heavily read-biased and writers are rare, you might still want to use tokio::sync::RwLock which uses a fairer algorithm. If you need strict fairness, you can implement a ticket system yourself, but that is beyond this page.
Advanced Patterns with RwLock
Beyond simple reads and writes, RwLock offers some less commonly used methods that can be useful in certain situations.
try_read and try_write
The standard read() and write() methods block until the lock is available. Sometimes you don't want to block; you want to check if the lock is available and do something else if it isn't. try_read() and try_write() return immediately with Ok(guard) if the lock is available, or Err(TryLockError::WouldBlock) if it is not.
Here is an example of a handler that tries to increment a counter but returns a 409 Conflict if the lock is busy:
use axum::{extract::State, http::StatusCode, response::IntoResponse};
use std::sync::{Arc, RwLock, TryLockError};
type SharedCounter = Arc<RwLock<u64>>;
async fn try_increment(State(counter): State<SharedCounter>) -> impl IntoResponse {
match counter.try_write() {
Ok(mut guard) => {
*guard += 1;
(StatusCode::OK, format!("New count: {}", *guard))
}
Err(TryLockError::WouldBlock) => {
(StatusCode::CONFLICT, "Counter is busy".to_string())
}
Err(TryLockError::Poisoned(e)) => {
let mut guard = e.into_inner();
*guard += 1;
(StatusCode::OK, format!("New count (recovered): {}", *guard))
}
}
}
This handler will never block. If another request is currently writing, it will return a 409. This pattern can be used to implement optimistic concurrency or to avoid queue buildup.
Read-Write Upgrade
Sometimes you want to read a value, decide to modify it, and then write a new value - all without allowing another writer to slip in between. RwLock does not support upgrading a read lock to a write lock atomically. If you try to acquire a write lock while still holding a read lock, you risk deadlock because a writer may be waiting for your read lock to release, and you are waiting for that writer to release, but the writer can't acquire the write lock while you hold the read lock.
The safe pattern is what we did in the cache example: release the read lock, then acquire the write lock, but re-check the condition after acquiring the write lock because the data may have changed in between. This is called "double-checked locking" and is essential for correctness.
Here is a corrected version of a cache insert that follows this pattern:
async fn get_or_insert(
State(cache): State<Cache>,
Path(key): Path<String>,
) -> String {
// First check without writing
if let Some(value) = cache.read().await.get(&key) {
return value.clone();
}
// Not found; we need to insert. But another task might have inserted it
// while we were waiting. So after acquiring write lock, check again.
let mut guard = cache.write().await;
if let Some(value) = guard.get(&key) {
return value.clone();
}
let new_value = format!("Computed for {}", key);
guard.insert(key, new_value.clone());
new_value
}
This code is safe. The second if let inside the write lock prevents overwriting a value that was inserted by another task in the tiny window between the read check and the write acquisition.
When to Use RwLock vs Mutex
Now that you understand RwLock, the question is: when should you use it instead of a Mutex? The general rule:
- If your shared data is read much more often than it is written, use
RwLock. Examples: configuration, cached data, a read-only list of items. - If your shared data is written about as often as it is read, or if the critical sections are extremely short (like incrementing a counter), a
Mutexmight be simpler and slightly faster because it avoids the extra bookkeeping of reader-writer locking. - If you need to hold the lock across an
.awaitand the critical section is longer, usetokio::sync::RwLock(ortokio::sync::Mutex).
For absolute beginners, it's often fine to start with Mutex for simplicity. But when you notice that many read-only endpoints are contending on the same lock, switch to RwLock.
Summary
Picking a lock is a decision tree, not a preference. Ask what the access pattern looks like. If most requests only read and writes are rare, use RwLock: readers run together and the server stops queueing read-only work behind other readers. If reads and writes are roughly balanced, or the critical section is a single tiny update like incrementing a counter, use Mutex: it is simpler and the extra bookkeeping of RwLock buys nothing. Then ask whether the lock must be held across an .await. If yes, the answer is the tokio version of whichever lock you picked; the std version does not compile in that position. If no, the std version is fine and slightly cheaper.
Two habits cover the rest. Keep every lock held for the shortest time you can, cloning the data out instead of working under the lock, and treat a poisoned std lock as a decision, not an accident: recover with into_inner() only when you know the data is still valid, and let the request fail otherwise. With those rules, the choice between Mutex and RwLock stops being a guess and becomes a reading of the workload in front of you.