Overview
Caching in FKApi provides:- Reduced database load
- Faster API response times
- Lower latency for frequently accessed data
- Improved scalability
- Automatic cache invalidation on data changes
Cache Architecture
Configuration
Redis Setup
Caching is configured infkapi/settings.py:
Cache Timeouts
Different timeout values are used based on data volatility:Cached Endpoints
The following API endpoints implement caching:Club Seasons
- Cache key:
season_club_{club_id} - Timeout: 1 hour (3600s)
- Invalidation: When Club or Kit changes
Club Kits by Season
- Cache key:
kit_club_{club_id}_season_{season_id} - Timeout: 30 minutes (1800s)
- Invalidation: When Kit, Club, or Season changes
Kit Details
- Cache key:
kit_json_{kit_id} - Timeout: 1 hour (3600s)
- Invalidation: When Kit changes
Search Endpoints
All search endpoints cache results:- Cache key:
search_{type}_{keyword} - Timeout: 30 minutes (1800s)
- Invalidation: When corresponding model changes
Cache Key Generation
Cache keys are generated using thegenerate_cache_key() utility in core/cache_utils.py:
Key Generation Features
- Consistent format: Predictable key structure
- Automatic hashing: Keys longer than 200 characters are MD5 hashed
- Prefix support: All keys prefixed with
fkapi: - Type safety: Handles various argument types
Cache Invalidation
Automatic Invalidation
FKApi uses Django signals for automatic cache invalidation. When a model is saved or deleted, related cache entries are automatically invalidated. The invalidation is configured incore/cache_utils.py:
Invalidation Functions
Club Cache
Season Cache
Kit Cache
Search Cache
User Collection Cache
Manual Invalidation
You can manually invalidate cache entries:Cache Warming
Cache warming pre-populates frequently accessed data to improve performance.Manual Warming
Use the management command:Warming Options
Scheduled Warming
Automate cache warming with Celery Beat insettings.py:
core/tasks.py:
Performance Optimization
Query Optimization
Cached endpoints use optimized database queries:Cache Timeouts
Choose appropriate timeouts:| Data Type | Timeout | Reason |
|---|---|---|
| Search results | 30 min | Balance between freshness and performance |
| Kit details | 1 hour | Relatively static once created |
| Club seasons | 1 hour | Infrequently changes |
| User collections | 24 hours | User-specific, large payload |
Memory Management
Monitor Redis memory usage:redis.conf:
Monitoring
Cache Hit Rate
Monitor cache effectiveness:Custom Metrics
FKApi includes Prometheus metrics incore/metrics.py:
Troubleshooting
Cache Not Working
from django.core.cache import cache
cache.set('test_key', 'test_value', timeout=60)
print(cache.get('test_key')) # Should print: test_value
Stale Data in Cache
# Clear specific key
redis-cli del fkapi:kit_json_123
# Clear all keys matching pattern
redis-cli --scan --pattern 'fkapi:kit_*' | xargs redis-cli del
# Clear entire cache (use with caution!)
redis-cli flushdb
High Memory Usage
Best Practices
Cache Key Design
Cache Key Design
- Use consistent naming patterns
- Include entity type in key prefix
- Use
generate_cache_key()utility - Avoid very long keys (>200 chars are hashed)
- Document key patterns
Cache Invalidation
Cache Invalidation
- Rely on automatic signal-based invalidation
- Invalidate related caches (e.g., kit change invalidates club)
- Test invalidation in development
- Monitor stale data issues
- Use manual invalidation sparingly
Timeout Strategy
Timeout Strategy
- Match timeout to data change frequency
- Shorter timeouts for volatile data
- Longer timeouts for static data
- Monitor cache hit rates to optimize
- Consider warming frequently accessed data
Memory Management
Memory Management
- Set Redis memory limits
- Use LRU eviction policy
- Monitor memory usage
- Clear unused keys periodically
- Compress large cache values if needed