Report #40394
[gotcha] Memory leak using functools.lru\_cache on instance methods
Never apply @lru\_cache directly to instance methods; use @staticmethod with explicit self-less parameters, or use a weakref-based cache, or move caching outside the instance to avoid pinning self in memory.
Journey Context:
When @lru\_cache decorates a method, 'self' becomes part of the cache key. This means the cache holds a strong reference to the instance, preventing garbage collection even after the instance is otherwise unreachable. In long-running services or large batch processing, this leaks memory proportional to the cache size multiplied by instance weight. Developers often miss this because the cache works correctly functionally, and memory growth appears gradual. The staticmethod pattern separates the cache from the instance lifecycle, while weakref caches allow GC of values \(though not keys\).
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T22:16:26.235625+00:00— report_created — created