The admin list endpoint returned in 40 ms. The dashboard felt fast. The client's team had no complaints, and that was precisely the problem: a single page load of that endpoint was issuing roughly 300 SQL queries, and a cache was the only reason nobody had noticed. This is a write-up of an audit we ran on a client's admin API, where ORM lazy loading had quietly become structural debt.

How a cache hides an N+1

The endpoint was a paginated list of records for an admin dashboard: 50 rows per page, each row showing a handful of related fields (owner, status history, a couple of aggregates). The serializer touched those relations as it built each row. With the ORM's default lazy loading, every access to a relation that wasn't already loaded fired its own SELECT.

The shape looked innocent:

rows = Record.query.filter_by(org_id=org).limit(50).all()
return [serialize(r) for r in rows]   # serialize() reads r.owner, r.status_history, r.tags

One query for the 50 rows, then three relation reads per row. That's 1 + 50 x 3 = 151 queries at minimum. Some relations nested one level deeper (the owner's role, for example), which is how the count crept toward 300. Classic N+1, multiplied by the number of relations.

Why did nobody see it? Someone had put a response cache in front of the endpoint with a short TTL, keyed on the query string. Warm hits never touched the database. Cold hits took a second or two, but the admin users were few, so a cold hit was rare and, from the user's side, looked like an occasional hiccup rather than a pattern. The cache converted a design flaw into an intermittent annoyance. It also meant any monitoring that averaged latency showed a healthy endpoint.

Finding it: query logs first, EXPLAIN ANALYZE second

We did not start with a profiler. We started by turning on statement logging against a staging copy and bypassing the cache for one request. The log made the problem obvious in seconds: the same statement shape repeated with only the parameter changing.

SELECT ... FROM users WHERE id = $1;
SELECT ... FROM users WHERE id = $1;
SELECT ... FROM users WHERE id = $1;
-- ... x50

Counting is the fastest diagnostic here. Group the log by normalized statement and sort by frequency; an N+1 sits at the top with a count that tracks your page size. If the count is a multiple of the page size, you have your culprit.

Then we ran EXPLAIN ANALYZE on the statements, and this is where it got more interesting than "too many queries." Two findings:

  • Each individual lazy query was cheap, a primary-key lookup. The cost was round-trip overhead and connection time, not query execution. That's why per-query slow logs showed nothing: no single statement crossed the threshold.
  • One of the relations, the status history, filtered on a foreign key column with no index. EXPLAIN ANALYZE showed a sequential scan per call. Fifty sequential scans on a small table is tolerable; on a table that grows, it's a time bomb. The cache had been shielding that too.

The lesson: slow-query thresholds are blind to N+1. Each query is fast. The pathology is only visible in aggregate, per request. If your tooling can't answer "how many queries did this request make?", add that before anything else.

Why we removed the cache before fixing anything

The tempting move was to fix the queries and leave the cache. We argued for the opposite order: switch the cache off first, in staging, and live with the real latency for a day.

Reasons:

  1. You can't measure a fix behind a cache. If warm hits mask everything, a before/after comparison is meaningless. With the cache off, query count and latency per request are honest numbers.
  2. The cache was encoding wrong assumptions. Its TTL had been tuned around the slow path. Once the endpoint was fast, a short-lived cache added invalidation bugs (stale status after an edit) for no benefit.
  3. It reveals the other callers. With the cache gone, we found two other endpoints reusing the same serializer with the same lazy access pattern. They had never been cached, and they were the ones people described as "sometimes slow."

This is the part that's easy to skip. A cache is a legitimate tool, but when it's the first response to a slow endpoint, it's often covering for a query problem that will reappear the moment the data grows or the cache is flushed.

The actual fix

The fix was unglamorous and small:

  • Eager load the relations the serializer needs, using the ORM's join or batched-select loading strategy. Batched "select in" loading was the better fit for collections: it issues one extra query per relation rather than one per row, and avoids row multiplication from wide joins.
  • Add the missing index on the status history foreign key and confirm with EXPLAIN ANALYZE that the plan flipped from sequential scan to index scan.
  • Make the serializer's data needs explicit. We moved the loading options next to the serializer so changing the fields forces a conscious decision about what to load.
  • Add a test asserting a maximum query count for the endpoint. It fails if someone adds a relation read without loading it. This is the guard that stops the debt from returning.

The query count dropped from around 300 to under ten, independent of page size. That's the property that matters: cost that scales with the number of relations, not the number of rows.

What to take from this

If you maintain an API on an ORM with lazy loading enabled by default, three cheap checks are worth running this week: log queries per request, count repeated statement shapes, and temporarily bypass your response caches on list endpoints. None of it requires new tooling. Treat lazy loading as a decision you make per query path, not a default you inherit.

Audits like this are a regular part of what orithLabs does: reading an existing backend, finding where performance and architectural debt is hiding, and handing back a prioritized fix list your own team can act on. If you suspect a cache is covering for something in your system, we're happy to compare notes.