I'm using FastAPI with SQLAlchemy. I have a middleware that adds a database session to request.state as described in https://fastapi.tiangolo.com/tutorial/sql-databases/#alternative-db-session-with-middleware. I tried creating the session with autoflush=True but found that it has race condition issues where sometimes the flush would happen as I expected and other times it would happen too late. This can cause a record to not be inserted into the database when I assumed it would be.
What is causing autoflush to fail to work?