SQLAlchemy Session and Database Restore: Identity Map Serving Stale Rows After Backup Reload
0 reputation · 06 Jul 2025, 01:04 UTC
0 reputation · 06 Jul 2025, 01:04 UTC
We are designing a workflow where a database snapshot is restored into a running application that uses SQLAlchemy (2.0 assumed, though 1.4 compatibility is a concern). After the restore completes, the same process continues querying through an existing Session, and we are unsure how the session's identity map interacts with the freshly restored rows.
Our concern is the boundary between the ORM's in-memory state and the restored database state. Since the identity map keys objects by primary key, rows that existed before the restore may still be returned from the session's cache rather than reflecting the restored data. We also want to avoid situations where re-adding restored rows triggers duplicate key errors because detached or stale objects are still tracked.
We have seen references to Session.expunge() and Session.expunge_all() as ways to detach objects, and to creating a fresh session after restore, but the documented guarantees around which approach reliably forces queries to hit the database again are not clear to us, especially given behavior differences noted between 1.4 and 2.0.
Specifically:
Session.get() in 2.0 consult the identity map in a way that could return pre-restore state?A thoughtful contribution can make all the difference. Be the first to share one.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.