Command Palette

Search for a command to run...

Назад к скиллам
скилл № 45125

graphql-n-plus-one-remediation

Use whenever a GraphQL query fires one database query per item (N+1), a slow-query alert traces to GraphQL, or a PR adds a list resolver: find the fan-out…

БесплатноБез исполняемых скриптов
testlandот testland★ 18 звёзд на GitHub

Установить graphql-n-plus-one-remediation в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Об этом скилле

graphql-n-plus-one-remediation

What N+1 looks like in a resolver tree

One field returns a list of N rows. The executor then invokes the resolver for each inner field once per row, so if Query.topReviews returns ten reviews the executor resolves Review.product ten times, and a data-source call in that child field becomes ten calls (apollographql.com). So 1 outer query plus N inner queries equals N+1.

// Parent resolver fetches N posts
posts: () => db.posts.findMany({ limit: 50 })

// Inner field-resolver fires once per post (50 DB calls)
Post: {
  author: (post) => db.users.findOne({ where: { id: post.authorId } }),
}

GraphQL makes the pattern easy to hit because the resolver tree, not the caller, decides how many times a child field runs.

Observable symptoms (practitioner heuristics, not standardised thresholds):

  • Tail latency on a list field grows roughly in proportion to the number of rows the list returns.
  • Database connection pool exhaustion under modest GraphQL request rates.
  • A resolver-level trace shows the child field resolved once per parent row rather than once per request.

What this skill owns, and what it does not

Owned: locating the N+1 pattern inside a resolver tree and changing the data-loading strategy so the child field costs one batched call instead of N calls.

Not owned:

  • Query complexity or depth limiting. Those reject an expensive query before execution. They cap what a client may ask for. They do not make a legitimate list query cheap, and a schema with correct batching still needs them for denial-of-service protection.
  • Rate limiting. That caps how many requests a client sends. An N+1 resolver is still N+1 on the first allowed request.
  • Caching strategy. DataLoader's cache is a per-request memoization of .load() calls, not a shared store, and does not replace Redis or Memcache (github.com/graphql/dataloader). Deciding what to put in Redis is a different job from removing the fan-out.
  • SQL-level fan-out. A resolver that looks batched in JavaScript can still emit per-row SQL underneath. Confirm at the database layer with a query-log or slow-query analysis.

Step 0: Detection workflow (repo scan)

When the input is a repo, PR diff, or schema type rather than a known resolver, locate the candidates first. Input modes:

  • A specific resolver file or directory (resolvers/post.ts).
  • A PR diff (git diff main...HEAD --name-only -- '*resolvers*').
  • A schema type (User) - find all resolvers on that type.

Grep for list-returning resolvers and entry points:

grep -rn "resolve:.*=>" resolvers/
grep -rn "Query: {\|Mutation: {" resolvers/  # entry points
grep -rn "\[.*\]" schema/                     # list-typed fields in schema

Enumerate every resolver that returns a list and every field resolver on the types in those lists, then continue with Step 1. SQL-level fan-out beneath the ORM hands off to db-query-plan-analyzer.

Step 1: Map the parent and child pairs

For every field that returns a list, write down the type it returns and every field resolver defined on that type. That parent/child pair is the only place N+1 can appear: a field resolver on a non-list parent runs once and cannot fan out.

Record the pairs in a table before judging any of them:

Parent field Returns Child field resolvers on the returned type
Query.posts [Post] Post.author, Post.comments
Post.comments [Comment] Comment.author

Nested list fields matter most: Query.posts returning 50 posts, each with Post.comments returning 10 comments, gives 500 invocations of Comment.author.

Step 2: Classify each child field resolver

Classify every child field resolver from the table above. Only the last three rows need a fix.

Resolver pattern Verdict
Calls a batching loader (loader.load(id)) Safe: batched per tick
Returns a value already on the parent object ((parent) => parent.author) and the parent query eagerly fetched it Safe: no data-source call
Reads from an in-memory structure already on the request context Safe: no per-call data-source hit
Makes one database call per invocation (db.x.findOne({ ... })) N+1 risk
Makes one HTTP call per invocation N+1 risk, usually worse: each call pays network latency
Reads a related record through an ORM that lazy-loads N+1 risk, and silent: the ORM hides the extra roundtrip

The second row has a trap. (parent) => parent.author is safe only when the parent query actually loaded author. In Prisma, related records are not returned unless the query asks for them via include or select (prisma.io). If the parent query has no matching `i

Полный SKILL.md на GitHub

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

  • .tessl-plugin/plugin.json
  • references/examples.md
  • references/fixes.md

FAQ

Что делает скилл graphql-n-plus-one-remediation?

Use whenever a GraphQL query fires one database query per item (N+1), a slow-query alert traces to GraphQL, or a PR adds a list resolver: find the fan-out, write a test that counts queries, and fix it with DataLoader batching, parent projection or selection-set prefetch.

Как установить скилл graphql-n-plus-one-remediation?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл graphql-n-plus-one-remediation запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить graphql-n-plus-one-remediation с