惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX - 技术
D
DataBreaches.Net
阮一峰的网络日志
阮一峰的网络日志
Recent Announcements
Recent Announcements
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
T
The Exploit Database - CXSecurity.com
Simon Willison's Weblog
Simon Willison's Weblog
Cisco Talos Blog
Cisco Talos Blog
Microsoft Security Blog
Microsoft Security Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
K
Kaspersky official blog
F
Fortinet All Blogs
GbyAI
GbyAI
Forbes - Security
Forbes - Security
The Cloudflare Blog
博客园 - 司徒正美
博客园_首页
量子位
Schneier on Security
Schneier on Security
G
GRAHAM CLULEY
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Proofpoint News Feed
N
News | PayPal Newsroom
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
T
Tor Project blog
V
Vulnerabilities – Threatpost
Y
Y Combinator Blog
Jina AI
Jina AI
Help Net Security
Help Net Security
T
Threat Research - Cisco Blogs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
C
Cybersecurity and Infrastructure Security Agency CISA
Project Zero
Project Zero
N
News and Events Feed by Topic
I
Intezer
B
Blog
美团技术团队
C
CERT Recently Published Vulnerability Notes
NISL@THU
NISL@THU
L
LINUX DO - 最新话题
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Blog — PlanetScale
Blog — PlanetScale
AWS News Blog
AWS News Blog
T
Tailwind CSS Blog
The Last Watchdog
The Last Watchdog
雷峰网
雷峰网
有赞技术团队
有赞技术团队

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution Node.js Cluster Mode: Scaling the Event Loop Across CPU Cores Postgres Partial Indexes: Stopping Soft Deletes from Ruining Your Query Performance Request Coalescing with the Singleflight Pattern: Stop Drowning Your Database on Every Cache Miss The Bulkhead Pattern: Why One Slow Endpoint Should Not Drown Your Whole Service Node.js AsyncLocalStorage: End-to-End Request Context Without the Propagation Hell Postgres Deadlocks: Logging the Victim, Reproducing the Race, and Fixing the Lock Order Your Node.js HTTP Client Is the Bottleneck: Connection Pool Tuning That Works Optimistic Locking in Postgres: Stop Losing Data to Race Conditions Postgres Read Replicas: Stop Serving Stale Data to Your Users Cursor Pagination: Why Offset Queries Explode at Scale and How to Fix Them Node.js Worker Threads: 60 Lines That Stop a CSV Upload from Timing Out Every Other Request Reliable Webhook Delivery: Architecture for Outbound HTTP You Can Trust Request Timeouts and Deadline Propagation: Stop the Chain of Slowness Advanced Security Practices in Node.js Graceful Shutdown in Node.js: The 40 Lines That Stop 502s During Deploys Finding Node.js Memory Leaks with Heap Snapshots Idempotency Keys in 30 Lines: Stop Your Webhook From Charging Customers Twice Backpressure In Node.js: The Fix For Slow-Motion Queue Meltdowns Retries Done Right: Jitter, Budgets, and the Stampede You Did Not See Coming The Cache Stampede: Why Your "Just Add Redis" Layer Crashes Postgres at 3 a.m. Postgres SKIP LOCKED: An 80-Line Job Queue You Can Run Without Redis Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right I Tried 5 AI Coding Tools for a Month. Here Is What I Actually Use CI/CD From Zero to Production in 30 Minutes With GitHub Actions Node.js vs Bun vs Deno: Which Runtime Should You Pick in 2025? Kubernetes Resource Requests And Limits: The Numbers That Decide If Your Cluster Is Stable The Three Pillars of Observability Are A Myth: What Actually Matters In Production pnpm Vs npm Vs yarn Vs Bun For Monorepos: Which One Earns The Migration In 2024 JSONB Indexing In Postgres: GIN Vs Expression Indexes, And When Each Is The Right Choice A Code Review Checklist That Ends The Same Three Arguments Every Sprint gRPC Vs REST In 2024: When The Switch Pays For Itself React Suspense For Data Fetching: The Pattern That Replaces Half Your Loading State Code The Five-Stage Rollout: How To Ship A Risky Change Without Holding Your Breath GitHub Actions In A Monorepo: Caching, Path Filters, And Secret Boundaries That Actually Work The Blameless Postmortem That Actually Improves Things: A Template And Six Hard-Won Rules Recursive CTEs In Postgres: How To Query A Tree Without N Round Trips Node.js Streams: When They Actually Help, And When They Just Add Complexity Playwright Vs Cypress In 2024: The Honest Comparison Of Which One Earns The Test Time React Server Components: The Mental Model That Makes The "use client" Boundary Obvious Pod Disruption Budgets: The K8s Object That Keeps Your Service Up During Cluster Maintenance Postgres LISTEN/NOTIFY: The Pub/Sub You Already Have And Are Not Using Chaos Engineering Starter Kit: The Five Drills That Don't Need Netflix-Scale Spec-Driven API Development With OpenAPI: How To Stop Drifting From Your Docs Saga Pattern vs Two-Phase Commit: Distributed Transactions Without The Lies Kubernetes Autoscaling Beyond CPU: The Custom-Metric HPA Pattern That Actually Works Postgres Partitioning For Time-Series: The Boring Setup That Saves Your Database Distributed Locks With Redis: An Honest Look At Redlock And When You Don't Need It HTTP/2 vs HTTP/3: What Actually Changes For Your App, And What Doesn't Image Optimization For The Web In 2023: srcset, AVIF, And The Lighthouse Score You Actually Want Kafka vs RabbitMQ: A Decision Tree That Doesn't Hate You UUID vs Bigint Primary Keys In Postgres: The Index Math That Decides For You Flame Graphs: How To Find The Slow Function In 30 Seconds Without Profiling Theatre Postgres Streaming Vs. Logical Replication: Which One Solves Your Actual Problem ESLint Rules That Earn Their Keep: The Twelve I Enable On Every Project Pre-Commit Hooks That Pay For Themselves: Husky, lint-staged, And The Five Rules That Stick Zero-Downtime Database Migrations: The Six-Step Pattern That Rules Them All Circuit Breakers In Node.js: 50 Lines That Stop A Failing Dependency From Taking Down Your Service Postgres VACUUM Is Not Magic: How Your Hot Table Bloats To 80GB And How To Fix It Kubernetes Liveness And Readiness Probes: The Difference That Causes Half Your Outages Rate Limiting In Production: A Token Bucket In 30 Lines Of Redis The Outbox Pattern: How To Stop Losing Events When Postgres And Kafka Disagree Load Testing With k6: The Three Scenarios That Find Real Bugs (Not Synthetic Numbers) Postgres Row-Level Security For Multi-Tenant Apps: The Pattern That Stops You From Leaking Data Rebase vs. Merge: The Team Policy That Ends The Argument Forever OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident Feature Flags That Pay Rent: The 4 Flag Types And When To Delete Each ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong Connection Pooling Without the Cargo Cult: pgbouncer in 100 Lines of Config JSONB Is Not a Schema: When To Reach For It in Postgres, And When To Stop Bash Strict Mode: The Three Lines That Stop Your Deploy Script From Lying To You
The N+1 Query Problem: We Found 23 In One Codebase And Killed Every One
The Practica · 2026-05-02 · via The Practical Developer

Most “slow API” tickets are not really about slow APIs. They are about one endpoint that quietly fires four hundred queries to render a page that should fire two. The N+1 query problem is the single most common reason a perfectly fine-looking codebase grinds to a halt the moment real data hits it.

I went through a real Node.js + Postgres service we ship to production with the goal of finding every N+1 query in it. There were 23. Some were obvious. Some were hiding three function calls deep inside a serializer. Here is exactly how to find them, exactly how to fix them, and the numbers from before and after.

What N+1 actually is

You query for a list of N items. Then, for each item, you fire another query to load something related. That is 1 query for the list and N queries for the children. Hence “N+1”.

The classic version, in Prisma:

const posts = await prisma.post.findMany({ take: 50 });

for (const post of posts) {
  post.author = await prisma.user.findUnique({
    where: { id: post.authorId },
  });
}

Looks reasonable. Reviews fine. Loads 50 posts and fires 51 queries. On a busy endpoint with a cold cache, this is the difference between a 40ms response and a 1.8s response, not because any single query is slow, but because round-trip latency adds up fast.

The same shape shows up in Sequelize, TypeORM, ActiveRecord, Django ORM, and every hand-rolled repository that ever existed. ORMs do not cause N+1. They just make it easier to write.

Step 1: Stop trusting your local environment

Locally, with 12 rows in the database, an N+1 query takes 8ms total. In production, with 200,000 rows and the same code shape, it takes 4 seconds. Your dev machine will not catch this. You need to either seed real-sized data or watch the actual query count.

The cheapest way to see the truth is to log every query with its timing. In Prisma:

const prisma = new PrismaClient({
  log: [
    { emit: 'event', level: 'query' },
  ],
});

prisma.$on('query', (e) => {
  console.log(`${e.duration}ms  ${e.query}`);
});

Run a single API request. If a single endpoint produces more than ~5 lines, you almost certainly have an N+1 hiding in it.

For Sequelize:

const sequelize = new Sequelize(url, {
  logging: (sql, timing) => console.log(`${timing}ms  ${sql}`),
  benchmark: true,
});

For raw pg, wrap the client:

const originalQuery = client.query.bind(client);
client.query = async (...args) => {
  const start = Date.now();
  const result = await originalQuery(...args);
  console.log(`${Date.now() - start}ms  ${args[0]}`);
  return result;
};

This is enough to find the worst offenders. You do not need a fancy tool yet.

Step 2: Count queries per request

Once you know N+1 exists, the next move is to count queries per request automatically so you can fail a test or fail a build when the count regresses.

A tiny middleware that attaches a counter to each request:

import { AsyncLocalStorage } from 'node:async_hooks';

const queryContext = new AsyncLocalStorage<{ count: number }>();

prisma.$on('query', () => {
  const ctx = queryContext.getStore();
  if (ctx) ctx.count++;
});

app.use((req, res, next) => {
  queryContext.run({ count: 0 }, () => {
    res.on('finish', () => {
      const ctx = queryContext.getStore();
      console.log(`[${req.method} ${req.path}] queries: ${ctx?.count}`);
    });
    next();
  });
});

Now every request prints how many queries it ran. The first time we turned this on, the worst endpoint was firing 412 queries to load 50 posts with comments and authors. Once you can see it, you can fix it.

For the queries that survive deduplication, you want to know which ones are slow on their own merits. Postgres has had this answered for years:

EXPLAIN (ANALYZE, BUFFERS) SELECT ...;

Read the output bottom-up. The first thing to look for is Seq Scan on a table that should have an index, or a Rows Removed by Filter number that dwarfs the rows returned. Both mean Postgres scanned far more than it needed to.

Two extension flags that are worth a one-time setup on a dev or staging database:

CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
CREATE EXTENSION IF NOT EXISTS auto_explain;

pg_stat_statements aggregates queries by shape and ranks them by total time. If you have an N+1, the parent query and the per-row child query will both jump out. The child query will show up with a wildly high calls count and a small mean_exec_time. That signature is gold.

SELECT calls, mean_exec_time::int AS avg_ms, query
FROM pg_stat_statements
ORDER BY calls DESC
LIMIT 20;

auto_explain automatically logs the plan for any query slower than a threshold. Set it to 100ms in staging and the slow plans show up in your Postgres logs without anyone having to remember to instrument them.

Step 4: The fixes that actually work

Once you have the offending code, there are four patterns that handle 95% of N+1s. In rough order of how often I reach for them:

Eager load with an include or JOIN

The simplest fix. Tell the ORM to load the relation in the same query.

Before:

const posts = await prisma.post.findMany({ take: 50 });
for (const post of posts) {
  post.author = await prisma.user.findUnique({ where: { id: post.authorId } });
}

After:

const posts = await prisma.post.findMany({
  take: 50,
  include: { author: true },
});

Two queries instead of 51. The Prisma engine issues the parent select and a single IN (...) query for the authors, then stitches them in memory. Same result for the API consumer.

Batch with DataLoader for graph-shaped reads

When the call graph is recursive (a GraphQL resolver, a serializer that walks an object tree, anything where you cannot easily push the relation up to the top-level query) DataLoader is the right tool.

import DataLoader from 'dataloader';

const userLoader = new DataLoader<string, User>(async (ids) => {
  const users = await prisma.user.findMany({
    where: { id: { in: [...ids] } },
  });
  const byId = new Map(users.map((u) => [u.id, u]));
  return ids.map((id) => byId.get(id)!);
});

// Anywhere in the request, in any resolver:
const author = await userLoader.load(post.authorId);

DataLoader collects every .load(id) call within a single tick of the event loop and fires one batch query. The interface still looks like findById, but under the hood it is findByIds. Drop one of these into a per-request context and most graph N+1s evaporate.

Aggregate in SQL, not in Node

A classic pattern: load posts, then for each post, count the comments.

const posts = await prisma.post.findMany({ take: 50 });
for (const post of posts) {
  post.commentCount = await prisma.comment.count({
    where: { postId: post.id },
  });
}

Push the count into SQL:

const posts = await prisma.post.findMany({
  take: 50,
  include: { _count: { select: { comments: true } } },
});

Or, when the ORM’s aggregate API isn’t expressive enough, drop to raw SQL:

const posts = await prisma.$queryRaw<Post[]>`
  SELECT
    p.*,
    COUNT(c.id) AS comment_count
  FROM posts p
  LEFT JOIN comments c ON c.post_id = p.id
  GROUP BY p.id
  ORDER BY p.created_at DESC
  LIMIT 50
`;

Postgres is far better at counting things than your application server. Let it.

Denormalize when the query never gets fast enough

For a feed endpoint we ship that loads 20 posts with their author, top 3 comments, like count, and current user’s reaction, we tried every combination of joins and aggregates. The plan was always somewhere between 80ms and 200ms, fine, but the budget was 25ms.

We added a comment_count and like_count column to posts, kept them in sync with triggers, and dropped the joins. The endpoint now serves in 12ms. The cost is two integer columns and four lines of trigger SQL. Worth it.

CREATE OR REPLACE FUNCTION bump_post_comment_count() RETURNS trigger AS $$
BEGIN
  IF (TG_OP = 'INSERT') THEN
    UPDATE posts SET comment_count = comment_count + 1 WHERE id = NEW.post_id;
  ELSIF (TG_OP = 'DELETE') THEN
    UPDATE posts SET comment_count = comment_count - 1 WHERE id = OLD.post_id;
  END IF;
  RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER comments_count_trigger
AFTER INSERT OR DELETE ON comments
FOR EACH ROW EXECUTE FUNCTION bump_post_comment_count();

Denormalization gets a bad name because people reach for it before they have tried indexing or aggregating. Earn it; do not start there.

Step 5: Lock it down so it does not come back

Fixing N+1 is not a one-time job. The same patterns will sneak back in within two sprints unless you put a gate in place.

A simple integration test that asserts query counts works surprisingly well:

it('GET /feed runs at most 4 queries', async () => {
  let count = 0;
  prisma.$on('query', () => count++);

  await request(app).get('/feed?limit=50').expect(200);

  expect(count).toBeLessThanOrEqual(4);
});

If someone adds a serializer that fires per-row queries, this test fails before the code reaches main. We have three of these on our hottest endpoints. They have caught regressions four times in the last six months.

For production observability, add the per-request query count to your structured logs and chart it. A sudden jump in average queries-per-request on a stable endpoint almost always means someone reintroduced an N+1.

The before-and-after

After two days of work (finding, fixing, and adding the regression tests) the numbers across the worst five endpoints in the service:

EndpointQueries beforeQueries afterp50 beforep50 after
GET /feed41231.81s42ms
GET /users/:id/posts1872820ms28ms
GET /search964640ms71ms
GET /notifications683410ms24ms
GET /admin/audit24452.10s96ms

No new infrastructure. No caching layer. No rewrite. Just finding the queries and replacing them with the version that should have been written the first time.

A few patterns that did not pay off

Worth calling out, since these get recommended a lot:

A blanket Redis cache in front of the API. Tempting, but it papers over the underlying problem and creates a new one (cache invalidation). The endpoints we cache today are the ones we cache after fixing the queries, not before.

Switching ORMs. We considered moving from Prisma to Drizzle “to get more control”. The N+1s would have moved with us. The bottleneck was code shape, not ORM.

Manually sharding the parent query into smaller LIMIT chunks. Marginally helps for a single slow query. Does nothing for an N+1, since the per-row child query is the actual problem.

The takeaway

If your API is slow and you have not yet logged every query for one request, do that first. It will tell you within five minutes whether you have an N+1 problem, and which endpoint to look at. Most fixes are one-line changes (an include, a DataLoader, a _count) and the speedups are not 20%; they are 10x to 50x.

The work is unglamorous. Nobody will notice until the graphs go down and stay down. That is the point.


This article was put together by The Practical Developer, with notes from query-tuning work we have done on real production systems. If you are building a service where this kind of database hygiene matters and you would rather hire the practice than learn it the hard way, Yojji is the international software development studio behind a lot of the work that ends up here. Founded in 2016, with offices across Europe, the US, and the UK, Yojji builds custom web and mobile products with senior engineers, dedicated teams, and a strong bias toward shipping software that holds up under real load, including the boring, valuable work of keeping query counts honest.