fix(dependencies): register one fallback backend under concurrent first AppCache calls - #91
Merged
Merged
Conversation
…st AppCache calls get_app_cache is a sync dependency, so FastAPI runs it in worker threads. In an app with no configured backend, concurrent first requests each built a MemoryBackend and a CacheManager, and the later set() replaced the earlier, leaving caches that could not see each other's entries. The lazy fallback now lives in proxy.get_backend_or_fallback(), which re-checks under a lock, and @cache uses the same helper. get_app_cache double-checks the manager under its own lock. Closes #76
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #76.
Problem
get_app_cacheis a sync dependency, so FastAPI runs it in worker threads. In an app that never configured a backend, concurrent first requests each built aMemoryBackendand aCacheManager. The laterset()replaced the earlier one, so for a while requests used caches that could not see each other's entries.Change
proxy.get_backend_or_fallback(): it returns the configured backend or registers aMemoryBackend. It re-checks under athreading.Lock, so every concurrent first caller gets the same instance.@cacheuses the same helper instead of its own copy of the fallback. The dependency and the decorator can no longer install competing fallbacks, even when one runs on the event loop and the other in a worker thread.get_app_cachedouble-checks the manager under its own lock. It stays a sync dependency, soapp.dependency_overridesusers are unaffected.Tests
test_get_app_cache_concurrent_first_calls_share_one_backend: 8 threads start together behind a barrier, with a slowed-downMemoryBackendconstructor.8 == 1managers.