The Real Fullstack

The GraphQL N+1

One GraphQL request. Why does PostgreSQL see 713 queries?

エンジニア8 分パフォーマンスラボデバッグラボ
graphqldataloadernodepostgresql

この課題はまだ日本語に翻訳されていません。英語版を表示しています。

ミッション:Find why one request becomes hundreds of queries, batch them safely, and stop abusive query shapes.背景 · 学習目標 ▾

Wrenly's mobile feed asks for 50 posts with their authors and comments. Each resolver fetches its author by id. The feed takes 2.3 s, and anonymous clients have started sending deeply nested queries that burn 40 s of CPU.

ミッション: Find why one request becomes hundreds of queries, batch them safely, and stop abusive query shapes.

学習目標

  • Recognise N+1 queries caused by per-field resolvers.
  • Batch and de-duplicate loads per request with DataLoader.
  • Limit query depth or cost on public GraphQL APIs.
シミュレーションシミュレーション値
mobile appGraphQL serverPostgreSQL
シミュレーションを実行
// one loader per request (never shared between users)const context = ({ req }) => ({  userLoader: new DataLoader(async (ids) => {    const rows = await db.users.findByIds(ids);              // SELECT … WHERE id = ANY($1)    return ids.map((id) => rows.find((u) => u.id === id));  }),});const resolvers = {  Post:    { author: (p, _, ctx) => ctx.userLoader.load(p.authorId) },  Comment: { author: (c, _, ctx) => ctx.userLoader.load(c.authorId) },};// plus: depth / cost limits on incoming queries

簡略化

Three symptoms with deterministic fixes. Query cost analysis can be more precise than depth limits. 教育用モデルです。数値は挙動を示すためのもので、ベンチマークではありません。

コンセプト

先に取り組むと役立つ課題

関連する課題

参考資料