Skip to content

Lesson 6 of 9 · 24m

Shared State Without Deadlock or Contention

Use ownership, message passing, async-aware locks, and narrow critical sections instead of reflexively wrapping everything in Arc and Mutex.

Arc<Mutex<T>> is the async Rust version of a junk drawer. Sometimes it is exactly right; often it is where ownership design goes to die. Shared state is not evil, but every shared mutable object introduces ordering, contention, poisoning, and shutdown questions. Senior async design is mostly about shrinking those questions.

Prefer ownership transfer over shared mutation

If one task produces a job and another consumes it, send the job through a channel rather than storing it in a shared vector protected by a lock:

tx.send(Job { id, payload }).await?;

Now the queue implementation owns synchronization, producers and consumers have clear roles, and shutdown follows channel closure. This is not merely aesthetic. It removes an entire class of lock-ordering bugs.

Choose the right lock

std::sync::Mutex is fine for very short synchronous critical sections. tokio::sync::Mutex is async-aware and can be held across await, but that capability is dangerous. RwLock adds reader/writer complexity that rarely helps when critical sections are hot. Sometimes DashMap, atomics, or immutable snapshots are better.

use std::sync::atomic::{AtomicU64, Ordering};

counter.fetch_add(1, Ordering::Relaxed);

An atomic counter avoids locking, but it does not compose multiple fields into one consistent state transition. Know the invariant you are protecting.

Keep critical sections synchronous and tiny

If a standard mutex is appropriate, use it like this:

let snapshot = {
    let state = shared.lock().unwrap();
    state.clone_for_lookup(key)
}; // lock released here

slow_database_call(snapshot).await;

Never call user code, network IO, or another lock acquisition while holding a mutex unless you have a documented ordering rule. Deadlocks in production rarely look like deadlocks at first. They look like gradual latency growth, then all workers waiting, then a restart.

Lock poisoning and panics are part of the design

Standard mutexes poison when a thread panics while holding them. Many codebases call .unwrap() on poisoned locks and turn one panic into total service failure. Decide intentionally: fail fast, recover with into_inner, or use a lock type without poisoning semantics. There is no universal right answer, but there is a wrong one: not knowing which behavior you have.

Consider actor-style state ownership

An actor owns state and receives commands:

enum RegistryMsg {
    Insert(String, u64),
    Get(String, oneshot::Sender<Option<u64>>),
}

The registry task is the only task mutating the map. This serializes access without exposing locks to callers. It also creates a natural place for metrics, persistence, shutdown draining, and invariant enforcement. The tradeoff is a queue hop and response latency. That tradeoff is often worth it.

Field notes

  • If every module shares the same state object, you do not have encapsulation; you have distributed global variables.
  • tokio::sync::Mutex does not prevent logical deadlock; it only cooperates with the scheduler.

Was this lesson helpful?

Sign in to rate