Bird
Raised Fist0
Djangoframework~20 mins

Cache backends (memory, Redis, Memcached) in Django - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Cache Mastery in Django
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
1:30remaining
What is the output of this Django cache code using memory backend?

Consider this Django view code snippet using the default memory cache backend:

from django.core.cache import cache

def get_data():
    cache.set('key', 'value', timeout=5)
    return cache.get('key')

What will get_data() return immediately after setting the cache?

Django
from django.core.cache import cache

def get_data():
    cache.set('key', 'value', timeout=5)
    return cache.get('key')
ANone
BRaises KeyError
C'value'
DEmpty string ''
Attempts:
2 left
💡 Hint

Think about what happens when you set and get a key immediately in the same cache.

📝 Syntax
intermediate
1:30remaining
Which cache backend setting is syntactically correct for Redis in Django?

Which of the following CACHES settings correctly configures Redis as the cache backend in Django?

A"""CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': 'redis://127.0.0.1:6379', } }"""
B"""CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.redis.RedisCache', 'LOCATION': 'redis://localhost:6379', } }"""
C"""CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'memcached://127.0.0.1:11211', } }"""
D"""CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/1', } }"""
Attempts:
2 left
💡 Hint

Redis backend in Django usually uses django_redis.cache.RedisCache and a Redis URL.

🔧 Debug
advanced
2:00remaining
Why does this Memcached cache code raise a connection error?

Given this Django cache setting and code snippet:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

from django.core.cache import cache
cache.set('foo', 'bar')
cache.get('foo')

Running this code raises a connection error. What is the most likely cause?

Django
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

from django.core.cache import cache
cache.set('foo', 'bar')
cache.get('foo')
AMemcached server is not running on 127.0.0.1:11211
BDjango cache API does not support Memcached
CThe backend string is misspelled
DThe cache key 'foo' is too long for Memcached
Attempts:
2 left
💡 Hint

Check if the Memcached service is active and reachable at the specified address.

state_output
advanced
1:30remaining
What is the value of the cache key after expiration with Redis backend?

Assume Redis cache backend is configured with a 1-second timeout. This code runs:

from django.core.cache import cache
cache.set('temp', 'data', timeout=1)
import time
time.sleep(2)
value = cache.get('temp')

What is the value of value after this code runs?

Django
from django.core.cache import cache
cache.set('temp', 'data', timeout=1)
import time
time.sleep(2)
value = cache.get('temp')
ANone
B'data'
CRaises TimeoutError
DEmpty string ''
Attempts:
2 left
💡 Hint

Think about what happens when you get a cache key after its timeout expires.

🧠 Conceptual
expert
2:00remaining
Which cache backend is best suited for sharing cache across multiple Django app instances?

You have multiple Django app servers running behind a load balancer. You want a cache backend that all instances share to keep data consistent. Which cache backend is best suited?

AFile-based cache backend (django.core.cache.backends.filebased.FileBasedCache)
BRedis cache backend (django_redis.cache.RedisCache)
CLocal memory cache backend (django.core.cache.backends.locmem.LocMemCache)
DDummy cache backend (django.core.cache.backends.dummy.DummyCache)
Attempts:
2 left
💡 Hint

Consider which cache backend supports sharing data across multiple machines.

Practice

(1/5)
1. Which Django cache backend stores data temporarily in the server's RAM and is suitable for development or small projects?
easy
A. Memcached cache
B. Redis cache
C. LocMemCache (local memory cache)
D. Database cache

Solution

  1. Step 1: Understand cache backend types in Django

    Django offers several cache backends. LocMemCache stores data in the local memory of the server process.
  2. Step 2: Identify the backend suitable for small or development use

    LocMemCache is simple and fast but only works for a single process, making it ideal for development or small projects.
  3. Final Answer:

    LocMemCache (local memory cache) -> Option C
  4. Quick Check:

    Local memory cache = LocMemCache [OK]
Hint: Local memory cache is for small or dev use only [OK]
Common Mistakes:
  • Confusing Redis with local memory cache
  • Thinking Memcached stores data locally per process
  • Assuming database cache is the default memory cache
2. Which of the following is the correct way to configure Redis as a cache backend in Django's settings.py?
easy
A. "BACKEND": "django.core.cache.backends.locmem.LocMemCache", "LOCATION": "redis://127.0.0.1:6379/1"
B. "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1"
C. "BACKEND": "django.core.cache.backends.memcached.MemcachedCache", "LOCATION": "redis://127.0.0.1:6379/1"
D. "BACKEND": "django.core.cache.backends.filebased.FileBasedCache", "LOCATION": "/var/tmp/django_cache"

Solution

  1. Step 1: Identify the correct backend class for Redis

    Django's Redis cache backend uses "django_redis.cache.RedisCache" as the backend string.
  2. Step 2: Check the location format for Redis

    The location for Redis cache is a URL like "redis://127.0.0.1:6379/1" specifying host, port, and database number.
  3. Final Answer:

    "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1" -> Option B
  4. Quick Check:

    Redis backend uses RedisCache and redis:// URL [OK]
Hint: Redis backend uses RedisCache and redis:// URL [OK]
Common Mistakes:
  • Using Memcached backend string for Redis
  • Using local memory backend with Redis URL
  • Confusing file-based cache with Redis
3. Given this Django cache configuration using Memcached:
"BACKEND": "django.core.cache.backends.memcached.PyMemcacheCache",
"LOCATION": "127.0.0.1:11211"

What will happen if you try to cache a Python dictionary with cache.set('key', {'a': 1}) and then retrieve it with cache.get('key')?
medium
A. The dictionary will be stored and retrieved correctly.
B. A TypeError will occur because Memcached cannot store dictionaries.
C. The dictionary will be converted to a string and retrieved as a string.
D. The cache.get('key') will return None because dictionaries are not serializable.

Solution

  1. Step 1: Understand Memcached serialization in Django

    Django's Memcached backend serializes Python objects automatically using pickle, so dictionaries can be stored and retrieved.
  2. Step 2: Check behavior of cache.set and cache.get with dict

    When you set a dictionary, it is pickled and stored. When you get it, it is unpickled back to the original dictionary.
  3. Final Answer:

    The dictionary will be stored and retrieved correctly. -> Option A
  4. Quick Check:

    Memcached backend serializes objects = works with dict [OK]
Hint: Memcached backend serializes objects automatically [OK]
Common Mistakes:
  • Assuming Memcached only stores strings
  • Thinking dictionaries cause errors in cache
  • Believing cache.get returns string instead of original object
4. You configured Redis cache in Django but get a connection error when running your app. Which of these is the most likely cause?
medium
A. Redis server is not running or unreachable at the specified location.
B. You used Memcached backend string instead of Redis backend string.
C. You forgot to import the cache module in your views.
D. You set the cache timeout to zero.

Solution

  1. Step 1: Identify common causes of Redis connection errors

    Connection errors usually happen if the Redis server is down or the address/port is wrong.
  2. Step 2: Evaluate other options for connection errors

    Using wrong backend string causes config errors, not connection errors. Importing cache or timeout settings do not cause connection failures.
  3. Final Answer:

    Redis server is not running or unreachable at the specified location. -> Option A
  4. Quick Check:

    Connection error = Redis server unreachable [OK]
Hint: Check if Redis server is running and reachable first [OK]
Common Mistakes:
  • Confusing config errors with connection errors
  • Blaming cache import for connection issues
  • Thinking timeout zero causes connection failure
5. You want to use Django caching for a large distributed app with multiple servers. Which cache backend should you choose and why?
hard
A. LocMemCache, because it is fast and stores data in local memory.
B. FileBasedCache, because it stores cache in files accessible by all servers.
C. Database cache, because it is the fastest for distributed caching.
D. Redis or Memcached, because they support shared cache across multiple servers.

Solution

  1. Step 1: Understand caching needs for distributed apps

    Distributed apps require a cache backend that can share data across multiple servers.
  2. Step 2: Evaluate cache backends for multi-server support

    LocMemCache stores data only in local memory, FileBasedCache is slow and not ideal for concurrency, Database cache is slower. Redis and Memcached are designed for shared caching across servers.
  3. Final Answer:

    Redis or Memcached, because they support shared cache across multiple servers. -> Option D
  4. Quick Check:

    Distributed cache needs shared backend = Redis/Memcached [OK]
Hint: Use Redis or Memcached for multi-server shared caching [OK]
Common Mistakes:
  • Choosing LocMemCache for distributed apps
  • Assuming file-based cache is fast and shared
  • Thinking database cache is best for speed