Logo di Backend Graphql Optimization

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

Panoramica

Autorej4flmao
Repositoryagent-skills
Nome della skillbackend-graphql-optimization
Stelle
41
Fork
6
File inclusi
Solo istruzioni
LicenzaMIT
Link
  • Istruzioni in Markdown

    Un file SKILL.md che il modello carica quando serve, consumando token solo quando una richiesta è effettivamente pertinente.

  • Funziona con qualsiasi LLM

    Le skill IA sono in semplice Markdown, non in codice specifico di un fornitore, quindi funzionano con GPT, Claude, Gemini, Grok o un modello locale.

  • Tutto nelle istruzioni

    Tutto ciò che serve al modello è nelle istruzioni: nessun file aggiuntivo da sincronizzare.

  • Open source

    Pubblicata da j4flmao su GitHub. Leggi i sorgenti prima di installarla.

Installazione

Installa la skill IA Backend Graphql Optimization in TypingMind per usarla con qualsiasi LLM, oppure copiala in un altro agente in grado di leggere SKILL.md.

1

Installa in TypingMind

TypingMind installa una skill direttamente dalla sua cartella GitHub: legge SKILL.md, raccoglie i file delle risorse e salva il risultato in locale.

  1. Apri l'app e vai su Plugin → Skill.
  2. Scegli "Installa da GitHub".
  3. Incolla l'URL della cartella della skill riportato qui sotto e conferma.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/graphql-optimization
  4. Attiva la skill in ogni chat in cui vuoi averla a disposizione.
Plugin → Skill → Nuova skill → Da URL GitHub, poi incolla l'URL della cartella e premi Continua.
2

Installa in un altro agente

Qualsiasi agente che legge il formato Agent Skills può usare questa skill: copia la cartella nella cartella delle skill di quell'agente.

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
Dopo la copia, riavvia Claude Code per caricare la nuova skill.

Usala in TypingMind

Attiva Backend Graphql Optimization in qualsiasi chat di TypingMind e al resto pensa il modello. Il nome e la descrizione della skill sono nel prompt di sistema e, non appena arriva una richiesta pertinente, il modello carica da solo le istruzioni complete: non devi mai richiamarla manualmente e non consuma token finché non viene effettivamente usata.

Il modello carica automaticamente Backend Graphql Optimization non appena riceve una richiesta pertinente.

Funziona con qualsiasi modello IA

Le skill IA sono semplici istruzioni in Markdown, non codice specifico di un fornitore, quindi Backend Graphql Optimization non è vincolata al modello per cui è stata scritta. Installala una sola volta in TypingMind e usala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modello locale che esegui tu, sempre con le tue chiavi API.

  • Caricata solo quando serve

    Il prompt di sistema contiene solo il nome e la descrizione. Le istruzioni vengono recuperate alla prima richiesta pertinente, quindi una skill inutilizzata non costa nulla.

  • Cambia modello durante la chat

    Poiché la skill è composta da istruzioni e non da codice, continua a funzionare anche se cambi modello: il nuovo modello legge lo stesso file SKILL.md.

Istruzioni della skill

Questo è il contenuto di SKILL.md che il modello carica. Leggilo prima dell'installazione: una skill è un insieme di istruzioni che il tuo modello seguirà.

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.

Domande frequenti

Cosa fa la skill IA 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).

Perché usare Backend Graphql Optimization su TypingMind?

Perché la installi una volta e la usi con qualsiasi modello. Backend Graphql Optimization è scritta in semplice Markdown anziché in codice specifico di un fornitore, quindi la stessa skill funziona con GPT-5, Claude, Gemini, Grok o un modello locale, e puoi cambiare modello durante la chat senza che smetta di funzionare. TypingMind usa le tue chiavi API, quindi paghi direttamente i fornitori anziché un abbonamento per posto utente, e le tue skill e chat restano nel tuo spazio di archiviazione.

Come installo Backend Graphql Optimization in TypingMind?

Apri Plugin → Skill → Installa da GitHub in TypingMind e incolla https://github.com/j4flmao/agent-skills/tree/main/skills/backend/graphql-optimization. TypingMind legge il file SKILL.md e installa la skill, che puoi abilitare per ogni singola chat.

Quali modelli IA possono usare Backend Graphql Optimization?

Qualsiasi modello che colleghi in TypingMind. Le skill IA sono semplici istruzioni in Markdown anziché codice specifico di un fornitore, quindi GPT, Claude, Gemini, Grok e i modelli locali possono tutti caricare questa skill quando una richiesta corrisponde al suo scopo.

Quanti modelli IA posso usare con Backend Graphql Optimization?

Quanti ne vuoi. Se un modello supporta le skill, puoi usarlo con Backend Graphql Optimization: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e molti altri, tutti su TypingMind con le tue chiavi API.

La skill IA Backend Graphql Optimization è gratuita?

Sì. È pubblicata su GitHub da j4flmao con licenza MIT. Paghi solo il tuo fornitore IA per i token che usi.

Cosa sono le skill IA?

Una skill IA è un pacchetto di istruzioni riutilizzabili che insegna a un modello IA come svolgere un'attività specifica. Segue il formato aperto Agent Skills: un file SKILL.md con un nome e una descrizione, più eventuali script, modelli o file di riferimento di cui il modello potrebbe aver bisogno. Il modello legge le istruzioni solo quando la tua richiesta corrisponde alla skill, quindi una skill installata non comporta costi finché non viene usata.

In cosa si differenziano le skill IA dai plugin o dai server MCP?

Un plugin o un server MCP fornisce a un modello nuovi strumenti da richiamare: codice che viene eseguito da qualche parte e restituisce un risultato. Una skill IA, invece, fornisce al modello conoscenze e procedure: come affrontare un'attività, quali passaggi seguire e quali caratteristiche deve avere un buon output. Le skill sono semplici istruzioni in Markdown, quindi non richiedono server, chiavi API né ambienti di esecuzione e funzionano con qualsiasi modello.

Vedi tutti

Crea subito la tua area di lavoro IA

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇