The ORM N+1, at the query layer

The same N+1 you saw in Ruby โ€” now in SQLAlchemy

If you've taken the Ruby course, this will feel familiar: fetch a list of walkers, then loop over them accessing walker.bookings โ€” and each access fires its own query. Ten walkers means one query to fetch the walkers, plus ten more to fetch each one's bookings. That's N+1 queries for what should be two.

It happens because a relationship like Walker.bookings is lazy by default โ€” SQLAlchemy doesn't fetch related rows until your code actually touches the attribute, and by then the original query has already finished. Async SQLAlchemy makes this worse: touching a lazy relationship outside an active session context raises MissingGreenlet instead of quietly running an extra query (you met this in module 32) โ€” so the N+1 either silently costs you N extra round trips, or crashes outright.