skip to content

Why does a Rust counter declared `const REQUESTS: AtomicU64 = AtomicU64::new(0);` and bumped with `fetch_add` on every request always read zero?

level: seniorimportance: should knowfreq 28%

answer

  1. what a const use produces
  2. a temporary per mention
  3. nothing is ever shared
  4. warning since Rust 1.93
  5. value versus place

basics

~20 s

Each mention of a const creates a new temporary copy of its value, so every fetch_add increments a throwaway AtomicU64 and load reads another fresh zero. Declare it static so every call uses one allocation.

solid answer

~40 s

A `const` names a value, not a place: `AtomicU64::new(0)` is inlined at every use, so `REQUESTS.fetch_add(1, Ordering::Relaxed)` creates a temporary atomic, increments it and drops it at the end of the statement, and `REQUESTS.load(..)` reads yet another zero. It compiles because `fetch_add` takes `&self`, and borrowing a temporary is legal. Since Rust 1.93 rustc warns by default with `const_item_interior_mutations` ("each usage of a `const` item creates a new temporary") and suggests a `static`; Clippy's `declare_interior_mutable_const` and `borrow_interior_mutable_const` flag the declaration and the borrows. The fix is `static REQUESTS: AtomicU64 = AtomicU64::new(0);`: one allocation, a `Sync` type, one counter for every thread. Memory ordering is not the bug.

code

rust · 14 lines
rust
use std::sync::atomic::{AtomicU64, Ordering};

const REQUESTS: AtomicU64 = AtomicU64::new(0);

fn handle_request() {
    REQUESTS.fetch_add(1, Ordering::Relaxed);
}

fn main() {
    for _ in 0..3 {
        handle_request();
    }
    println!("requests = {}", REQUESTS.load(Ordering::Relaxed));
}

go deeper

for a junior

Recall that every use of a const is a new copy of its value, so state that must be shared lives in a static.

for a middle

Walk through why fetch_add on a const compiles: it takes &self, and the temporary it borrows is dropped at the end of the statement.

for a senior

Diagnose the zero counter from the symptom, cite the const_item_interior_mutations warning from Rust 1.93, and rule out ordering and overflow.

for a principal

Make the warning a gate: deny const_item_interior_mutations and Clippy's interior-mutable-const lints in CI so this class never reaches production metrics.

## The symptom A request counter, a feature flag or a cache declared as a `const` of an interior-mutable type compiles, runs and never changes. A metrics endpoint reports `requests = 0` under load. Nothing panics and no test that only checks "it compiles" notices. ```rust use std::sync::atomic::{AtomicU64, Ordering}; const REQUESTS: AtomicU64 = AtomicU64::new(0); fn handle_request() { REQUESTS.fetch_add(1, Ordering::Relaxed); } fn main() { for _ in 0..3 { handle_request(); } println!("requests = {}", REQUESTS.load(Ordering::Relaxed)); } ``` ## Why it compiles and does nothing A `const` item is "not associated with a specific memory location" and is "essentially inlined wherever [it is] used" (the Reference). Read `REQUESTS.fetch_add(1, Ordering::Relaxed)` with that rule applied: 1. The compiler substitutes the value `AtomicU64::new(0)` for `REQUESTS`, which creates a **temporary** atomic. 2. `fetch_add` takes `&self`, so it borrows the temporary. A shared borrow is all an atomic needs to change, which is the point of **interior mutability**, so no `mut` is required and nothing is rejected. 3. The temporary is incremented to 1 and dropped at the end of the statement. 4. `REQUESTS.load(Ordering::Relaxed)` creates another temporary, initialised to 0, and reads it. Each mention is its own object, so no two calls ever touch the same counter. The same thing happens with any type that mutates through `&self`: a `const LOCK: Mutex<Vec<u32>>` gives every `LOCK.lock()` a new, empty mutex, and pushes vanish. ## What the toolchain says rustc 1.93 added the warn-by-default lint `const_item_interior_mutations`, "to warn against calls which mutate interior mutable `const` items" (RELEASES.md). On rustc 1.99.1 the program above produces: ```plaintext warning: mutation of an interior mutable `const` item with call to `fetch_add` --> e9.rs:6:5 | 6 | REQUESTS.fetch_add(1, Ordering::Relaxed); | --------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | `REQUESTS` is a interior mutable `const` item of type `Atomic<u64>` | = note: each usage of a `const` item creates a new temporary = note: only the temporaries and never the original `const REQUESTS` will be modified = help: for more details on interior mutability see <https://doc.rust-lang.org/reference/interior-mutability.html> = note: `#[warn(const_item_interior_mutations)]` on by default help: for a shared instance of `REQUESTS`, consider making it a `static` item instead | 3 - const REQUESTS: AtomicU64 = AtomicU64::new(0); 3 + static REQUESTS: AtomicU64 = AtomicU64::new(0); | warning: 1 warning emitted requests = 0 ``` Four details are worth knowing: - The rustc lint fires on the **mutating** call (`fetch_add`, `lock`), not on `load`, which only reads. - Clippy adds `declare_interior_mutable_const` on the declaration and `borrow_interior_mutable_const` on each borrow, so a project that runs Clippy hears about it at the `const` line itself. - A related, older rustc lint, `const_item_mutation`, fires when code takes a `&mut` to a `const`, as in `V.push(3)` on `const V: Vec<u32>`. - Toolchains older than 1.93 predate the lint, so there only Clippy's lints catch the atomic case. ## The fix: a static A `static` represents one allocation, and "all references and raw pointers to the static refer to the same allocation". `AtomicU64` is `Sync`, so it satisfies the bound every shared static has. Changing one keyword fixes the counter: ```rust use std::sync::atomic::{AtomicU64, Ordering}; static REQUESTS: AtomicU64 = AtomicU64::new(0); // A const of an interior-mutable type is fine as an initializer template: const ZERO: AtomicU64 = AtomicU64::new(0); static PER_ROUTE: [AtomicU64; 4] = [ZERO; 4]; fn handle_request(route: usize) { REQUESTS.fetch_add(1, Ordering::Relaxed); PER_ROUTE[route].fetch_add(1, Ordering::Relaxed); } fn main() { for route in [0, 1, 1] { handle_request(route); } println!( "requests = {}, route 1 = {}", REQUESTS.load(Ordering::Relaxed), PER_ROUTE[1].load(Ordering::Relaxed) ); } ``` It prints: ```plaintext requests = 3, route 1 = 2 ``` The snippet also shows the one legitimate job of an interior-mutable `const`: an **initializer template**. The Reference requires the operand of an array repeat expression `[x; N]` to be `Copy`, a `const` block, or a path to a constant item. `AtomicU64` is not `Copy`, so `[AtomicU64::new(0); 4]` fails with E0277, while `[ZERO; 4]` evaluates the constant four times and builds four separate atomics inside one static. An inline `[const { AtomicU64::new(0) }; 4]` does the same without naming a `const`, and Clippy stays quiet about it. ## What is not the cause | Suspect | Why it is innocent | |---|---| | `Ordering::Relaxed` | Relaxed still makes `fetch_add` atomic; it orders other memory, it does not lose increments | | Optimisation removing the call | The release build behaves the same; the program is doing what it says | | Overflow | Each temporary goes from 0 to 1 at most | | Threads | The bug shows in a single thread, as above | In review, treat any `const` whose type contains `Atomic*`, `Mutex`, `RwLock`, `Cell`, `RefCell` or `OnceLock` as a question: is it a template for building statics, or should it be a `static`?

  • In Rust, does `const LOCK: Mutex<Vec<u32>> = Mutex::new(Vec::new());` give the program one shared lock?
    No. Every `LOCK.lock()` locks a brand-new mutex built from the constant's value, so a push through one call is gone by the next, and `LOCK.lock().unwrap().len()` is always 0. rustc 1.99.1 flags each `lock` call with `const_item_interior_mutations`. Declare it `static LOCK: Mutex<Vec<u32>>`, which compiles because `Mutex::new` and `Vec::new` are `const fn`.
  • In Rust, is a `const` of an interior-mutable type ever correct?
    Yes, as an initializer template. `AtomicU64` is not `Copy`, so `static SLOTS: [AtomicU64; 4] = [AtomicU64::new(0); 4];` fails with E0277, but `[ZERO; 4]` with `const ZERO: AtomicU64 = AtomicU64::new(0);` builds four separate atomics. Clippy's `declare_interior_mutable_const` still warns on that `const`; the inline form `[const { AtomicU64::new(0) }; 4]` needs no named const and draws no warning.

  • The counter loses increments because `Ordering::Relaxed` is too weak.
  • A `const` of an atomic type works as a lock-free global counter.
  • rustc refuses to compile a mutating method call on a `const` item.
  • The idiomatic fix is `static mut REQUESTS: u64` updated in `unsafe` blocks.
  • Making the const `pub` would let every module share one counter.

Assumes Rust 1.99; the warn-by-default rustc lint const_item_interior_mutations that flags this call arrived in Rust 1.93.