Lesson 4 of 14 · 20m
Shared State: Mutex, DashMap, and Atomics
Arc<Mutex<T>> vs RwLock vs DashMap vs atomics, mutex poisoning as a designed failure mode, OnceLock for one-time state, and the lock discipline that prevents the 3am deadlock.
A request handler needs the rate-limit counters. A background task needs them too. &mut can't reach across tasks — there is exactly one exclusive borrow, and two tasks is already one too many. This is where Arc<Mutex<T>> enters the codebase, and it's also where a whole class of production bugs lives, because the tool you reach for changes what can go wrong at 3am.
The smorgasbord, and what each actually does
use std::sync::{Arc, Mutex, RwLock};
use std::sync::atomic::{AtomicU64, Ordering};
struct AppState {
requests_served: AtomicU64, // a counter — no lock
config: RwLock<Config>, // many readers, rare writer
sessions: Mutex<HashMap<SessionId, Session>>, // everyone writes
}Mutex<T>— one accessor at a time. Correct default.RwLock<T>— many concurrent readers or one writer. Pays off only when reads vastly outnumber writes and the critical section is non-trivial; on a hot path, writer-starvation and reader-lock contention often make it slower than a plainMutex.AtomicU64and friends — lock-free single values.fetch_add(1, Ordering::Relaxed)is the right counter; reach forOrdering::SeqCstonly when you can say why the weaker order is wrong.DashMap<K, V>— a sharded lock around aHashMap. Under write-heavy multi-task access it beatsMutex<HashMap>because keys in different shards don't contend. It's theConcurrentHashMappattern, not magic: iteration still takes the locks.parking_lot::Mutex— drop-in replacement that's smaller (one word of lock state), faster under contention, and doesn't poison. Thestdmutex's poisoning is the part nobody reads about until it matters.
Poisoning: the failure mode built in on purpose
A std::sync::Mutex that was held while a thread panicked becomes poisoned. Every subsequent lock() returns Err(PoisonError) — the standard library's bet that data a panicking thread was mutating may be inconsistent, so the safe default is to fail loudly:
let mut guard = state.sessions.lock()
.unwrap_or_else(|e| e.into_inner()); // deliberate: we accept possibly-stale dataThe wrong mental model is "poisoning is a nuisance — unwrap and move on." The code that ships lock().unwrap() everywhere converts one panicking task into a service-wide 500 storm: task A panics mid-update, every later request hits PoisonError, and your handler unwraps it into another panic. Either make the critical section panic-free (the real fix), choose parking_lot explicitly (no poisoning, no pretense), or write down why into_inner() is safe here.
One-shot and global state: OnceLock and LazyLock
Half of "shared mutable state" in services is really "shared immutable state that arrives late" — config loaded at startup, a compiled regex, a lazily-built HTTP client:
use std::sync::OnceLock;
static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
let client = CLIENT.get_or_init(|| reqwest::Client::new());OnceLock (std, since Rust 1.70) runs the initializer exactly once even under racing callers. LazyLock (1.80) is the same for static items you want initialized on first touch with zero ceremony — it replaced most uses of the once_cell/lazy_static crates in new code. If your global can't fail and can't change, LazyLock is the answer; if it needs runtime args or error handling, OnceLock::get_or_try_init on a stored value.
The lock discipline that prevents the 3am deadlock
Two rules, mechanically enforced:
- Never hold a
stdguard across.await.std::sync::MutexGuardis!Send— multi-threaded Tokio rejects it at compile time, which is the good outcome. The bad outcome is a runtime that compiles anyway (single-threaded executor, or you "fixed" it with a wrapper) and deadlocks: task A awaits holding the lock, task B waits on the lock, nobody wakes. Scope the guard so it drops before the.await:
let item = {
let mut map = state.cache.lock().unwrap();
map.insert(k, v);
map.get(&k).cloned()
}; // guard dropped here — before the await
tx.send(item).await.ok();- Acquire in one order only. Task A locks
sessionsthenledger; task B locksledgerthensessions. Under load they meet in the middle and neither moves. Pick a lock order, document it next to the struct, and keep the critical sections short enough that it rarely matters.
The bug that ships
The interior-mutability bug that ships is Arc<Mutex<HashMap>> standing in for "we'll figure out contention later" — then a hot endpoint serializes every request through one mutex, and your async service performs like it's single-threaded because it is, at the lock. Profile before reaching for RwLock or DashMap (they're not free), but when one mutex is the throughput ceiling, sharding or lock-free counters are the fix — not a bigger box.
Try this
Build a RateLimiter as Arc<Mutex<HashMap<IpAddr, (u32, Instant)>>> and hit it with 200 concurrent tasks. Then swap the HashMap for DashMap and the counter for AtomicU64 and compare — you'll feel exactly which contention the lock was costing you.
Field notes
tokio::sync::Mutexexists for the case where the guard must span an.await— it's slower and easier to deadlock into big critical sections, so use it only when crossing.awaitis a requirement, not a default.flurryis the port of Java'sConcurrentHashMapfor when you need a truly concurrent map with per-entry semantics;DashMapcovers most service workloads.- An
Arc<RwLock<T>>whereTis aVecof audit entries that only ever grows: considerMutex<Vec>—RwLockbuys nothing when every access is a write.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Rust 1.100: The Never Type Is Finally Stable, and Cargo Learned to Wait
Rust 1.100 stabilizes the never type after ten years and five failed attempts, along with the core Allocator API and a DropGuard helper. The change most teams will notice is in Cargo: a one-line config that makes it skip any crate version published in the last few days.
What Rust 1.79 Shipped
The Rust Development Team has unveiled Rust 1.79, marking another step forward in the evolution of the memory-safe programming language. This latest update, announced last week on June 13, brings stability to both inline const expressions and the associated item bounds syntax, providing…
Source-Based Coverage Arrived in Rust 1.60
Rust 1.60, introduced just this April 7, 2022, stabilizes support for LLVM-based coverage instrumentation in rustc. This provides for source-based code coverage. Developers can try this out by rebuilding their code with -Cinstrument-coverage. Afterward, running the resulting binary will produce…
What is Rust? The Language That Makes Systems Programming Safe
Rust eliminates entire categories of bugs — null pointer dereferences, buffer overflows, data races, use-after-free — at compile time with no runtime overhead. Microsoft, Google, Amazon, and the Linux kernel all use it for systems code.