0
0
Djangoframework~5 mins

Cache invalidation strategies in Django

Choose your learning style9 modes available
Introduction

Cache invalidation strategies help keep your cached data fresh and accurate. They decide when to update or remove stored data so users see the latest information.

When you want to update cached web pages after content changes.
When database records change and cached queries need refreshing.
When user-specific data in cache must reflect recent actions.
When you want to avoid showing outdated information to users.
When you want to improve performance but keep data reliable.
Syntax
Django
from django.core.cache import cache

# Example: Delete a cache key
cache.delete('my_key')

# Example: Set cache with timeout
cache.set('my_key', 'value', timeout=300)

# Example: Clear all cache
cache.clear()

Use cache.delete(key) to remove specific cached data.

Use timeout to set how long data stays cached before automatic invalidation.

Examples
Cache user profile data for 10 minutes (600 seconds).
Django
cache.set('user_42_profile', user_profile_data, timeout=600)
Remove cached user profile when it changes.
Django
cache.delete('user_42_profile')
Clear all cached data, useful after big updates.
Django
cache.clear()
Sample Program

This example caches a product list, then updates it by deleting the old cache and setting a new one. Finally, it prints the updated cached list.

Django
from django.core.cache import cache

# Simulate caching a product list
products = ['apple', 'banana', 'cherry']
cache.set('product_list', products, timeout=120)

# Later, product list changes
products.append('date')

# Invalidate old cache
cache.delete('product_list')

# Update cache with new list
cache.set('product_list', products, timeout=120)

# Retrieve and print cached product list
cached_products = cache.get('product_list')
print(cached_products)
OutputSuccess
Important Notes

Always delete or update cache when underlying data changes to avoid stale info.

Use timeouts to automatically expire cache if manual invalidation is missed.

Be careful with cache.clear() as it removes all cached data, which might affect performance.

Summary

Cache invalidation keeps cached data fresh and accurate.

Use cache.delete() to remove specific cached items.

Set timeouts to auto-expire cached data after some time.