Skip to content

rust.unbounded_cache

Stability High

Detects caches without size limits or eviction policies.

Unbounded caches:

  • Memory exhaustion — Cache grows until OOM
  • No eviction — Stale data never removed
  • Unpredictable behavior — Sudden crashes under load
// ❌ Before (unbounded HashMap cache)
use std::collections::HashMap;
use std::sync::RwLock;
lazy_static! {
static ref CACHE: RwLock<HashMap<String, Data>> = RwLock::new(HashMap::new());
}
fn get_or_fetch(key: &str) -> Data {
if let Some(data) = CACHE.read().unwrap().get(key) {
return data.clone();
}
let data = fetch(key);
CACHE.write().unwrap().insert(key.to_string(), data.clone());
data
}
// ✅ After (bounded LRU cache)
use lru::LruCache;
use std::num::NonZeroUsize;
lazy_static! {
static ref CACHE: Mutex<LruCache<String, Data>> =
Mutex::new(LruCache::new(NonZeroUsize::new(1000).unwrap()));
}
fn get_or_fetch(key: &str) -> Data {
let mut cache = CACHE.lock().unwrap();
if let Some(data) = cache.get(key) {
return data.clone();
}
let data = fetch(key);
cache.put(key.to_string(), data.clone());
data
}
  • HashMap used as cache without size limits
  • Missing LRU/TTL eviction
  • Caches without capacity configuration

Unfault can suggest replacing with bounded LRU cache.