How to Implement a Static Cache in Rust
In this article
A static cache in Rust stores computed values in a global, lazily-initialized container so they are computed once and reused across the whole program. This is useful for expensive constants, configuration data, or precomputed tables. You'll typically use the once_cell or std::sync::OnceLock (stable since Rust 1.70) to achieve thread-safe lazy initialization. This guide walks you through implementing a simple static cache using OnceLock and a HashMap, then covers common pitfalls and troubleshooting.
What You'll Need
- Rust installed (1.70 or later for
OnceLock; if using older, addonce_cellcrate). - Basic familiarity with Rust ownership, lifetimes, and traits.
- For the
once_cellapproach, addonce_cell = "1"to yourCargo.toml.
Step-by-Step
- Decide what to cache. Identify the data you want to compute once and reuse. For example, a function that reads a configuration file or generates a large lookup table.
- Choose your storage type. For a simple value, use
OnceLock<T>. For a key-value cache, useOnceLock<HashMap<K, V>>or aMutexinside if you need to mutate after initialization. Static caches are usually immutable after first fill. - Declare the static variable. At module level, write something like:
use std::sync::OnceLock; static CACHE: OnceLock<HashMap<String, u64>> = OnceLock::new(); - Write an accessor function. This function will lazily initialize the cache on first call. Use
get_or_initorget_or_try_init(if fallible). Example:fn get_cache() -> &'static HashMap<String, u64> { CACHE.get_or_init(|| { // build the map, e.g., from a file or computation let mut m = HashMap::new(); m.insert("key".to_string(), 42); m }) } - Use the cache. Call
get_cache()anywhere in your program. The first call initializes, subsequent calls return the same reference.fn main() { let cache = get_cache(); println!("{}", cache["key"]); } - Handle fallible initialization (optional). If your initialization can fail (e.g., reading a file), use
get_or_try_initwhich returns aResult. Example:fn get_cache() -> Result<&'static HashMap<String, u64>, io::Error> { CACHE.get_or_try_init(|| { let content = std::fs::read_to_string("config.txt")?; // parse and build map Ok(map) }) } - Consider using
once_cellfor older Rust. If you can't useOnceLock, addonce_celland useonce_cell::sync::Lazy<T>orOnceCell. The API is similar.use once_cell::sync::Lazy; static CACHE: Lazy<HashMap<String, u64>> = Lazy::new(|| { ... });
Common Mistakes
- Using
static mut. This is unsafe and not thread-safe. Always useOnceLockorLazy. - Forgetting that
OnceLockis immutable after init. If you need to update the cache after first fill, you need aMutexorRwLockinside theOnceLock. - Initializing with a closure that borrows non-static data. The closure must return a value that lives for
'static. You cannot capture local references. - Calling
get_or_initrecursively. If the initialization closure itself calls the accessor, you'll get a deadlock or panic. Avoid recursion. - Using
HashMapwithout a hasher that isSend + Sync. The defaultRandomStateis fine, but if you use a custom hasher, ensure it is thread-safe.
Tips
- Prefer
OnceLockoverLazyif you are on Rust 1.70+; it's standard and avoids an extra dependency. - If your cache is large, consider using
Boxinside to avoid copying. - For read-heavy workloads, use
RwLockinstead ofMutexif you need mutability after init. - Use
get_or_try_initfor fallible setups to avoid panics. - Test your cache initialization with multiple threads to ensure it's truly thread-safe.
Troubleshooting
- Compile error:
OnceLocknot found. Ensure your Rust is 1.70+. If not, useonce_cellcrate. - Panic:
OnceLockalready initialized. This happens if you callsetmanually after init. Useget_or_initinstead. - Deadlock when initializing. The initialization closure must not call the accessor again. If it does, use a separate static for the inner data.
- Borrowing issues. The returned reference is
&'static, so you cannot store it in a struct with a non-static lifetime. Instead, store the accessor function or re-fetch each time. - Cache not updating. If you need to refresh, you cannot with
OnceLock. Use aMutexand check a timestamp or version.
Frequently Asked Questions
Can I use a static cache with non-static data?
No, the cache must hold 'static data. If you need to store references, they must have 'static lifetime, which usually means leaking or using Box::leak.
Is OnceLock faster than Lazy?
They are similar. OnceLock is part of std and uses a fast path. Lazy from once_cell is also efficient. Benchmark if performance is critical.
How do I make a cache that can be cleared?
You can't with OnceLock. Use a Mutex<Option<HashMap>> and reset to None when needed.
Can I use a static cache in a library?
Yes, but be careful: each crate using the library gets its own copy of the static. If you need a global shared cache across crates, use a crate like ctor or a global registry, but that's more complex.
What if my initialization is expensive and I want to show progress?
You can't easily show progress inside get_or_init because it blocks. Consider initializing eagerly at startup using std::thread::spawn and OnceLock::set before main work begins.
Is it safe to use HashMap in a static cache?
Yes, as long as it's behind OnceLock and never mutated after initialization. The default hasher is thread-safe.