My Django site recently started throwing errors from my caching code and I can’t figure out why…
I call:
from django.core.cache import cache
cache.set('blogentry', some_value)
And the error thrown by Django is:
TransactionManagementError: This code isn't under transaction management
But looking at the PostgreSQL database logs, it seems to stem from this error:
STATEMENT: INSERT INTO cache_table (cache_key, value, expires) VALUES (E'blogentry', E'pickled_version_of_some_value', E'2009-07-27 11:10:26')
ERROR: duplicate key value violates unique constraint "cache_table_pkey"
For the life of me I can’t figure out why Django is trying to do an INSERT instead of an UPDATE. Any thoughts?
That’s a typical race. It checks if the key you inserted exists; if it doesn’t, it does an insert, but someone else can insert the key between the count and the insert. Transactions don’t prevent this.
The code appears to expect this and to try to deal with it, but when I looked at the code to handle this case I could see immediately that it was broken. Reported here: http://code.djangoproject.com/ticket/11569
I’d strongly recommend sticking to the memcache backend.