New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Cached values may be stale after updating in a transaction #296
Comments
Interesting! So I'm OK with the proposed fix more or less as-is, and here are some bonus thoughts:
|
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. |
This issue has been closed as stale because it has not had any recent activity. Please feel free to re-open if the issue is still relevant. Thank you for your contributions! |
On Bitbucket we use waffle flags/samples/switches in some very high-traffic scenarios, which can lead to race conditions like this one.
Recently we uncovered another one: since BaseModel.save() calls flush() immediately after saving, there is the potential for a separate process to read the previous value and cache it before the transaction is committed, resulting in the stale value being cached indefinitely.
You might think this is an edge case but in fact the Django admin site always wraps changes in transactions, so this applies to any application for which the primary mechanism for flipping flags and switches is the admin UI.
The most natural fix for this would be to change
BaseModel.save()
to something like:However,
transaction.on_commit
only became available in Django 1.9, so this wouldn't work out of the box on previous versions of Django. If this were my library, I'd probably just add a runtime check to useon_commit
if available, otherwise callflush()
directly and add a note in the docs to library consumers: sorry, but there is a race condition unless you're on Django>=1.9.The reason I am opening an issue and not a pull request is actually something else entirely: the current test suite seems to use sqlite, but the best way I can come up with to demonstrate the problem is to use threads and it seems sqlite doesn't play nicely with threads—or at least, it didn't work for me locally (the linked issue appears to have a solution, but this is about where I stopped digging).
In any case, here is a test that can be added if someone wants to put in the effort to make it work:
The text was updated successfully, but these errors were encountered: