As a Rust lead, what code-review rule do you set for hand-written atomics and orderings weaker than `SeqCst`, and when do you require `Mutex`, `OnceLock` or a channel instead?
answer
- safe atomics cannot cause UB
- unsafe atomics guard other memory
- name the paired operation
- Miri and weakly ordered CI
- std primitives first
basics
~20 sAllow Relaxed for independent counters in safe code, require std primitives for anything that publishes or guards data, and confine hand-written orderings that guard unsafe access to one reviewed module with documented Release/Acquire pairs and Miri tests.
solid answer
~40 sStart from the fact that a wrong ordering in safe Rust is a logic bug, never undefined behaviour, while a wrong ordering that guards `unsafe` access to non-atomic memory is a data race. So: tier one, `Relaxed` counters, gauges and ids are fine anywhere. Tier two, flags and pointers that publish or guard data use `OnceLock`, `LazyLock`, `Mutex`, `RwLock` or a channel, which already contain correct orderings; a reviewer asks why std does not fit before accepting a custom one. Tier three, any hand-written `Acquire`/`Release`/`AcqRel` protocol lives in one small module with a comment on every atomic naming the operation it pairs with, a `SAFETY` argument for each dereference, Miri tests, and a second reviewer who knows the memory model. `SeqCst` is acceptable as a default but not as a substitute for the argument.
go deeper
Recall that std's Mutex, OnceLock and channels already use correct orderings, so most code never needs a custom ordering.
Explain why Relaxed counters are safe in safe Rust and why publishing data needs a Release and Acquire pair or a std primitive.
Review tier 3 code by matching each Release to its Acquire, checking every SAFETY comment, and running it under Miri and on a weakly ordered machine.
Set the tiers, decide who may approve custom protocols, and weigh measured speed against the lasting review and bus-factor cost of hand-written atomics.
## The decision a lead owns Atomics are cheap to write and expensive to review. A team needs a rule that lets engineers use them where they are easy and safe, and stops the clever cases from reaching production unexamined. The rule is judgment, not a single right answer, but in Rust it can lean on one property other languages lack. ## The Rust-specific fact the rule builds on The memory model in `core::sync::atomic` defines a **data race** as conflicting accesses, at least one of them **non-atomic**, where neither happens-before the other, and names data races and partially overlapping mixed-size atomic accesses as the memory model's sources of undefined behaviour. Two consequences follow: - **Safe atomic code cannot cause undefined behaviour.** Every access to an atomic is atomic, so a wrong ordering there can produce a wrong answer — a stale flag, a lost update from `load` plus `store` — but not UB. - **Orderings become safety-critical exactly where they guard non-atomic memory**: a raw pointer published through `AtomicPtr`, an `UnsafeCell` behind a lock flag, a buffer slot claimed by `compare_exchange`. All of those need `unsafe` to touch the data. So the review burden can be placed where `unsafe` already draws attention. ## A three-tier rule | Tier | What it covers | Rule | |---|---|---| | 1. Independent values | request counters, gauges, id generators, "shutdown requested" hints that guard no data | any engineer, `Relaxed` allowed, normal review | | 2. Publishing or guarding data | init-once config, shared caches, work queues, mutual exclusion | use `OnceLock`, `LazyLock`, `Mutex`, `RwLock`, `Arc`, `mpsc` or Rayon; a custom version needs a written reason | | 3. Custom protocols | hand-written `Release`/`Acquire` pairs, CAS loops over pointers, fences | one small module, documented pairs, Miri, two reviewers | Tier 2 is where most proposals belong. Std's primitives already contain the orderings — on Linux `std::sync::Mutex` takes the lock with `compare_exchange(UNLOCKED, LOCKED, Acquire, Relaxed)` and only falls back to the kernel under contention — so a custom replacement must beat an uncontended single atomic operation, which it rarely does. Clippy's `mutex_atomic` lint (allow-by-default, in the restriction group) can flag the opposite case, a `Mutex<bool>` or `Mutex<usize>` that guards nothing else and could be an atomic. ## What tier 3 code must carry 1. **A comment on every atomic operation naming its partner**: "Release: pairs with the Acquire load in `get`; publishes the fields written in `build`". An ordering without a named partner is presumed wrong. 2. **A `SAFETY` comment on every dereference** that cites the happens-before edge, not just "the pointer is valid". 3. **Encapsulation**: the atomics and the `unsafe` stay private to the module, and its public API is safe, so the invariant cannot be broken from outside. 4. **Miri in CI**: `cargo +nightly miri test` detects data races on non-atomic accesses in the executions it explores. It is evidence, not proof; it cannot cover every interleaving. 5. **Tests on a weakly ordered target** such as AArch64 where the team has one, because x86-64 hides many missing `Acquire`/`Release` pairs. 6. **A reclamation story** for any pointer that is ever replaced: who frees the old value, and how readers are known to be gone. ## Where `SeqCst` fits The Rustonomicon advises that sequential consistency "is definitely the right choice if you're not confident about the other memory orders". A reasonable policy is: `SeqCst` is the default for tier 3 drafts, and downgrading to `Acquire`/`Release`/`Relaxed` requires the pair comments above and a measured benefit. But `SeqCst` is not a fix for a broken protocol — a check-then-act race or a missing read-modify-write is just as broken with it. ## Trade-offs to weigh - **Speed versus reviewability**: hand-written atomics win only in hot, contended paths, and only measurement shows that; the cost is permanent review load. - **Team depth**: if only one engineer can reason about the memory model, tier 3 code is a bus-factor risk; prefer a well-reviewed crate or std. - **Targets**: some microcontrollers lack compare-and-swap entirely, so portable libraries guard read-modify-write code with `cfg(target_has_atomic = …)`. - **Async code** has its own primitives and its own rules about holding guards; this rule covers OS threads. The rule's message to the team is simple: counters are easy, publishing is std's job, and anything else is a small, documented, Miri-tested module that two people understand.
- An engineer replaces a `Mutex<HashMap<…>>` cache with a hand-written `AtomicPtr` swap and claims a speedup. What do you ask for before approving?A benchmark under realistic contention against the existing `Mutex`, ideally against a sharded lock too; the pair comment and `SAFETY` argument for every load and dereference; Miri tests; and, above all, how old maps are freed while readers may still hold them. Without a reclamation answer the change trades a lock for a use-after-free.
- Why can the rule allow `Relaxed` in tier 1 without a second reviewer?Tier 1 atomics guard no other memory, and every access to them is atomic, so the Rust memory model rules out a data race. The worst outcome of a wrong choice is a slightly stale reading or a logic error such as a lost update, which ordinary review and tests catch. Undefined behaviour needs a non-atomic access, which tier 1 code does not make.
- Switching every ordering to SeqCst makes any hand-written atomic protocol correct.
- A wrong ordering on atomics in safe code is undefined behaviour.
- Tests passing on x86-64 prove the orderings are right.
- Replacing a Mutex with atomics is always a speedup.
- A clean Miri run proves the code has no ordering bugs.