10/12
Technical Architecture & AI Engineering · 7 min read

AI Code Review Audit: Catching N+1 Queries and Unbounded Latency Bottlenecks

Spot AI-generated N+1 loops, unbounded SELECT queries, and missing composite indexes in 10 seconds during code review, and replace them with batched lookups and cursor pagination.

Why This Matters at Engineering Leadership Scale

Latency regressions stay invisible on local seed databases. An AI assistant asked to "list compliance audits with their owner and evidence count" writes spotless code that finishes in 12ms on 8 local rows. Two weeks after launch, an Enterprise tenant with 2,400 audits loads the page, fires 4,801 SQL queries in one request, spikes PostgreSQL CPU to 98%, and slows down every tenant sharing the cluster.

At Engineering Manager and Head of Engineering scale, your leverage is teaching Tech Leads a repeatable 10-second scan for query cardinality, bounds, and index coverage so N+1 loops never clear review.

Core Mental Model & Framework

AI Latency Anti-Pattern10-Second Visual Trigger in DiffEnterprise Load FailureExact Fix to Demand
N+1 Query Inside Loopawait db... or await fetch(...) inside .map(), .forEach(), or for200 items -> 201+ round-trips (2s+ latency)Collect unique IDs, run 1 batched WHERE id = ANY($1) (DataLoader), join via Map
Unbounded SELECT *Missing LIMIT or unclamped req.query.limit?limit=50000 OOM-kills API podsEnforce server-side MAX_LIMIT = 100 + explicit columns + keyset cursor
Missing Composite IndexWHERE tenant_id = $1 AND status = $2 ORDER BY created_at DESC with no migrationFull table scan across all tenantsCREATE INDEX CONCURRENTLY ... ON table (tenant_id, status, created_at DESC, id DESC)
Deep OFFSET DriftOFFSET 10000 LIMIT 50 on large tablesScans and discards 10k rows per pageKeyset cursor pagination (WHERE (created_at, id) < ($3, $4))

Step-by-Step Implementation Tutorial

1. Run the 10-Second await-Inside-Loop Scan

Scan any PR diff touching list endpoints or resolvers strictly for for, .map(async, or lazy ORM getters. Any DB or HTTP call inside an iteration over dynamic records is an automatic request-changes finding.

2. Audit the Buggy AI Diff vs. the Batched, Bounded Fix

typescript
// =========================================================================
// BUGGY AI-GENERATED DIFF (DO NOT APPROVE)
// 2N + 1 sequential SQL queries, unbounded SELECT *, missing composite index
// =========================================================================
export async function listTenantAudits(
  db: Pool, tenantId: string, status: string, requestedLimit?: number
) {
  // BUG 1: Unbounded query if limit omitted or set to 999999
  const limitSql = requestedLimit ? `LIMIT ${Number(requestedLimit)}` : "";

  // BUG 2: SELECT * pulls huge JSONB columns over the wire
  const auditsRes = await db.query(
    `SELECT * FROM compliance_audits
     WHERE tenant_id = $1 AND status = $2 ORDER BY created_at DESC ${limitSql}`,
    [tenantId, status]
  );

  // BUG 3: Classic N+1 loop (200 audits = 400 extra DB round-trips)
  const items = [];
  for (const audit of auditsRes.rows) {
    const ownerRes = await db.query(
      `SELECT id, full_name FROM users WHERE tenant_id = $1 AND id = $2`,
      [tenantId, audit.owner_id]
    );
    const countRes = await db.query(
      `SELECT COUNT(*)::int AS total FROM evidence_items WHERE tenant_id = $1 AND audit_id = $2`,
      [tenantId, audit.id]
    );
    items.push({ ...audit, owner: ownerRes.rows[0] ?? null, evidenceCount: countRes.rows[0].total });
  }
  return { items };
}

Now look at the fixed diff: server-clamped MAX_LIMIT = 100, keyset cursor pagination, explicit columns, and 3 constant O(1) queries joined in memory with Map.

typescript
// =========================================================================
// FIXED PRODUCTION DIFF
// Constant 3 queries (O(1) round-trips), MAX_LIMIT=100, keyset cursor
// Requires: CREATE INDEX CONCURRENTLY idx_audits_tenant_status_created
//   ON compliance_audits (tenant_id, status, created_at DESC, id DESC);
// =========================================================================
const MAX_LIMIT = 100;
export interface AuditCursor { createdAt: string; id: string; }

export async function listTenantAudits(
  db: Pool, tenantId: string, status: string, requestedLimit = 25, cursor?: AuditCursor
) {
  const pageSize = Math.min(Math.max(1, Math.trunc(requestedLimit)), MAX_LIMIT);
  const fetchLimit = pageSize + 1;

  const auditsRes = cursor
    ? await db.query(
        `SELECT id, title, status, owner_id, created_at FROM compliance_audits
         WHERE tenant_id = $1 AND status = $2 AND (created_at, id) < ($3::timestamptz, $4::uuid)
         ORDER BY created_at DESC, id DESC LIMIT $5`,
        [tenantId, status, cursor.createdAt, cursor.id, fetchLimit]
      )
    : await db.query(
        `SELECT id, title, status, owner_id, created_at FROM compliance_audits
         WHERE tenant_id = $1 AND status = $2 ORDER BY created_at DESC, id DESC LIMIT $3`,
        [tenantId, status, fetchLimit]
      );

  const hasMore = auditsRes.rows.length > pageSize;
  const rows = hasMore ? auditsRes.rows.slice(0, pageSize) : auditsRes.rows;
  if (rows.length === 0) return { items: [], nextCursor: null };

  const auditIds = rows.map((r) => r.id);
  const ownerIds = Array.from(new Set(rows.map((r) => r.owner_id).filter(Boolean)));

  // FIX: Constant 2 batched enrichment queries regardless of page size
  const [ownersRes, countsRes] = await Promise.all([
    ownerIds.length
      ? db.query(`SELECT id, full_name FROM users WHERE tenant_id = $1 AND id = ANY($2::uuid[])`, [tenantId, ownerIds])
      : Promise.resolve({ rows: [] }),
    db.query(
      `SELECT audit_id, COUNT(*)::int AS total FROM evidence_items
       WHERE tenant_id = $1 AND audit_id = ANY($2::uuid[]) GROUP BY audit_id`,
      [tenantId, auditIds]
    ),
  ]);

  const ownerById = new Map(ownersRes.rows.map((u) => [u.id, u]));
  const countByAudit = new Map(countsRes.rows.map((c) => [c.audit_id, c.total]));

  const items = rows.map((a) => ({
    id: a.id, title: a.title, status: a.status, createdAt: a.created_at,
    owner: ownerById.get(a.owner_id) ?? null,
    evidenceCount: countByAudit.get(a.id) ?? 0,
  }));

  const last = rows[rows.length - 1];
  return {
    items,
    nextCursor: hasMore ? { createdAt: last.created_at.toISOString(), id: last.id } : null,
  };
}

3. Mandate EXPLAIN (ANALYZE, BUFFERS) and Automated Query-Count Budgets

Require a 6-line EXPLAIN (ANALYZE, BUFFERS) snippet in PR descriptions for new multi-column filters showing Index Scan (never Seq Scan). Add a test wrapper counting db.query invocations and asserting expect(queryCount).toBeLessThanOrEqual(3) on a 50-row seed so future AI edits cannot reintroduce an N+1 loop.

Worked Production Scenario: Before vs. After

Context: A multi-tenant GRC SaaS shipped an AI-generated "Open Controls Overview" API with an unbounded SELECT * and two per-row queries inside .map(). Local 15-row tests ran in 90ms; on launch day, an Enterprise bank with 1,900 controls triggered 3,801 queries in 11.4 seconds, saturating the read replica and causing 502 alerts across two neighboring squads.

After: A 20-minute review refactor applied batched ANY($2) lookups, MAX_LIMIT = 100 keyset pagination, a concurrent composite index, and a queryCount <= 3 CI test.

MetricBeforeAfter
SQL queries per request (100 items)201 (3,801 unbounded)3 (constant O(1))
Enterprise dashboard p99 latency11,400 ms (timeouts)38 ms
PostgreSQL read replica peak CPU96% spikes14% steady
Response payload size14.8 MB (SELECT *)64 KB

Common Failure Modes & Anti-Patterns

  1. Wrapping an N+1 loop in Promise.all(rows.map(r => db.query(...))): Parallelizing an N+1 fires 200 simultaneous queries and starves your 20-connection DB pool. Fix: Collapse N queries into 1 batched WHERE id = ANY($1) query.
  2. Putting status before tenant_id in a composite index: Scans low-selectivity rows across tenants. Fix: Lead multi-tenant B-tree indexes with equality keys in selectivity order: (tenant_id, status, created_at DESC, id DESC).
  3. Running blocking CREATE INDEX in migrations: Locks table writes during deploys. Fix: Always require CREATE INDEX CONCURRENTLY.

How to Handle Pushback in the Room

Skeptical Principal Engineer: "Why run three batched queries instead of one SQL LEFT JOIN?"

Calm Response: "For 1-to-1 joins like users, a LEFT JOIN is often even cleaner. For 1-to-many aggregates like evidence_items counts or cross-service enrichment, three constant batched queries avoid Cartesian row multiplication - the non-negotiable bar is O(1) queries per request, never O(N)."

Pushing Product Manager: "The UI already has numbered pages (1..40) - can we keep OFFSET?"

Calm Response: "For small lists under a few hundred rows, OFFSET with MAX_LIMIT = 100 is fine. On audit logs growing to hundreds of thousands of rows, deep OFFSET degrades linearly and duplicates rows as new events arrive - Next/Previous cursors keep every page fast."

Key Takeaways & This Week's Action Rep

  • Do the 10-second await-inside-loop scan: Reject any DB or HTTP call inside .map(), .forEach(), or for.
  • Parallelizing an N+1 is still an N+1: Replace per-row queries with batched ANY($1) or DataLoader.
  • Clamp every list query server-side: Enforce MAX_LIMIT = 100, drop SELECT *, and use keyset cursors.
  • Automate query-count budgets in CI: Assert queryCount <= 3 on a 50-row seed to catch regressions forever.

This Week's Action Rep: Add a queryCount assertion helper to one high-traffic list endpoint test in your codebase, seed 50 items, and confirm query count stays constant.