﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
37543	Apps.get_models() and Apps.get_swappable_settings_name() share a single cache across all Apps instances	Robert Lechte		"`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 single `ProjectState.apps` render, the global registry rebuilds its model list **2,002 times** on `main`, 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."	Cleanup/optimization	new	Migrations	dev	Normal				Unreviewed	0	0	0	0	0	0
