Caching Strategy
Overview
The Chainr platform implements a multi-level caching strategy to improve performance, reduce database load, and enhance user experience.
Cache Layers
1. Application Cache (Redis)
Purpose: Fast access to frequently requested data
Technology: Redis in-memory database
TTL: Configurable per data type
Use Cases:
User sessions
API responses
Computed results
Rate limiting data
2. Database Query Cache
Purpose: Cache expensive database queries
Technology: SQLAlchemy query result caching
TTL: Based on data freshness requirements
Use Cases:
User profile data
Project metadata
Lookup tables
3. CDN Cache
Purpose: Cache static assets and API responses
Technology: Cloud CDN (Cloudflare/AWS CloudFront)
TTL: Based on content type
Use Cases:
Static files (JS, CSS, images)
Public API responses
Documentation pages
4. Browser Cache
Purpose: Client-side caching for better UX
Technology: HTTP cache headers
TTL: Short-term for dynamic content
Use Cases:
User preferences
Frequently accessed data
Cache Keys
Naming Convention
chainr:{service}:{entity}:{id}:{field}
Examples:
chainr:core:user:123:profilechainr:auth:session:abc123:datachainr:ai:document:456:analysis
Cache Invalidation
Time-based Expiration
User sessions: 24 hours
API responses: 5-15 minutes
Static assets: 1 hour to 1 week
Event-based Invalidation
User profile updates → Clear user cache
Document changes → Clear document cache
Project modifications → Clear project cache
Cache Implementation
Redis Configuration
# Redis client setup
redis_client = redis.Redis(
host=os.getenv("REDIS_HOST", "localhost"),
port=int(os.getenv("REDIS_PORT", 6379)),
db=int(os.getenv("REDIS_DB", 0)),
decode_responses=True
)
# Cache decorator
def cached(ttl_seconds: int = 300):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
key = f"{func.__name__}:{hash(str(args) + str(kwargs))}"
cached_result = redis_client.get(key)
if cached_result:
return json.loads(cached_result)
result = func(*args, **kwargs)
redis_client.setex(key, ttl_seconds, json.dumps(result))
return result
return wrapper
return decorator
Cache Warming
Pre-populate frequently accessed data on startup
Background jobs to refresh cache
User-specific cache warming on login
Monitoring & Metrics
Cache Hit/Miss Ratios
Track cache performance
Identify optimization opportunities
Monitor cache size and memory usage
Cache Health Checks
Redis connectivity
Memory usage alerts
Key eviction monitoring
Cache Policies
Cache-aside Pattern
Application checks cache first
Falls back to database if cache miss
Updates cache on database writes
Write-through Cache
Data written to cache and database simultaneously
Ensures cache consistency
Higher write latency
Cache Invalidation Strategies
TTL-based: Automatic expiration
Version-based: Include version in cache key
Event-driven: Invalidate on data changes
Performance Benchmarks
Target cache hit rates:
API responses: > 80%
User data: > 90%
Static assets: > 95%
Troubleshooting
Common Issues
Cache stampedes (thundering herd)
Cache pollution
Memory pressure
Network latency
Solutions
Probabilistic early expiration
Cache warming strategies
Memory limits and eviction policies
Circuit breakers for cache failures