Exercise 1: Why Sharing the Route's Session Would Be Unsafe — Possible Solution ==================================================================== WHY SHARING ONE SESSION ACROSS CONCURRENT TASKS IS UNSAFE ------------------------------ SQLAlchemy's classic Session is designed around the assumption that only one logical operation uses it at a time - it maintains internal state (like tracking which objects belong to the current transaction) that isn't built to handle multiple queries, merges, and commits happening in an interleaved order from several concurrently-running coroutines at once. asyncio.gather() runs several lookup_ingredient calls concurrently, meaning their queries and commits against a shared session could interleave in an order the Session was never designed to handle correctly, risking genuinely inconsistent internal state. WHAT lookup_ingredient DOES INSTEAD ------------------------------ Rather than accepting the request's own shared db parameter, lookup_ingredient calls SessionLocal() itself at the start of the function, creating a brand-new, dedicated session that belongs only to that one specific concurrent task, and explicitly closes it in a finally block once that task's work is done. Since every concurrently-running call to lookup_ingredient creates its own separate session, none of them ever touch the same session object another one is using at the same time. WHY THIS WORKS AS AN ANSWER ------------------------------ It correctly explains why SQLAlchemy's Session isn't safe for concurrent use across multiple simultaneously-running tasks, and correctly describes the specific fix - giving each concurrent task its own dedicated session via SessionLocal() rather than sharing the route's own request-scoped session.