Opened 9 minutes ago
#37543 new Cleanup/optimization
Apps.get_models() and Apps.get_swappable_settings_name() share a single cache across all Apps instances
| Reported by: | Robert Lechte | Owned by: | |
|---|---|---|---|
| Component: | Migrations | Version: | dev |
| Severity: | Normal | Keywords: | |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
Apps.get_models() and Apps.get_swappable_settings_name() are decorated with @functools.cache on the class methods in django/apps/registry.py. Because @functools.cache stores a single cache on the function object, every Apps (and StateApps) instance shares that cache, and calling clear_cache() on any registry empties the cached entries for every other registry—including the global django.apps.apps registry.
During migrations, Django creates many temporary StateApps registries and calls clear_cache() repeatedly (on every model registration/render and re-render after state changes). Meanwhile, Field.deconstruct() on related fields queries the global registry via global_apps.get_swappable_settings_name(), which calls global_apps.get_models(include_swapped=True). Because each StateApps.clear_cache() wipes the global registry's cache, the global registry rebuilds its model list on almost every historical model rendered.
In addition, the shared cache retains strong references to every Apps / StateApps instance cached in it until the next clear_cache().
Impact
- Synthetic benchmark (1,000 models with FKs to
AUTH_USER_MODEL): during a singleProjectState.appsrender, the global registry rebuilds its model list 2,002 times onmain, compared to 2 times with per-registry caches. - Production project with thousands of migrations: 2x performance
Proposed fix
Wrap self.get_models and self.get_swappable_settings_name with functools.cache per instance in Apps.__init__(). This preserves cache_clear() and cache_info() per registry (including django.test.utils.isolate_lru_cache), isolates clear_cache() to the registry being cleared, and allows unreachable temporary registries to be garbage-collected.
(Related: #34687 added get_swappable_settings_name.cache_clear() to Apps.clear_cache().)
I have a patch with regression tests ready and will open a PR referencing this ticket.