Engineering Note

Techniques for eliminating silent database query amplification in ORMs through query planning, batching, and join projection.

The Hidden Cost of Lazy Loading

The N+1 query problem occurs when an application executes 1 initial query to fetch N parent records, and then issues N subsequent queries to fetch relational children one by one in a loop.

While convenient in local development with 10 records, in production with 500 records this translates to 501 network round-trips to the database, exhausting connection pools and causing massive latency spikes.

Batch Loading & Explicit JOIN Strategies

To solve this reliably, use either eager relational loading with explicit JOINs or the DataLoader batching pattern. Instead of querying per row, gather all target IDs and execute a single WHERE id IN (...) query, coalescing results into a memory map.

In PostgreSQL, you can also leverage JSON aggregation (json_agg / jsonb_build_object) to aggregate related children into structured objects directly inside the database engine, returning everything in one atomic scan.

SQL
-- Fetch orders with items in a single query avoiding N+1
SELECT 
  o.id, 
  o.total_amount, 
  o.status,
  COALESCE(json_agg(json_build_object(
    'sku', i.sku, 
    'quantity', i.quantity
  )) FILTER (WHERE i.id IS NOT NULL), '[]') AS items
FROM orders o
LEFT JOIN order_items i ON i.order_id = o.id
WHERE o.created_at >= NOW() - INTERVAL '7 days'
GROUP BY o.id;

Related Engineering Notes

/production-ready-apis

Designing Production-Ready APIs

A comprehensive guide to designing resilient REST APIs: deterministic contracts, idempotency keys, RFC 7807 problem details, and defense-in-depth rate limiting.

/response-projection

API Response Projection & Data Security

Preventing inadvertent data leaks by establishing intentional serialization boundaries between database entities and public API responses.

← Back to engineering notes