multi_tier_cache/lib.rs
1//! Multi-Tier Cache
2//!
3//! A high-performance, production-ready multi-tier caching library for Rust featuring:
4//! - **L1 Cache**: In-memory caching with Moka (sub-millisecond latency)
5//! - **L2 Cache**: Distributed caching with Redis (persistent storage)
6//! - **Cache Stampede Protection**: DashMap + Mutex request coalescing
7//! - **Redis Streams**: Built-in support for event streaming
8//! - **Automatic L2-to-L1 Promotion**: Intelligent cache tier promotion
9//! - **Comprehensive Statistics**: Hit rates, promotions, in-flight tracking
10//!
11//! # Quick Start
12//!
13//! ```rust,no_run
14//! use multi_tier_cache::{CacheSystem, CacheStrategy};
15//!
16//! #[tokio::main]
17//! async fn main() -> anyhow::Result<()> {
18//! // Initialize cache system
19//! let cache = CacheSystem::new().await?;
20//!
21//! // Store data with cache strategy
22//! let data = serde_json::json!({"user": "alice", "score": 100});
23//! cache.cache_manager()
24//! .set_with_strategy("user:1", data, CacheStrategy::ShortTerm)
25//! .await?;
26//!
27//! // Retrieve data (L1 first, then L2 fallback)
28//! if let Some(cached) = cache.cache_manager().get("user:1").await? {
29//! tracing::info!("Cached data: {}", cached);
30//! }
31//!
32//! // Get statistics
33//! let stats = cache.cache_manager().get_stats();
34//! tracing::info!("Hit rate: {:.2}%", stats.hit_rate);
35//!
36//! Ok(())
37//! }
38//! ```
39//!
40//! # Features
41//!
42//! - **Multi-Tier Architecture**: Combines fast in-memory (L1) with persistent distributed (L2) caching
43//! - **Cache Stampede Protection**: Prevents duplicate computations during cache misses
44//! - **Redis Streams**: Publish/subscribe with automatic trimming
45//! - **Zero-Config**: Sensible defaults, works out of the box
46//! - **Production-Proven**: Battle-tested at 16,829+ RPS with 5.2ms latency
47//!
48//! # Architecture
49//!
50//! ```text
51//! Request → L1 Cache (Moka) → L2 Cache (Redis) → Compute/Fetch
52//! ↓ Hit (90%) ↓ Hit (75%) ↓ Miss (5%)
53//! Return Promote to L1 Store in L1+L2
54//! ```
55
56use std::sync::Arc;
57use anyhow::Result;
58use tracing::{info, warn};
59
60pub mod backends;
61pub mod cache_manager;
62pub mod traits;
63pub mod builder;
64pub mod invalidation;
65pub mod redis_streams;
66
67// Re-export backend types (maintains backward compatibility)
68pub use backends::{
69 L1Cache, L2Cache, // Type aliases
70 MokaCache, RedisCache, // Default backends
71 DashMapCache, // Additional backends
72};
73
74// Optional backends (feature-gated)
75#[cfg(feature = "backend-memcached")]
76pub use backends::MemcachedCache;
77
78#[cfg(feature = "backend-quickcache")]
79pub use backends::QuickCacheBackend;
80pub use cache_manager::{
81 CacheManager, CacheStrategy, CacheManagerStats,
82 // Multi-tier support (v0.5.0+)
83 TierConfig, CacheTier, TierStats,
84};
85pub use traits::{CacheBackend, L2CacheBackend, StreamingBackend};
86pub use builder::CacheSystemBuilder;
87pub use invalidation::{
88 InvalidationConfig, InvalidationMessage, InvalidationStats,
89 InvalidationPublisher, InvalidationSubscriber,
90};
91pub use redis_streams::RedisStreams;
92
93// Re-export async_trait for user convenience
94pub use async_trait::async_trait;
95
96/// Main entry point for the Multi-Tier Cache system
97///
98/// Provides unified access to L1 (Moka) and L2 (Redis) caches with
99/// automatic failover, promotion, and stampede protection.
100///
101/// # Example
102///
103/// ```rust,no_run
104/// use multi_tier_cache::CacheSystem;
105///
106/// #[tokio::main]
107/// async fn main() -> anyhow::Result<()> {
108/// let cache = CacheSystem::new().await?;
109///
110/// // Use cache_manager for all operations
111/// let manager = cache.cache_manager();
112///
113/// Ok(())
114/// }
115/// ```
116///
117/// # Note on l1_cache and l2_cache Fields
118///
119/// When using multi-tier mode or custom backends, `l1_cache` and `l2_cache`
120/// may be `None`. Always use `cache_manager()` for cache operations.
121#[derive(Clone)]
122pub struct CacheSystem {
123 /// Unified cache manager (primary interface)
124 pub cache_manager: Arc<CacheManager>,
125 /// L1 Cache (in-memory, Moka) - `None` when using custom backends
126 pub l1_cache: Option<Arc<L1Cache>>,
127 /// L2 Cache (distributed, Redis) - `None` when using custom backends
128 pub l2_cache: Option<Arc<L2Cache>>,
129}
130
131impl CacheSystem {
132 /// Create new cache system with default configuration
133 ///
134 /// # Configuration
135 ///
136 /// Redis connection is configured via `REDIS_URL` environment variable.
137 /// Default: `redis://127.0.0.1:6379`
138 ///
139 /// # Example
140 ///
141 /// ```rust,no_run
142 /// use multi_tier_cache::CacheSystem;
143 ///
144 /// #[tokio::main]
145 /// async fn main() -> anyhow::Result<()> {
146 /// // Set environment variable (optional)
147 /// std::env::set_var("REDIS_URL", "redis://localhost:6379");
148 ///
149 /// let cache = CacheSystem::new().await?;
150 /// Ok(())
151 /// }
152 /// ```
153 pub async fn new() -> Result<Self> {
154 info!("Initializing Multi-Tier Cache System");
155
156 // Initialize L1 cache (Moka)
157 let l1_cache = Arc::new(L1Cache::new().await?);
158
159 // Initialize L2 cache (Redis)
160 let l2_cache = Arc::new(L2Cache::new().await?);
161
162 // Initialize cache manager
163 let cache_manager = Arc::new(CacheManager::new(l1_cache.clone(), l2_cache.clone()).await?);
164
165 info!("Multi-Tier Cache System initialized successfully");
166
167 Ok(Self {
168 cache_manager,
169 l1_cache: Some(l1_cache),
170 l2_cache: Some(l2_cache),
171 })
172 }
173
174 /// Create cache system with custom Redis URL
175 ///
176 /// # Arguments
177 ///
178 /// * `redis_url` - Redis connection string (e.g., "redis://localhost:6379")
179 ///
180 /// # Example
181 ///
182 /// ```rust,no_run
183 /// use multi_tier_cache::CacheSystem;
184 ///
185 /// #[tokio::main]
186 /// async fn main() -> anyhow::Result<()> {
187 /// let cache = CacheSystem::with_redis_url("redis://custom:6379").await?;
188 /// Ok(())
189 /// }
190 /// ```
191 pub async fn with_redis_url(redis_url: &str) -> Result<Self> {
192 info!(redis_url = %redis_url, "Initializing Multi-Tier Cache System with custom Redis URL");
193
194 // Initialize L1 cache (Moka)
195 let l1_cache = Arc::new(L1Cache::new().await?);
196
197 // Initialize L2 cache (Redis) with custom URL
198 let l2_cache = Arc::new(L2Cache::with_url(redis_url).await?);
199
200 // Initialize cache manager
201 let cache_manager = Arc::new(CacheManager::new(
202 Arc::clone(&l1_cache),
203 Arc::clone(&l2_cache)
204 ).await?);
205
206 info!("Multi-Tier Cache System initialized successfully");
207
208 Ok(Self {
209 cache_manager,
210 l1_cache: Some(l1_cache),
211 l2_cache: Some(l2_cache),
212 })
213 }
214
215 /// Perform health check on all cache tiers
216 ///
217 /// Returns `true` if at least L1 is operational.
218 /// L2 failure is tolerated (graceful degradation).
219 ///
220 /// # Example
221 ///
222 /// ```rust,no_run
223 /// use multi_tier_cache::CacheSystem;
224 ///
225 /// #[tokio::main]
226 /// async fn main() -> anyhow::Result<()> {
227 /// let cache = CacheSystem::new().await?;
228 ///
229 /// if cache.health_check().await {
230 /// tracing::info!("Cache system healthy");
231 /// }
232 ///
233 /// Ok(())
234 /// }
235 /// ```
236 pub async fn health_check(&self) -> bool {
237 let l1_ok = match &self.l1_cache {
238 Some(cache) => cache.health_check().await,
239 None => true, // If no L1 cache instance, assume OK (using custom backends)
240 };
241
242 let l2_ok = match &self.l2_cache {
243 Some(cache) => cache.health_check().await,
244 None => true, // If no L2 cache instance, assume OK (using custom backends)
245 };
246
247 if l1_ok && l2_ok {
248 info!("Multi-Tier Cache health check passed");
249 true
250 } else {
251 warn!(l1_ok = %l1_ok, l2_ok = %l2_ok, "Multi-Tier Cache health check - partial failure");
252 l1_ok // At minimum, L1 should work
253 }
254 }
255
256 /// Get reference to cache manager (primary interface)
257 ///
258 /// Use this for all cache operations: get, set, streams, etc.
259 pub fn cache_manager(&self) -> &Arc<CacheManager> {
260 &self.cache_manager
261 }
262}