Backbone Cache
A production-ready, high-performance caching library for the Backbone Framework. Provides unified caching interface with Redis and in-memory backends, featuring async/await support, TTL management, and comprehensive statistics.
🚀 Features
- 🔗 Multiple Backends: Redis for distributed caching, Memory for local caching
- ⚡ Async/Await: Full async support built on Tokio
- ⏰ TTL Support: Time-to-live expiration for cache entries
- 🔧 Generic Types: Cache any serializable Rust data structures
- 📊 Statistics: Comprehensive cache statistics and monitoring
- 🔒 Thread-Safe: Safe concurrent access with proper locking
- 🎯 Batch Operations: Support for mget, mset, mdelete
- 🔑 Key Prefixing: Built-in multi-tenant support
- 🏗️ Production-Ready: Robust error handling and connection management
📋 Quick Start
Installation
Add to your Cargo.toml:
[]
= "2.0"
= { = "1.0", = ["full"] }
= { = "1.0", = ["derive"] }
Basic Usage
use ;
use ;
async
🏗️ Overview
Backbone Cache provides a unified caching interface that abstracts away the complexity of different caching backends while maintaining high performance and reliability.
Architecture
┌─────────────────────────────────────────────────────────────┐
│ Application Code │
└─────────────────────┬───────────────────────────────────────┘
│
┌─────────────────────▼───────────────────────────────────────┐
│ Cache Trait (Unified Interface) │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ set() | get() | delete() | exists() | ttl() | clear() │ │ │
│ │ mget() | mset() | mdelete() | stats() │ │ │
│ └─────────────────────────────────────────────────────────┘ │
└─────────────────────┬───────────────────────────────────────┘
│
┌─────────────┼─────────────┐
│ │ │
┌───────▼───────┐ ┌───▼───────┐ ┌───▼───────┐
│ Redis │ │ Memory │ │ Future │
│ Backend │ │ Backend │ │ Backend │
│ │ │ │ │ │
└──────────────┘ └───────────┘ └───────────┘
Key Components
- Cache Trait: Generic interface defining caching operations
- RedisCache: Production-ready distributed caching backend
- MemoryCache: High-performance in-memory caching backend
- CacheEntry: Metadata container for cache entries
- CacheStats: Comprehensive statistics and monitoring
- CacheConfig: Flexible configuration options
📚 Usage Examples
Redis Cache
use ;
// Basic Redis connection
let cache = new.await?;
// With configuration
let cache = with_config.await?;
// Store data with TTL
cache.set.await?;
// Batch operations
let keys = vec!;
let results = cache..await?;
let entries = vec!;
cache.mset.await?;
Memory Cache
use MemoryCache;
// With entry limit
let cache = new; // 50k entries max
// Unbounded memory cache
let cache = new;
// Usage is identical to Redis cache
cache.set.await?; // No expiration
let cached_config: = cache.get.await?;
Key Management
use CacheKey;
// Namespace-based keys
let user_key = user; // "user:123"
let session_key = session; // "session:abc123"
// Custom namespace
let api_key = build;
// API response caching
let response_key = api_response;
Statistics and Monitoring
// Get cache statistics
let stats = cache.stats.await?;
println!;
println!;
println!;
// Statistics include:
// - Hit rate percentage
// - Total entries count
// - Hits/misses counters
// - Sets/deletes counters
// - Memory usage (Redis)
🔧 Technical Details
Async/Await Support
All cache operations are fully async and built on Tokio:
Thread Safety
- RedisCache: Uses Redis connection manager with built-in thread safety
- MemoryCache: Uses
Arc<RwLock<T>>for safe concurrent access
Error Handling
Comprehensive error types with proper error propagation:
TTL Management
Flexible time-to-live support:
// Set with 1 hour expiration
cache.set.await?;
// Set without expiration
cache.set.await?;
// Check TTL
let ttl: = cache.ttl.await?;
match ttl
// Set/extend TTL
let extended = cache.expire.await?; // 2 hours
Memory Management
Memory cache includes intelligent eviction strategies:
// LRU (Least Recently Used) eviction
let cache = new; // 1000 entries max
// Automatic cleanup of expired entries
// Background cleanup runs on each operation
// Memory-efficient storage with Vec<u8> for serialized data
Performance Characteristics
| Operation | Redis Cache | Memory Cache |
|---|---|---|
| Set | ~1ms (network) | ~10μs (local) |
| Get | ~1ms (network) | ~5μs (local) |
| mset | O(n) network | O(n) local |
| mget | O(n) network | O(n) local |
| Memory | Redis cluster | Process memory |
| Persistence | Durable | Ephemeral |
| Scalability | Horizontal | Single node |
Configuration Options
🏃♂️ Performance Benchmarks
Memory Cache Benchmarks
| Operation | Latency | Throughput |
|---|---|---|
| Set | ~5-10μs | ~100k ops/sec |
| Get | ~3-8μs | ~125k ops/sec |
| Delete | ~4-6μs | ~160k ops/sec |
| Cleanup | ~50-100μs | Background |
Redis Cache Benchmarks
| Operation | Latency | Throughput |
|---|---|---|
| Set | ~0.8-2ms | ~500 ops/sec |
| Get | ~0.6-1.5ms | ~650 ops/sec |
| Mset (10) | ~3-8ms | ~1250 ops/sec |
| Mget (10) | ~2-6ms | ~1500 ops/sec |
Note: Benchmarks performed on local development environment with Redis 6.2
🔒 Security Considerations
Key Prefixing
Use key prefixing to avoid conflicts in shared Redis instances:
let cache = with_config.await?;
// Keys will be prefixed: "myapp:prod:v1:user:123"
Connection Security
// With authentication
let cache = new.await?;
// With SSL/TLS
let cache = new.await?;
Data Serialization
All data is serialized using serde_json:
// Data is automatically serialized/deserialized
cache.set.await?;
📊 Monitoring and Observability
Statistics
Comprehensive statistics for monitoring:
let stats = cache.stats.await?;
// Key metrics
println!;
println!;
println!;
println!;
// Operation counters
println!;
Logging
Integration with tracing for observability:
use ;
Health Checks
Redis connection health monitoring:
🧪 Testing
Unit Tests
Integration Tests
🚀 Production Deployment
Environment Variables
# Redis Configuration
REDIS_URL=redis://redis-cluster.company.com:6379
REDIS_PASSWORD=your_password_here
REDIS_DB=0
# Cache Configuration
CACHE_DEFAULT_TTL=3600
CACHE_MAX_MEMORY_ENTRIES=50000
CACHE_KEY_PREFIX=myapp:prod
Docker Configuration
FROM rust:1.70 as builder
WORKDIR /app
COPY . .
RUN cargo build --release
FROM debian:bullseye-slim
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/target/release/cache-service /usr/local/bin/cache-service
EXPOSE 8080
CMD ["cache-service"]
Kubernetes Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: cache-service
spec:
replicas: 3
selector:
matchLabels:
app: cache-service
template:
metadata:
labels:
app: cache-service
spec:
containers:
- name: cache-service
image: your-registry/cache-service:latest
ports:
- containerPort: 8080
env:
- name: REDIS_URL
value: "redis://redis-cluster:6379"
- name: CACHE_DEFAULT_TTL
value: "3600"
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
🔧 Advanced Usage
Custom Cache Implementation
use async_trait;
use ;
Cache Decorator Pattern
Cache Warming
async
🤝 Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Setup
# Clone repository
# Install dependencies
# Run tests
# Run benchmarks
# Check formatting
# Run clippy
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🔗 Related Projects
- Backbone Framework - The main framework
- Backbone Auth - Authentication module
- Backbone Config - Configuration management
📞 Support
Made with ❤️ for the Backbone Framework