N+1 query problem adds hundreds of milliseconds per request
warningperformanceUpdated May 21, 2024(via Exa)
Technologies:
How to detect:
Application fetches a list of items then separately queries related data for each item. Each request triggers multiple sequential database queries instead of a single optimized query, adding hundreds of milliseconds to response time.
Recommended action:
Enable SQLAlchemy query logging to identify N+1 patterns. Replace separate queries with eager loading using `joinedload()` to fetch related data in a single query with joins. Example: `User.query.options(joinedload(User.posts)).all()`