Performance: Cache invalidation strategies
This affects page load speed by controlling how fresh cached content is served and how often the server recomputes or fetches data.
Jump into concepts and practice - no test required
from django.core.cache import cache def get_data(): data = cache.get('my_data') if not data: data = expensive_db_query() cache.set('my_data', data) return data def update_data(new_data): save_to_db(new_data) cache.delete('my_data') # invalidate cache immediately
from django.core.cache import cache def get_data(): data = cache.get('my_data') if not data: data = expensive_db_query() cache.set('my_data', data, timeout=3600) # fixed 1 hour timeout return data
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Fixed timeout cache invalidation | N/A | N/A | May delay fresh content load | [X] Bad |
| Manual cache key deletion | N/A | N/A | Multiple cache calls increase server load | [!] OK |
| Batch cache key deletion (delete_many) | N/A | N/A | Fewer cache calls, consistent invalidation | [OK] Good |
| Cache versioning | N/A | N/A | Automatic fresh content with minimal overhead | [OK] Good |
from django.core.cache import cache
cache.set('user_1', 'Alice', timeout=300)
cache.delete('user_1')
result = cache.get('user_1', 'Not Found')
print(result)from django.core.cache import cache
cache.set('page_data', 'content', timeout=600)
cache.delete('page_data')
cache.delete('page_data')