Backend Graphql Optimization logo

Backend Graphql Optimization

Community
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).

Overview

Publisherj4flmao
Repositoryagent-skills
Skill namebackend-graphql-optimization
Stars
41
Forks
6
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by j4flmao on GitHub. Read the source before you install it.

Installation

Install the Backend Graphql Optimization AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/graphql-optimization
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

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
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Backend Graphql Optimization in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Backend Graphql Optimization on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Backend Graphql Optimization is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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.

Frequently asked questions

What does the Backend Graphql Optimization AI skill do?

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).

Why use Backend Graphql Optimization on TypingMind?

Because you install it once and use it with any model. Backend Graphql Optimization is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Backend Graphql Optimization in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/j4flmao/agent-skills/tree/main/skills/backend/graphql-optimization. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Backend Graphql Optimization?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Backend Graphql Optimization?

As many as you like. As long as a model supports skills, you can use Backend Graphql Optimization with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Backend Graphql Optimization AI skill free?

Yes. It is published on GitHub by j4flmao under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇