Cache-aside (lazy loading) in Django with invalidation on commit

Django Caching Patterns November 13, 2026 python

What is the cache-aside (lazy loading) pattern, the most common caching pattern?

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# ======================================================================
# Q: What is the cache-aside (lazy loading) pattern, the most common caching
# pattern?
# ======================================================================

def get_product(pk):
    key = f'product:v2:{pk}'
    data = cache.get(key)
    if data is None:                                   # cache miss
        data = ProductSerializer(Product.objects.get(pk=pk)).data
        cache.set(key, data, timeout=60 * 15)
    return data

# invalidation when it changes
def update_product(product):
    product.save()
    transaction.on_commit(lambda: cache.delete(f'product:v2:{product.pk}'))