DatabasesNov 14, 2026·6 min read

The N+1 Query Problem: Why Your Database Bill Tripled with 50 Users

I reproduced how AI coding tools fetch data in production. In local dev it takes 18ms. With 50 concurrent tabs it fires 5,000 HTTP round trips and pegs Postgres CPU at 100%.

#N+1 Query#Supabase#PostgreSQL#Database Costs#SQL Server#Performance

01Run this check right now

Diagnostic Test

The 30-Second Browser Network Check

Open your browser developer tools, go to the Network tab, and filter by /rest/v1/ or fetch. If loading a dashboard fires dozens of parallel requests for individual IDs, your app runs an N+1 query loop.

curl -s "https://<PROJECT_ID>.supabase.co/rest/v1/orders?select=id,customer_id&limit=10"

Findings from the Field

  • /01AI coding tools write mapped loops because fetching child records in separate functions looks clean and modular in a single file.
  • /02On localhost with 5 rows, the loop takes 18ms. Under 50 concurrent users, that same component fires over 5,000 HTTP round trips in seconds.
  • /03Postgres does not struggle with the math; it chokes on opening, authenticating, and tearing down connection slots.
  • /04Replacing mapped Promise.all loops with a single nested PostgREST join drops response latency from 4,200ms to 24ms: roughly 175X faster.
  • /05Adding an explicit B-tree index on foreign key columns prevents sequential table scans as your user table scales.

The mystery of the tripled database bill

A founder messaged me last week with a classic mystery. Their prototype, built with Cursor and Supabase, worked without a hitch during local testing. Demos were smooth, buttons responded quickly, and everything looked ready. Then they launched to a private beta of roughly 50 users, and within four days their cloud database CPU was pinned at 98% and their billing tier automatically upgraded.

I was curious where all those compute cycles were vanishing. A dashboard with 50 users should barely wake Postgres up from an idle sleep. So I cloned the repository into an isolated sandbox to profile the queries and see what was happening on the wire.

What the AI model generated in code

I looked at the primary dashboard component first. The goal was simple: display a list of customer orders alongside each customer's name and email address.

When an AI coding assistant writes this feature, it chooses the most intuitive, single-file decomposition possible. First, fetch the orders array. Then, loop over each order with JavaScript map, querying the customers table for each customer ID:

During local development on a laptop with 5 test rows, this entire block finishes in about 18ms. You do not notice a thing. The UI feels snappy, tests pass, and you ship it.

The innocent-looking loop in src/pages/Orders.tsxtypescript
// Fetch parent records first
const { data: orders } = await supabase.from('orders').select('*');

// Then loop over every single row to fetch child records
const ordersWithCustomers = await Promise.all(
  orders.map(async (order) => {
    const { data: customer } = await supabase
      .from('customers')
      .select('*')
      .eq('id', order.customer_id)
      .single();
    return { ...order, customer };
  })
);

Where the round trips go: the waiter analogy

To understand why this melts production servers, consider an analogy. Imagine sitting down at a diner and ordering dinner. Instead of handing the waiter a complete order, you ask for a single french fry. The waiter walks to the kitchen, brings back one fry, and then you ask for a second fry. You repeat this 100 times to assemble your plate.

In our dashboard, if the database has 100 orders, this code fires 1 query for the orders list, followed by 100 separate queries for individual customer IDs. That is 101 independent HTTP round trips over the public internet for a single page refresh.

Now imagine 50 beta users open the app around 9:00 AM. That single React component fires 5,050 HTTP requests into PostgREST in less than 3 seconds. Each request carries TLS handshake overhead, HTTP header parsing, JWT verification, and an independent database transaction. Postgres is not struggling with mathematical calculations; it is suffocating under connection slot bookkeeping.

The 30-second DevTools check

You do not need heavy APM monitoring to catch this. I opened Chrome DevTools on the dashboard, switched to the Network tab, and filtered requests by /rest/v1/.

Instead of 1 or 2 clean data calls, the waterfall tab showed a staircase of 100 near-identical requests: GET /customers?id=eq.101, GET /customers?id=eq.102, and so on. Because browsers limit concurrent HTTP connections per domain (typically 6 in Chrome), the requests queued up sequentially.

Total page load time on a standard connection was 4,200ms. With 50 concurrent tabs, requests started timing out with 504 gateway errors.

Fixing the loop with a single nested join

The fix is almost comical in its simplicity. PostgREST (the API layer exposing PostgreSQL in Supabase) understands foreign keys natively. Instead of making 100 round trips across the country, we instruct Postgres to join the tables on the database host and return a single nested JSON tree in 1 round trip:

In my sandbox benchmark, replacing the Promise.all loop with this single nested query dropped response latency from 4,200ms to 24ms: roughly a 175X speedup. Network traffic dropped from 101 requests down to 1. Database CPU dropped from 98% back to 3%.

Single nested PostgREST querytypescript
// 1 request. 1 round trip. Postgres does the join in memory.
const { data: orders, error } = await supabase
  .from('orders')
  .select(`
    id,
    created_at,
    total_amount,
    status,
    customers (
      id,
      full_name,
      email
    )
  `);

The missing foreign key index

There was one second-order issue that surfaced when testing with larger datasets. When AI tools generate database tables via SQL migrations, they almost never declare indexes on foreign key columns.

If orders.customer_id has no B-tree index, Postgres must perform a sequential scan across the entire customers table for every joined row. With 50 rows in development, sequential scans complete in microseconds because the table lives in memory cache. When your customer table reaches 20,000 users, an unindexed join forces Postgres to scan 20,000 disk blocks repeatedly.

Running EXPLAIN ANALYZE highlighted the sequential scan immediately. We added the missing foreign key indexes in the SQL editor:

Adding this index dropped the Postgres query execution time from 160ms down to 1.1ms: about 145X faster on a table of 25,000 customer records.

PostgreSQL B-tree indexessql
-- Index the foreign key column to turn sequential scans into index scans
CREATE INDEX IF NOT EXISTS idx_orders_customer_id 
ON public.orders (customer_id);

CREATE INDEX IF NOT EXISTS idx_order_items_order_id 
ON public.order_items (order_id);

Reflections: physics versus clean local loops

Looking back at this pattern, I suspect we will see much more of it as AI coding models become the primary way software gets built. LLMs are trained to write modular, self-contained functions that look clean in a single file. Mapping over an array and calling a helper function feels tidy in code.

Computers, however, are governed by physical constraints: speed of light, TCP socket buffers, and database lock contention. Once you remember that every await supabase.from() call is a network packet traveling across physical fiber, the architecture practically designs itself.

Now I can get back to building, because yolo.

Production Hardening & Audits

Stuck on prompt regressions, leaked keys, or database scaling in an AI-built app? Explore our platform-specific teardowns:

Diagnostic & Rescue

1 business day reply

Think your prototype is vulnerable or hitting scale limits?

Send us a note with your repository, Supabase link, or project details. A senior engineer will review your policies and reply within one business day.