skip to content

As a Rust lead, would you keep one `Mutex<HashMap>` for a hot rate limiter, shard it, or standardise on `parking_lot::Mutex`, and how would you decide?

level: principalimportance: should knowfreq 30%

answer

  1. measure contention first
  2. shrink the critical section
  3. N shards routed by hash
  4. one shard per request
  5. std futex lock vs parking_lot

basics

~20 s

Keep one Mutex<HashMap> until profiles show lock contention, shrink the critical section first, then shard by client hash with one lock per request. Default to std's lock and admit parking_lot only for a measured need or a feature std lacks.

solid answer

~40 s

I would start with `Arc<Mutex<HashMap<String, u32>>>` because it is obviously correct, and change it only on evidence such as threads parked on the lock or latency that worsens with core count. The cheapest fix is a shorter critical section: allocate keys and hash before `lock()`, never hold the guard across I/O. If contention remains, shard into `Box<[Mutex<HashMap<..>>]>` routed by `BuildHasher::hash_one`, with a rule that a request locks one shard and multi-shard work locks in index order. On the lock type, std is a sound default now: futex-based on Linux since Rust 1.62, `const fn new` since 1.63. `parking_lot` drops poisoning and adds fairness, `MutexGuard::map` and upgradable reads, so I would admit it per need and record the choice.

code

rust · 40 lines
rust
use std::collections::HashMap;
use std::hash::{BuildHasher, RandomState};
use std::sync::Arc;
use std::thread;

use parking_lot::Mutex; // lock() returns the guard itself: no poisoning

struct ShardedLimiter {
    hasher: RandomState,
    shards: Box<[Mutex<HashMap<String, u32>>]>,
}

impl ShardedLimiter {
    fn new(n: usize) -> Self {
        let shards = (0..n).map(|_| Mutex::new(HashMap::new())).collect();
        Self { hasher: RandomState::new(), shards }
    }

    fn allow(&self, client: &str, limit: u32) -> bool {
        let i = self.hasher.hash_one(client) as usize % self.shards.len();
        let key = client.to_owned(); // allocate before taking the lock
        let mut shard = self.shards[i].lock(); // one shard per call, never two
        let hits = shard.entry(key).or_insert(0);
        *hits += 1;
        *hits <= limit
    }
}

fn main() {
    let limiter = Arc::new(ShardedLimiter::new(16));
    let workers: Vec<_> = (0..4)
        .map(|t| {
            let limiter = Arc::clone(&limiter);
            let client = format!("client-{}", t % 2);
            thread::spawn(move || (0..10).filter(|_| limiter.allow(&client, 15)).count())
        })
        .collect();
    let allowed: usize = workers.into_iter().map(|w| w.join().unwrap()).sum();
    println!("allowed {allowed} of 40"); // two clients, 20 hits each, limit 15
}

go deeper

for a junior

Recall that one Mutex shared by every request serialises them, and that several smaller locks can let requests proceed in parallel.

for a middle

Explain how to route a key to a shard with a BuildHasher and why work should not be done while holding a guard.

for a senior

Diagnose contention from profiles, keep one shard per request with a fixed order for multi-shard work, and know std's futex lock and const new.

for a principal

Own the defaults: when sharding is required, std vs parking_lot and the poisoning stance, the lock-ordering rule, and the metric that would reopen the decision.

## Start from the measurement, not the type A rate limiter keyed by client id is a textbook hot lock: every request on every thread takes it, and every access writes, so an `RwLock` does not help. `Arc<Mutex<HashMap<String, u32>>>` is still the right *first* version — it is obviously correct and easy to review. The decision a lead owns is what evidence justifies something more complex, and which lock type the codebase uses by default. Evidence worth asking for: - profiles showing threads parked in the mutex's lock path, or latency that grows with core count while CPU stays idle; - the length of the critical section: allocating a `String` key, formatting a log line or calling into another component while holding the guard inflates contention more than the lock type ever will; - the shape of the traffic: a few very hot clients concentrate contention on one key, which sharding alone cannot fix; - whether the hot path needs the map at all — a per-thread counter merged periodically, or an atomic counter (the material on atomics), may remove the lock entirely. ## Option one: shorten the critical section Before changing any type: 1. Build owned keys and compute hashes **before** calling `lock()`. 2. Hold the guard only for the lookup and update; never across I/O. 3. Move cleanup of expired windows to a background sweep that takes the lock in short slices. This often settles the problem with no structural change. ## Option two: shard the map Sharding replaces one `Mutex<HashMap>` with N of them, `Box<[Mutex<HashMap<String, u32>>]>`, and routes each client by hash: `shards[hasher.hash_one(client) as usize % shards.len()]` using a `BuildHasher` such as `RandomState`. Two requests contend only when their clients land in the same shard. | Design | Contention | Cost | |---|---|---| | One `Mutex<HashMap>` | every request serialises | simplest; global operations are trivial | | N shards of `Mutex<HashMap>` | only same-shard requests | global reads (a total count, a sweep) must visit every shard | | Lock-free or per-thread counters | almost none | harder to review; approximate or delayed totals | Sharding brings one Rust-relevant rule. Each request must lock **exactly one** shard. Any operation that needs two or more — a sweep that moves entries, a consistent snapshot — must lock them in a fixed order, such as ascending index, or two threads can each hold one shard and wait for the other forever. Rust's type system does not prevent deadlocks; they are safe code that never finishes. `parking_lot` offers an optional `deadlock_detection` feature whose `check_deadlock` reports such cycles at run time, usually enabled only in test or debug builds. ## The other default: std vs `parking_lot` The second lead decision is which `Mutex` the codebase reaches for. The trade-offs have shifted over recent releases: - Since **Rust 1.62**, std's `Mutex` on Linux is a small futex-based lock with no allocation (Windows followed in 1.78); on macOS and other pthread targets it still lazily boxes a pthread mutex. - Since **Rust 1.63**, `Mutex::new` is a `const fn`, so a `static` lock no longer needs a crate. - std **poisons** on panic and its `lock()` returns `LockResult`; `parking_lot::Mutex::lock()` returns the guard directly and simply releases the lock on panic. - `parking_lot` adds eventual fairness, a 1-byte `Mutex`, `MutexGuard::map` (still unstable in std), `upgradable_read()` on its `RwLock`, and the deadlock detector. Its own docs still say std boxes its mutex — true only on pthread platforms today. A defensible default: **std locks everywhere**, with `parking_lot` admitted where a measured need or one of its features (fair unlocking, guard mapping, upgradable reads) justifies a dependency. Mixing both is legal, but the guard types differ and poisoning behaves differently, so the choice should be written down; clippy's `disallowed_types` can enforce it. ## What to write down - When a lock is allowed to be global and when sharding is required. - Which `Mutex` type is the default and how poisoning is handled. - The lock-ordering rule for any code that takes more than one lock. - The metric — lock wait time or tail latency — that would reopen the decision.

  • How many shards would you start with, and does it matter that the count is a power of two?
    A small multiple of the worker thread count, for example 4x, is a reasonable start; beyond that, extra shards cost memory and make global sweeps slower with little contention gain. A power of two lets `% len` become a mask, but with a good hasher the difference is minor next to the lock itself. Measure lock wait time before and after rather than guessing.
  • What changes for a team if it swaps `std::sync::Mutex` for `parking_lot::Mutex` across the codebase?
    Every `lock().unwrap()` becomes `lock()`, and a panic mid-update no longer poisons the lock, so later threads read whatever half-written state was left. Guard types change, so APIs that expose guards break. The team gains fairness controls, guard mapping and upgradable reads, and adds a dependency to audit.

  • parking_lot is always faster, so std's Mutex should never be used
  • An RwLock fixes contention on a map where every request writes
  • Rust's borrow checker rules out lock-order deadlocks between shards
  • std's Mutex still needs a crate to be used in a static
  • Sharding needs no extra rules because each shard is just another Mutex

Assumes Rust 1.99 and parking_lot 0.12.5; std's futex Mutex dates from 1.62 on Linux and 1.78 on Windows, const Mutex::new from 1.63.