User Agents

Web browsers and everyday web tech, explained

How to Implement a Static Cache in Rust

· 4 min read · Cookies and Cache

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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, add once_cell crate).
  • Basic familiarity with Rust ownership, lifetimes, and traits.
  • For the once_cell approach, add once_cell = "1" to your Cargo.toml.

Step-by-Step

  1. 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.
  2. Choose your storage type. For a simple value, use OnceLock<T>. For a key-value cache, use OnceLock<HashMap<K, V>> or a Mutex inside if you need to mutate after initialization. Static caches are usually immutable after first fill.
  3. Declare the static variable. At module level, write something like:
    use std::sync::OnceLock;
    
    static CACHE: OnceLock<HashMap<String, u64>> = OnceLock::new();
  4. Write an accessor function. This function will lazily initialize the cache on first call. Use get_or_init or get_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
        })
    }
  5. 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"]);
    }
  6. Handle fallible initialization (optional). If your initialization can fail (e.g., reading a file), use get_or_try_init which returns a Result. 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)
        })
    }
  7. Consider using once_cell for older Rust. If you can't use OnceLock, add once_cell and use once_cell::sync::Lazy<T> or OnceCell. 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 use OnceLock or Lazy.
  • Forgetting that OnceLock is immutable after init. If you need to update the cache after first fill, you need a Mutex or RwLock inside the OnceLock.
  • 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_init recursively. If the initialization closure itself calls the accessor, you'll get a deadlock or panic. Avoid recursion.
  • Using HashMap without a hasher that is Send + Sync. The default RandomState is fine, but if you use a custom hasher, ensure it is thread-safe.

Tips

  • Prefer OnceLock over Lazy if you are on Rust 1.70+; it's standard and avoids an extra dependency.
  • If your cache is large, consider using Box inside to avoid copying.
  • For read-heavy workloads, use RwLock instead of Mutex if you need mutability after init.
  • Use get_or_try_init for fallible setups to avoid panics.
  • Test your cache initialization with multiple threads to ensure it's truly thread-safe.

Troubleshooting

  • Compile error: OnceLock not found. Ensure your Rust is 1.70+. If not, use once_cell crate.
  • Panic: OnceLock already initialized. This happens if you call set manually after init. Use get_or_init instead.
  • 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 a Mutex and 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.