Tag: backend

1 post

Catching N+1 Queries with SQLAlchemy Events

The N+1 query problem is the most common ORM performance issue. It's also the hardest to catch before production. The code looks correct, the logic is sound, and the bug only appears when you count the queries. This is an exploration of building a lightweight observability layer using SQLAlchemy's built-in event system. No APM required. No external dependencies. Just the ORM. It covers: - How N+1 queries happen, with runnable code examples - Building a QueryCounter using SQLAlchemy events - Writing regression tests that fail when query counts increase - Fixing N+1 with selectinload() and joinedload() - Extending the same pattern for slow query monitoring and query fingerprinting

11 min read