Expand description
Observability and metrics collection for cache operations.
This module provides traits and implementations for monitoring cache behavior, tracking performance metrics, and managing cache entry time-to-live (TTL) policies.
§Module Overview
Cache-kit separates observability into two concerns:
- Metrics (
CacheMetrics): Track hits, misses, performance timing - TTL Policies (
TtlPolicy): Control how long entries remain in cache
§Metrics
Implement the CacheMetrics trait to collect cache statistics for your monitoring system:
ⓘ
use cache_kit::observability::CacheMetrics;
use std::time::Duration;
struct PrometheusMetrics;
impl CacheMetrics for PrometheusMetrics {
fn record_hit(&self, _key: &str, _duration: Duration) {
// Update your metrics backend
// counter!("cache_hits").inc();
// histogram!("cache_latency").record(duration);
}
// ... implement other methods
}
// let expander = CacheExpander::new(backend)
// .with_metrics(Box::new(PrometheusMetrics));Default behavior (if not overridden) uses NoOpMetrics, which logs via the log crate.
§TTL Policies
Control cache entry lifespan with flexible TTL policies:
use cache_kit::observability::TtlPolicy;
use std::time::Duration;
// Fixed TTL for all entries (5 minutes)
let _policy = TtlPolicy::Fixed(Duration::from_secs(300));
// Different TTL per entity type
let _policy = TtlPolicy::PerType(|entity_type| {
match entity_type {
"user" => Duration::from_secs(3600), // 1 hour
"session" => Duration::from_secs(1800), // 30 minutes
_ => Duration::from_secs(600), // 10 minutes default
}
});
// let expander = CacheExpander::new(backend)
// .with_ttl_policy(_policy);§When to Use Each TTL Policy
| Policy | Use Case | Example |
|---|---|---|
Default | Let backend decide | Works with Redis default TTL |
Fixed | Uniform cache duration | All entries expire in 5 minutes |
Infinite | Never expire | Static reference data (rarely used) |
PerType | Type-specific expiry | Users cache 1h, sessions 30m |
§Metrics Methods
The CacheMetrics trait provides hooks for all cache lifecycle events:
record_hit()- Cache hit with operation durationrecord_miss()- Cache miss with operation durationrecord_set()- Cache write with operation durationrecord_delete()- Cache delete with operation durationrecord_error()- Operation failure with error message
All methods receive the cache key and relevant timing/error information.
Structs§
- NoOp
Metrics - Default metrics implementation (no-op).
Enums§
- TtlPolicy
- TTL (Time-to-Live) policy for cache entries.
Traits§
- Cache
Metrics - Trait for cache metrics collection.