skip to content

As a Rust lead, when do you allow a process-wide `LazyLock` or `OnceLock` global in a service, and when do you require passing state explicitly?

level: principalimportance: should knowfreq 32%

answer

  1. immutable and derivable: fine as a global
  2. a hidden dependency every test shares
  3. set once at startup, read-only after
  4. Arc<Config> in the struct that needs it
  5. a poisoned LazyLock never recovers

basics

~20 s

Allow a global when the value is immutable and self-contained, such as a table of compiled patterns or a process-wide facility set once at startup. Require explicit passing, usually an Arc<Config> field or a parameter, for anything tests vary, anything per tenant or request, and anything that holds mutable state.

solid answer

~60 s

A `static` `LazyLock` or `OnceLock` is cheap to write and safe, but it is a hidden input: no signature shows it, and every test in a `cargo test` binary shares it, because tests run in parallel threads in one process. I allow it for values that are immutable and derivable from the program alone, such as compiled regex tables or lookup maps, and for facilities that are genuinely process-wide and set once in `main`, such as the logger or a metrics registry. I require explicit passing for configuration, clients, pools and anything mutable: the service struct owns an `Arc<Config>` or takes `&Config`, so a test builds its own value and two configurations can coexist. A `OnceLock` set in `main` is the compromise when a deep call path needs read-only startup data, with `set` returning `Err` on a second call. I also forbid fallible work in a `LazyLock` initialiser: if it panics the lock is poisoned and every later access panics, so loading a file belongs in `main`, where the error can be reported.

code

rust · 36 lines
rust
use std::sync::{Arc, OnceLock};

#[derive(Debug)]
struct Config {
    db_url: String,
    max_conns: u32,
}

// Global: set once at startup, read anywhere. Hidden dependency, shared by every test.
static CONFIG: OnceLock<Config> = OnceLock::new();

fn pool_size_global() -> u32 {
    CONFIG.get().expect("config not initialised").max_conns
}

// Explicit: the dependency is in the signature, and each test builds its own.
struct Service {
    config: Arc<Config>,
}

impl Service {
    fn pool_size(&self) -> u32 {
        self.config.max_conns
    }
}

fn main() {
    let cfg = Config { db_url: "db://primary/app".into(), max_conns: 16 };
    CONFIG.set(cfg).expect("set once");
    let again = CONFIG.set(Config { db_url: String::new(), max_conns: 1 });
    println!("second set is_err: {}", again.is_err());
    println!("global: {}", pool_size_global());

    let svc = Service { config: Arc::new(Config { db_url: "db://test".into(), max_conns: 2 }) };
    println!("explicit: {} ({})", svc.pool_size(), svc.config.db_url);
}

go deeper

for a junior

Know that LazyLock and OnceLock build a global once and that a static's initialiser cannot read a value computed in main.

for a middle

Explain why tests in one binary share globals and why a global config makes a function's dependencies invisible.

for a senior

Choose between a static LazyLock, a OnceLock set in main and an Arc<Config> field for a concrete service, and handle initialisation failure.

for a principal

Set and enforce the rule: which state may be global, how it is initialised, and how libraries and tests receive state instead.

## What a global costs, even when it is safe With the standard library's `LazyLock` and `OnceLock`, a global no longer needs `lazy_static!` or `unsafe`. That makes globals easy to add, which is exactly why a lead needs a rule. The costs are not about memory safety: - **Hidden dependencies.** A function that reads `CONFIG.get()` declares nothing in its signature; a reviewer cannot see what it depends on. - **Shared test state.** `cargo test` runs the tests of one binary in parallel threads of one process, and the Rust Book warns that tests must not depend on shared state. A `OnceLock` set by one test is set for all of them, and the first test to run decides its value. - **One value per process.** Two tenants, two databases or a staging and a production client side by side need two values; a global allows one. - **Unrecoverable initialisation failure.** If a `LazyLock` initialiser panics, the lock is poisoned and, as the standard library documents, every later access panics. A missing file read inside the initialiser therefore crashes far from `main`. - **Initialisation order hidden in time.** A `LazyLock` runs on first use, so the cost and the failure land in whichever request touches it first. ## Where a global earns its place The pattern is right when the value is **immutable** and either **derivable from the program alone** or **genuinely one per process**: - A table of compiled regular expressions, a parsed lookup map embedded with `include_str!`, a precomputed table. Nothing varies between tests or tenants, and the initialiser cannot fail at run time except by a bug. - Process-wide facilities that the ecosystem already treats as global, such as the installed logger or a metrics registry, set once at the top of `main`. - Read-only startup data deep in a call path that would otherwise thread a parameter through ten layers, provided `main` fills a `OnceLock` once and the rest only reads it. ## Where explicit passing is required | State | Rule | Why | |---|---|---| | Configuration that tests vary | field `Arc<Config>` or parameter `&Config` | each test builds its own | | Database pools, HTTP clients | owned by the service struct | lifetime and shutdown are explicit | | Per-tenant or per-request data | parameters or request context | a global holds one value | | Mutable caches and counters | owned by a struct, shared with `Arc` | contention and reset are visible | | Compiled patterns, lookup tables | `static LazyLock` | immutable, derivable, cheap to share | The explicit version costs a field and a constructor argument. It buys a signature that tells the truth, tests that run in parallel without interfering, and the option of a second instance. ## A rule the team can review against 1. **Immutable only.** A global holds no `Mutex` or atomics unless it is a recognised process-wide facility, and a new one needs a sentence in review. 2. **No fallible work in `LazyLock`.** Loading files, reading environment variables or connecting to anything happens in `main`, where an error can be reported; a `OnceLock` then stores the result. 3. **Set once, in one place.** `OnceLock::set` is called from `main` only; it returns `Err` with the rejected value on a second call, which is a bug to surface, not to ignore. 4. **Libraries take parameters.** A library crate never reads an application's global; it takes the value through its API so any binary can use it. 5. **Tests build their own.** If a test needs a different value of something, that thing is not a global. ## The trade-off to state in an interview Globals trade explicitness for convenience. For immutable, self-contained data the convenience is free, because nothing can observe the sharing. For configuration, connections and mutable state the cost appears later, in tests that interfere, in a second tenant the design cannot hold, and in initialisation failures that surface as panics on a random request. The lead's job is to draw that line once and keep new globals on the right side of it.

  • How do you test code that already reads a global you cannot remove yet?
    Wrap the global behind a function or a trait the code calls, add a constructor that takes the value explicitly, and move callers over one module at a time. Until then, tests that need a different value cannot run against the global; run them in a separate test binary or with `--test-threads=1` only as a stopgap.
  • Why not make the configuration a `static LazyLock` that reads the file on first use?
    Because the read can fail. A panic in the initialiser poisons the `LazyLock`, and every later access panics, so the failure surfaces on whichever request touched it first rather than as a clean error from `main`. Load in `main`, report errors there, and store the result in a `OnceLock` or pass it down.

  • Globals are fine in Rust because LazyLock and OnceLock make them memory-safe.
  • Each Rust test gets a fresh copy of every static, so globals never leak between tests.
  • A panicking LazyLock initialiser simply runs again on the next access.
  • Passing Arc<Config> everywhere is always over-engineering compared with one global.