Skip to content

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 plain Mutex.
  • AtomicU64 and friends — lock-free single values. fetch_add(1, Ordering::Relaxed) is the right counter; reach for Ordering::SeqCst only when you can say why the weaker order is wrong.
  • DashMap<K, V> — a sharded lock around a HashMap. Under write-heavy multi-task access it beats Mutex<HashMap> because keys in different shards don't contend. It's the ConcurrentHashMap pattern, 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. The std mutex'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 data

The 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:

  1. Never hold a std guard across .await. std::sync::MutexGuard is !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();
  1. Acquire in one order only. Task A locks sessions then ledger; task B locks ledger then sessions. 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::Mutex exists 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 .await is a requirement, not a default.
  • flurry is the port of Java's ConcurrentHashMap for when you need a truly concurrent map with per-entry semantics; DashMap covers most service workloads.
  • An Arc<RwLock<T>> where T is a Vec of audit entries that only ever grows: consider Mutex<Vec> — RwLock buys nothing when every access is a write.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.