No matter how optimized your SQL queries are, computing the same database calculations for thousands of simultaneous visitors wastes CPU cycles and spikes latency. Django's Caching Framework stores pre-rendered HTML fragments or raw Python objects in high-speed in-memory memory stores like Redis.
Install the modern django-redis client package:
pip install django-redis
# mywebsite/settings.py
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"CONNECTION_POOL_KWARGS": {"max_connections": 100},
"SOCKET_CONNECT_TIMEOUT": 5,
"SOCKET_TIMEOUT": 5,
},
"KEY_PREFIX": "veewom_cache"
}
}
from django.views.decorators.cache import cache_page
# Caches the entire rendered response in Redis for 15 minutes (900 seconds)
@cache_page(60 * 15)
def homepage_view(request):
featured_articles = BlogPost.objects.published().featured()[:5]
return render(request, 'home.html', {'articles': featured_articles})
{% load cache %}
<!-- Cache this expensive category sidebar widget for 1 hour (3600s) -->
{% cache 3600 sidebar_nav %}
<ul class="cat-list">
{% for cat in all_categories %}
<li><a href="{{ cat.get_absolute_url }}">{{ cat.name }} ({{ cat.articles.count }})</a></li>
{% endfor %}
</ul>
{% endcache %}
from django.core.cache import cache
def get_platform_metrics():
# Cache-Aside Pattern:
# 1. Check if key exists in Redis
metrics = cache.get('global_platform_metrics')
if metrics is None:
# 2. Cache miss -> perform heavy calculations
metrics = {
'total_students': User.objects.count(),
'total_tutorials': BlogPost.objects.filter(is_published=True).count(),
}
# 3. Store in Redis for 30 minutes
cache.set('global_platform_metrics', metrics, timeout=60 * 30)
return metrics
Broaden your backend architecture, REST API design, and production engineering expertise:
Configure Redis caching backends and connection pooling.
Optimize queries first before masking inefficiencies with cache layers.
Share Redis instances between caching and message queuing.
Run Redis containers alongside Django in production docker-compose.