Logo Backend Graphql Optimization

Backend Graphql Optimization

Cộng đồng
j4flmao
backend-graphql-optimization

Use this skill when the user says 'graphql n+1', 'dataloader', 'graphql slow', 'graphql performance', 'batch resolvers', 'query complexity', 'depth limit', 'persisted queries', 'graphql caching'. Diagnoses and fixes GraphQL server performance: N+1 resolver queries with per-request DataLoader, query depth/complexity limits, persisted queries, and response caching. Do NOT use for: schema design and general resolver patterns (backend-graphql-patterns), federated supergraphs (api-graphql-federation), client-side Apollo/urql caching (frontend data-fetching).

Tổng quan

Nhà phát hànhj4flmao
Kho mãagent-skills
Tên kỹ năngbackend-graphql-optimization
Sao
41
Bản fork
6
Tệp đi kèm
Chỉ có hướng dẫn
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Đầy đủ trong hướng dẫn

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được j4flmao công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Backend Graphql Optimization trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/graphql-optimization
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/backend/graphql-optimization .claude/skills/backend-graphql-optimization
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Backend Graphql Optimization trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Backend Graphql Optimization ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Backend Graphql Optimization không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

GraphQL Optimization

Purpose

GraphQL resolvers run per field, so a naive implementation issues one database query per parent object (N+1) and lets clients send arbitrarily expensive queries. This skill removes N+1 with batching, bounds query cost, and adds caching where it is safe.

Agent Protocol

Trigger

Exact user phrases: "graphql n+1", "dataloader", "graphql slow", "graphql performance", "batch resolvers", "query complexity", "depth limit", "persisted queries", "graphql caching".

Input Context

  • Server library (Apollo Server, GraphQL Yoga, Mercurius, graphql-java, Strawberry, gqlgen, Hot Chocolate).
  • Data layer (SQL/ORM, REST backends) and the slow query or resolver.
  • Whether the API is public (untrusted clients) or first-party only.

Output Artifact

Loader definitions, context wiring, and server validation/caching config. No files unless requested.

Response Format

Problem: {N+1 on Type.field | unbounded query | no caching}
Fix: {DataLoader keyed by X | depth<=N, complexity<=M | APQ/persisted | cache hint}
Queries before/after: {n} -> {m}
Code: {loader + resolver + server config}

Diagnosing N+1

Enable SQL logging (or tracing via OpenTelemetry) and run a list query such as:

graphql
{ posts(first: 50) { id title author { name } } }

51 queries (SELECT posts + 50 x SELECT user WHERE id = ?) is N+1. Target: 2 queries.

DataLoader (Node.js)

Rules that make DataLoader correct:

  1. Create loaders per request (in the context factory). A global loader caches across users and leaks data between requests.
  2. The batch function receives an array of keys and must return an array of the same length in the same order, with null or an Error instance for missing keys.
  3. Batching happens within one tick of the event loop; resolvers just call loader.load(id).
ts
import DataLoader from 'dataloader';
import type { Pool } from 'pg';

export interface User { id: string; name: string }

export function createLoaders(db: Pool) {
  return {
    userById: new DataLoader<string, User | null>(async (ids) => {
      const { rows } = await db.query<User>(
        'SELECT id, name FROM users WHERE id = ANY($1)',
        [ids as string[]],
      );
      const byId = new Map(rows.map((u) => [u.id, u]));
      return ids.map((id) => byId.get(id) ?? null);
    }),
    // One-to-many: key = authorId, value = that author's posts.
    postsByAuthor: new DataLoader<string, Post[]>(async (authorIds) => {
      const { rows } = await db.query<Post>(
        'SELECT * FROM posts WHERE author_id = ANY($1)',
        [authorIds as string[]],
      );
      const grouped = new Map<string, Post[]>();
      for (const p of rows) {
        const list = grouped.get(p.author_id) ?? [];
        list.push(p);
        grouped.set(p.author_id, list);
      }
      return authorIds.map((id) => grouped.get(id) ?? []);
    }),
  };
}

export interface Post { id: string; title: string; author_id: string }

Resolvers and per-request context (Apollo Server 4+ standalone):

ts
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import depthLimit from 'graphql-depth-limit';
import { Pool } from 'pg';
import { createLoaders } from './loaders';
import { typeDefs } from './schema'; // SDL string or DocumentNode

const db = new Pool({ connectionString: process.env.DATABASE_URL });

type Ctx = { loaders: ReturnType<typeof createLoaders> };

const resolvers = {
  Post: {
    author: (post: { author_id: string }, _: unknown, ctx: Ctx) =>
      ctx.loaders.userById.load(post.author_id),
  },
  User: {
    posts: (user: { id: string }, _: unknown, ctx: Ctx) =>
      ctx.loaders.postsByAuthor.load(user.id),
  },
};

const server = new ApolloServer<Ctx>({
  typeDefs,
  resolvers,
  validationRules: [depthLimit(8)], // reject deeply nested queries
});

await startStandaloneServer(server, {
  context: async () => ({ loaders: createLoaders(db) }), // fresh per request
});

Equivalents in other stacks: java-dataloader (graphql-java, Spring for GraphQL @BatchMapping), strawberry.dataloader.DataLoader (Python), graph-gophers/dataloader or gqlgen's dataloaden pattern (Go), Hot Chocolate BatchDataLoader (.NET).

Alternative: Join-Based Resolution

When the parent resolver can see the selection set, fetch children in the same SQL with a JOIN (tools: Join Monster, PostGraphile, Hasura, Prisma include). This is faster for fixed shapes but couples resolvers to SQL; DataLoader stays simpler and works across data sources.

Bounding Query Cost

ControlWhat it stopsNotes
Depth limita { b { a { b ... } } } recursion7-10 is typical
Complexity/cost analysisWide queries (first: 1000 nested twice)graphql-query-complexity; weight list fields by their first/limit argument
Pagination capsUnbounded listsEnforce max first, e.g. 100, in resolvers
Persisted queries / allow-listArbitrary client queriesStrongest control for first-party clients
TimeoutsSlow resolvers holding connectionsPer-request deadline propagated to DB calls
Disable introspection in prod (public APIs)Schema miningDefense in depth only, not a security boundary

Caching

LayerMechanismCaveat
Per-requestDataLoader memoizationAutomatic; scoped to one request
Field/entityRedis cache inside loaders or servicesInvalidate on writes like any cache-aside
Whole responseApollo @cacheControl hints + response cache plugin, or CDNOnly for public or per-user-keyed data
HTTP/CDNAutomatic Persisted Queries (APQ) sent as GET with a hashEnables CDN caching of query responses

Anti-Patterns

Anti-patternFix
DataLoader instantiated at module scopeCreate in context per request
Batch function returns rows in DB orderMap back to input key order
load() inside a loop with await each timePromise.all(ids.map(id => loader.load(id))) or loadMany
Fetching all columns for every resolverSelect only needed fields or use projection from info
No list size limitCap first/limit and compute cost

Checklist

  • Query count for representative list queries measured before and after.
  • Every relation resolver goes through a per-request loader or join.
  • Depth limit, cost limit and max page size enforced.
  • Persisted queries for first-party clients.
  • Resolver timings traced (OpenTelemetry) to find hot fields.

References

  • Related skills: skills/backend/universal/graphql-patterns/SKILL.md, skills/backend/universal/api/graphql-federation/SKILL.md, skills/backend/universal/caching/SKILL.md.

Câu hỏi thường gặp

Kỹ năng AI Backend Graphql Optimization làm được gì?

Use this skill when the user says 'graphql n+1', 'dataloader', 'graphql slow', 'graphql performance', 'batch resolvers', 'query complexity', 'depth limit', 'persisted queries', 'graphql caching'. Diagnoses and fixes GraphQL server performance: N+1 resolver queries with per-request DataLoader, query depth/complexity limits, persisted queries, and response caching. Do NOT use for: schema design and general resolver patterns (backend-graphql-patterns), federated supergraphs (api-graphql-federation), client-side Apollo/urql caching (frontend data-fetching).

Vì sao nên dùng Backend Graphql Optimization trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Backend Graphql Optimization là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Backend Graphql Optimization trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/j4flmao/agent-skills/tree/main/skills/backend/graphql-optimization. TypingMind đọc tệp SKILL.md và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Backend Graphql Optimization?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Backend Graphql Optimization với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Backend Graphql Optimization với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Backend Graphql Optimization có miễn phí không?

Có. Kỹ năng này được j4flmao phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇