DetachedInstanceError when accessing lazy-loaded relationship after session close
0 reputation · 29 Feb 2024, 01:43 UTC
Problem Context
When a SQLAlchemy Session is closed, accessing a lazy-loaded relationship on an object raises sqlalchemy.orm.exc.DetachedInstanceError.
Goal
Determine whether the occurrence of DetachedInstanceError signals a performance bottleneck in session handling before applying optimizations such as eager loading or session configuration changes.
Constraints & Uncertainty
The error appears only after the session is terminated, but it is unclear if the underlying issue is merely the session lifecycle or if it reflects excessive lazy-load queries that could be optimized. Additionally, the impact of expire_on_commit=False on the error frequency is uncertain.
Specific Questions
- Does the frequency of
DetachedInstanceErrorcorrelate with increased latency for lazy-loaded relationships? - Can instrumentation of query execution before session close reliably identify which lazy loads contribute most to the error?
- What combination of session options (e.g.,
expire_on_commit,joinedload) balances error avoidance with query performance?