What is `cached` and why is it needed?
The cached library is a powerful and flexible tool for caching function call results in Rust. It allows you to significantly speed up program execution by avoiding repeated computations of expensive operations (e.g., database queries, large data computations, external API calls). Caching is especially useful in web servers, game engines, analytical systems, and any applications where the same data is requested multiple times.
Installation
Add the dependency to your Cargo.toml:
[dependencies]cached = "0.48"After that, run cargo build — the library is ready to use.
Main Features
- Function caching — automatic saving of function call results based on its arguments.
- TTL (Time To Live) — set the cache lifetime, after which data is automatically removed.
- Maximum cache size — limit the number of stored entries (LRU heuristic).
- Async support — work with async functions via
cached::async. - Stores — built-in support for Redis, Memcached, file cache, and in-memory store.
Rust Code Example
use cached::proc_macro::cached;use std::time::Duration;
// Cache a function with a TTL of 60 seconds and a maximum of 10 entries#[cached( time = 60, size = 10, key = "u32", convert = r#"{ _input }"#)]fn expensive_computation(input: u32) -> String { println!("Computing for {}", input); std::thread::sleep(Duration::from_secs(2)); format!("Result for {}", input)}
fn main() { // First call — computation (2 seconds) println!("{}", expensive_computation(42)); // Second call — instant return from cache println!("{}", expensive_computation(42));}On the first call to expensive_computation(42), the function executes (2-second delay), and on the second call, the result is instantly retrieved from the cache.
When to Use
The cached library is ideal for:
- Speeding up frequently called functions with unchanged arguments.
- Reducing load on databases or external services.
- Implementing memoization in recursive algorithms (e.g., Fibonacci numbers).
- Creating caching proxy layers in APIs.
Avoid caching if data changes frequently or the result depends on external state (time, randomness).
Conclusion
cached is a minimalist yet powerful library that solves 90% of caching tasks in Rust. Thanks to macros, it requires no boilerplate code and integrates easily into any project. Install it today and feel the performance boost!