← Back to Chapters

Setting Up Redis or Memcached with Django

⚡ Setting Up Redis or Memcached with Django

? Quick Overview

To boost the performance of your Django app, integrate caching systems like Redis or Memcached. These in-memory stores cache data efficiently, reducing database load and speeding up data retrieval.

? Key Concepts

  • Redis supports persistence and advanced data structures.
  • Memcached focuses on high-speed temporary caching.

? Syntax / Theory

Django caching is configured via the CACHES setting. Each backend defines how data is stored and retrieved.

? Setting Up Redis with Django

? View Code Example
# Install Redis client and Django integration
pip install redis django-redis
? View Code Example
# Install Redis server on Ubuntu
sudo apt-get install redis-server
? View Code Example
# Configure Redis cache backend in Django
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379/1',
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
}
}
}

? Setting Up Memcached with Django

? View Code Example
# Install Memcached Python clients
pip install python-memcached django-pylibmc
? View Code Example
# Install Memcached server on Ubuntu
sudo apt-get install memcached
? View Code Example
# Configure Memcached cache backend in Django
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}

? Live Output / Explanation

Once configured, Django automatically stores frequently accessed data in memory, significantly reducing response times.

? Interactive Simulator: Cache vs. Database

Click "Fetch Data" to simulate a request. First click hits the DB (slow). Second click hits the Cache (fast).

?️ Database (Slow: ~2000ms)
➡️
Redis Cache
Empty
➡️
? App View
Waiting for input...

? Use Cases

  • Session storage
  • API response caching
  • Template fragment caching

✅ Tips & Best Practices

  • Use Redis when persistence is required.
  • Prefer Memcached for lightweight temporary caching.
  • Monitor cache hit/miss ratios.

? Try It Yourself

  • Configure Redis locally and cache a queryset.
  • Experiment with cache expiration.
  • Compare performance with and without caching.