0
Challenge · 64The Data API & Your Next.js App
The N+1 trap over embeds
Queriesused in ~70% of apps
DevLog's feed renders 5 posts and the network tab shows 11 requests. Nobody wrote a bug — they wrote the obvious code: fetch the posts, then loop over them fetching each one's author. It works perfectly on your laptop with 5 posts and quietly ruins the app the day the feed has 200.
Core idea. N+1 is 1 request to list the parents plus N more requests, one per parent, to fetch something that belongs to it — a round-trip cost that scales with the size of the list, even though every individual query is fast. The fix is not 'make the queries faster'; it's asking for the related data in the SAME request via an embed, so the round-trip count stops depending on how many rows came back. The trap in the name — 'over embeds' — is that an embed can silently reintroduce the exact row-multiplication bug concept 23 already warned about, just at the JSON layer instead of the SQL layer.
poke it, drag it,
try to break it
try to break it
no slides here.
you drive.
you drive.
Playground, this isn't a screenshot
DevLog feed · 5 posts
const posts = await supabase.from('posts').select();
for (const p of posts) {
await supabase.from('profiles').select().eq('id', p.user_id);
await supabase.from('comments').select('*', { count: 'exact', head: true }).eq('post_id', p.id);
}
0 / 11 requests~0ms elapsed (serial round trips)
1GET posts
2GET author of "Why I switched to Postgres"
3GET author of "RLS, explained"
4GET author of "Ships on Fridays"
5GET author of "Indexing tips"
6GET author of "My Vim setup"
7GET comment count for "Why I switched to Postgres"
8GET comment count for "RLS, explained"
9GET comment count for "Ships on Fridays"
10GET comment count for "Indexing tips"
11GET comment count for "My Vim setup"
5 posts → 11 requests (1 list + 5 author lookups + 5 comment-count lookups), each paying a full round trip in series. The query underneath every single one is fast — the cost is entirely the network, multiplied by every row in the list.
↑ play a little first, then dig in