Urgent.News

What's breaking now, across hundreds of outlets.

Tech

The N+1 Query Problem in Node.js & PostgreSQL: How to Detect and Eliminate It

Here's a performance bug that never shows up in a slow-query log. Every individual query is fast: 1 to 2 ms, perfectly indexed, textbook plans. Your database CPU is bored. And yet the endpoint takes 400 ms, gets slower as data grows, and under load it eats your connection pool alive. That's the N+1 query problem : you run 1 query to fetch a list, then N more queries, one per item, to fetch…

The N+1 query problem in Node.js and PostgreSQL manifests as a performance issue where each query takes between 1 to 2 milliseconds, but the endpoint takes 400 milliseconds to respond, getting slower as data grows and consuming connection pool resources. This occurs because the endpoint makes one query to fetch a list of items, followed by N more queries, one per item, to fetch related data.

For instance, listing 50 latest posts with their authors' names results in 51 queries, even though each individual query is fast. The problem is exacerbated under load, as it eats up your connection pool, causing slower response times and increased latency. Recognizing N+1 involves identifying when multiple queries are executed for each item in a result set, often hidden in asynchronous code, GraphQL resolvers, or ORM lazy loading.

Solutions include using DataLoader to batch requests, eager loading related data in ORMs, and structuring queries to minimize round-trip latency.

Rewritten by urgent.news; may contain errors — check the original.

Source: dev.to

Read the original at dev.to →

Report a problem with this story

More in Tech

Technical SEO for Developers: 7 Checks to Make Before Launching a Website

A website can look great, load a modern JavaScript application, and still have a problem that is easy to miss: search engines may not be able to access its most important content.

  • Examine server response headers and HTML content using tools like curl
  • Ensure each page has unique, descriptive titles dynamically generated
  • Verify internal links function correctly, avoid client-side routing only

More from Monday 12 October →