Django cache invalidation on transaction commit?

801 views Asked by At

When developing your project in Django with READ-COMITTED level, I think cache.delete can lead to race condition and django's signals won't help much.

T1                          T2
                            cache.delete
cache.get (not found)
read from database
cache.set (old value again)
                            commit
                            cache.get (old value)

How can I ensure that cache invalidation is only done at the moment of transaction commit?

1

There are 1 answers

2
augustomen On

You should only delete from cache when the transaction has been committed. To ensure your transaction has been committed (for example, in case you're using django.middleware.transaction.TransactionMiddleware to commit upon every request), you can force a commit using commit_on_success:

from django.db import transaction
with transaction.commit_on_success():
    # ... do db stuff ...

cache.delete('key')