Cachelito Async
A flexible and efficient async caching library for Rust async/await functions.
Features
- 🚀 Lock-free caching - Uses DashMap for concurrent access without blocking
- 🎯 Multiple eviction policies - FIFO, LRU, LFU, ARC, Random, and TLRU (Time-aware LRU)
- ⏰ TLRU with frequency_weight - Fine-tune recency vs frequency balance (v0.15.0)
- 💾 Memory-based limits - Control cache size by memory usage (v0.10.1)
- ⏱️ TTL support - Automatic expiration of cached entries
- 📊 Limit control - Set maximum cache size by entry count or memory
- 🔍 Result caching - Only caches
Okvalues fromResulttypes - 🌐 Global cache - Shared across all tasks and threads
- ⚡ Zero async overhead - No
.awaitneeded for cache operations - 📈 Statistics - Track cache hit/miss rates and performance metrics
- 🎛️ Conditional caching - Cache only valid results with
cache_ifpredicates (v0.14.0) - 🔥 Smart invalidation - Tag-based, event-driven, and conditional invalidation (v0.12.0+)
Installation
Add this to your Cargo.toml:
[]
= "0.10.1"
= { = "1", = ["full"] }
Quick Start
use cache_async;
use Duration;
async
async
Examples
Basic Async Caching
use cache_async;
async
Cache with Limit and LRU Policy
use cache_async;
async
Cache with TTL (Time To Live)
use cache_async;
async
Result Caching (Only Ok Values)
use cache_async;
async
Cache Statistics
Track cache performance with built-in statistics:
use ;
async
async
async
Statistics Features:
- Automatic tracking of hits and misses
- Hit/miss rates calculation
- Global registry for all async caches
- Custom cache naming with
nameattribute - Thread-safe counters using
AtomicU64
TLRU with Frequency Weight
Fine-tune the balance between recency and frequency in TLRU eviction decisions:
use cache_async;
// Low frequency_weight (0.3) - emphasizes recency
// Good for time-sensitive data where freshness matters more
async
// High frequency_weight (1.5) - emphasizes frequency
// Good for popular content that should stay cached
async
// Default (omit frequency_weight) - balanced approach
async
Frequency Weight Guide:
< 1.0→ Emphasize recency (time-sensitive data: stock prices, news)= 1.0(default) → Balanced (general-purpose caching)> 1.0→ Emphasize frequency (popular content: trending posts, hot products)
Combining Features
use cache_async;
async
Macro Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
limit |
usize |
unlimited | Maximum number of entries in cache |
policy |
"fifo" | "lru" | "lfu" | "arc" | "random" | "tlru" |
"fifo" |
Eviction policy when limit is reached |
ttl |
u64 |
none | Time-to-live in seconds |
frequency_weight |
f64 |
1.0 | Weight factor for frequency in TLRU (v0.15.0) |
name |
String |
function name | Custom cache identifier |
max_memory |
String |
none | Maximum memory usage (e.g., "100MB") |
tags |
[String] |
none | Tags for group invalidation |
events |
[String] |
none | Events that trigger invalidation |
dependencies |
[String] |
none | Cache dependencies |
invalidate_on |
function | none | Function to check if entry should be invalidated |
cache_if |
function | none | Function to determine if result should be cached |
Eviction Policies
LRU (Least Recently Used) - Default
- Evicts least recently accessed entries
- O(n) performance for cache hits (reordering)
- Best when access patterns matter
- Ideal for temporal locality workloads
FIFO (First In, First Out)
- Evicts oldest entries first
- O(1) performance for all operations
- Best for simple use cases
- Predictable behavior
LFU (Least Frequently Used)
- Evicts least frequently accessed entries
- O(n) performance for eviction (finding minimum frequency)
- O(1) performance for cache hits (increment counter)
- Best for workloads with "hot" data
- Popular items remain cached longer
ARC (Adaptive Replacement Cache)
- Hybrid policy combining LRU and LFU
- Self-tuning based on access patterns
- O(n) performance for eviction and cache hits
- Best for mixed workloads
- Scan-resistant
Random Replacement
- Randomly evicts entries when cache is full
- O(1) performance for all operations
- Minimal overhead, no access tracking
- Best for baseline benchmarks
- Good for truly random access patterns
TLRU (Time-aware Least Recently Used)
- Combines recency, frequency, and time-based expiration
- O(n) performance for eviction and cache hits
- Customizable with
frequency_weightparameter - Formula:
score = frequency^weight × position × age_factor frequency_weight < 1.0: Emphasize recency (good for time-sensitive data)frequency_weight > 1.0: Emphasize frequency (good for popular content)- Best for time-sensitive data with TTL
- Without TTL, behaves like ARC
Policy Comparison:
| Policy | Eviction | Cache Hit | Use Case |
|---|---|---|---|
| LRU | O(1) | O(n) | Recent access matters |
| FIFO | O(1) | O(1) | Simple predictable caching |
| LFU | O(n) | O(1) | Frequency patterns matter |
| ARC | O(n) | O(n) | Mixed workloads, adaptive |
| Random | O(1) | O(1) | Baseline benchmarks |
| TLRU | O(n) | O(n) | Time-sensitive with TTL |
Performance
- Lock-free: Uses DashMap for excellent concurrent performance
- No blocking: Cache operations don't block the async executor
- Minimal overhead: No
.awaitneeded for cache lookups - Memory efficient: Configurable limits prevent unbounded growth
Thread Safety
All caches are thread-safe and can be safely shared across multiple tasks and threads. The underlying DashMap provides excellent concurrent performance without traditional locks.
Comparison with Sync Version
| Feature | cachelito | cachelito-async |
|---|---|---|
| Functions | Sync | Async |
| Storage | Thread-local or Global (RwLock) | Global (DashMap) |
| Concurrency | Mutex/RwLock | Lock-free |
| Scope | Thread or Global | Always Global |
| Best for | CPU-bound, sync code | I/O-bound, async code |
Examples in Repository
async_basic.rs- Basic async cachingasync_lru.rs- LRU eviction policyasync_tlru.rs- TLRU (Time-aware LRU) eviction policy with concurrent operationsasync_concurrent.rs- Concurrent task accessasync_stats.rs- Cache statistics tracking
Run examples with:
Requirements
- Rust 1.70.0 or later
- Arguments must implement
Debugfor key generation - Return type must implement
Clonefor cache storage
License
Licensed under the Apache License, Version 2.0. See LICENSE for details.
Related Crates
cachelito- Sync version for regular functionscachelito-core- Core caching primitivescachelito-macros- Sync procedural macros