graphql-performance
Use when optimizing GraphQL API performance with query complexity analysis, batching, caching strategies, depth limiting, monitoring, and database optimization.
What this skill does
# GraphQL Performance
Apply GraphQL performance optimization techniques to create efficient,
scalable APIs. This skill covers query complexity analysis, depth
limiting, batching and caching strategies, DataLoader optimization,
monitoring, tracing, and database query optimization.
## Query Complexity Analysis
Query complexity analysis prevents expensive queries from overwhelming
your server by calculating and limiting the computational cost.
```typescript
import { GraphQLError } from 'graphql';
import { ApolloServer } from '@apollo/server';
// Complexity calculator
const getComplexity = (field, childComplexity, args) => {
// Base complexity for field
let complexity = 1;
// List multiplier based on limit argument
if (args.limit) {
complexity = args.limit;
} else if (args.first) {
complexity = args.first;
}
// Add child complexity
return complexity + childComplexity;
};
// Directive-based complexity
const schema = `
directive @complexity(
value: Int!
multipliers: [String!]
) on FIELD_DEFINITION
type Query {
user(id: ID!): User @complexity(value: 1)
users(limit: Int): [User!]! @complexity(
value: 1,
multipliers: ["limit"]
)
posts(first: Int): [Post!]! @complexity(
value: 5,
multipliers: ["first"]
)
}
type User {
id: ID!
posts: [Post!]! @complexity(value: 10)
}
`;
// Complexity validation plugin
const complexityPlugin = {
requestDidStart: () => ({
async didResolveOperation({ request, document, operationName }) {
const complexity = calculateComplexity({
document,
operationName,
variables: request.variables
});
const maxComplexity = 1000;
if (complexity > maxComplexity) {
throw new GraphQLError(
`Query is too complex: ${complexity}. ` +
`Maximum allowed: ${maxComplexity}`,
{
extensions: {
code: 'QUERY_TOO_COMPLEX',
complexity,
maxComplexity
}
}
);
}
}
})
};
// Manual complexity calculation
const calculateComplexity = ({ document, operationName, variables }) => {
let totalComplexity = 0;
const visit = (node, multiplier = 1) => {
if (node.kind === 'Field') {
// Get field complexity from directive or default
const complexity = getFieldComplexity(node);
// Handle multipliers from arguments
const args = getArguments(node, variables);
const fieldMultiplier = getMultiplier(args);
totalComplexity += complexity * multiplier * fieldMultiplier;
// Visit child fields
if (node.selectionSet) {
node.selectionSet.selections.forEach(child =>
visit(child, multiplier * fieldMultiplier)
);
}
}
};
visit(document);
return totalComplexity;
};
```
## Depth Limiting
Prevent deeply nested queries that can cause performance issues and
potential denial of service attacks.
```typescript
import { ValidationContext, GraphQLError } from 'graphql';
const depthLimit = (maxDepth: number) => {
return (validationContext: ValidationContext) => {
return {
Field(node, key, parent, path, ancestors) {
const depth = ancestors.filter(
ancestor => ancestor.kind === 'Field'
).length;
if (depth > maxDepth) {
validationContext.reportError(
new GraphQLError(
`Query exceeds maximum depth of ${maxDepth}. ` +
`Found depth of ${depth}.`,
{
nodes: [node],
extensions: {
code: 'DEPTH_LIMIT_EXCEEDED',
depth,
maxDepth
}
}
)
);
}
}
};
};
};
// Usage with Apollo Server
const server = new ApolloServer({
typeDefs,
resolvers,
validationRules: [depthLimit(7)]
});
// Example queries
// ✅ Allowed (depth: 4)
query {
user {
posts {
comments {
author {
username
}
}
}
}
}
// ❌ Rejected (depth: 8)
query {
user {
friends {
friends {
friends {
friends {
friends {
friends {
friends {
username
}
}
}
}
}
}
}
}
}
```
## Query Cost Analysis
Implement cost-based rate limiting to protect against expensive
queries.
```typescript
interface CostConfig {
objectCost: number;
scalarCost: number;
defaultListSize: number;
}
const calculateQueryCost = (
document,
variables,
config: CostConfig
) => {
let totalCost = 0;
const visit = (node, multiplier = 1) => {
if (node.kind === 'Field') {
const fieldType = getFieldType(node);
// List cost
if (isListType(fieldType)) {
const listSize = getListSize(node, variables) ||
config.defaultListSize;
multiplier *= listSize;
}
// Field cost
if (isObjectType(fieldType)) {
totalCost += config.objectCost * multiplier;
} else {
totalCost += config.scalarCost * multiplier;
}
// Visit children
if (node.selectionSet) {
node.selectionSet.selections.forEach(child =>
visit(child, multiplier)
);
}
}
};
visit(document);
return totalCost;
};
// Rate limiting based on cost
const costLimitPlugin = {
requestDidStart: () => ({
async didResolveOperation({ request, document, contextValue }) {
const cost = calculateQueryCost(
document,
request.variables,
{ objectCost: 1, scalarCost: 0.1, defaultListSize: 10 }
);
// Check user's rate limit
const limit = await getRateLimit(contextValue.user);
const used = await getCostUsed(contextValue.user);
if (used + cost > limit) {
throw new GraphQLError('Rate limit exceeded', {
extensions: {
code: 'RATE_LIMIT_EXCEEDED',
cost,
used,
limit
}
});
}
// Track cost usage
await incrementCostUsed(contextValue.user, cost);
}
})
};
```
## Batching with DataLoader
Optimize data fetching by batching multiple requests into single
database queries.
```typescript
import DataLoader from 'dataloader';
// Basic DataLoader setup
const createUserLoader = (db) => {
return new DataLoader<string, User>(
async (userIds) => {
// Single query for all users
const users = await db.users.findByIds(userIds);
// Map to maintain order
const userMap = new Map(users.map(u => [u.id, u]));
return userIds.map(id => userMap.get(id) || null);
},
{
// Cache for duration of request
cache: true,
// Batch at most 100 at a time
maxBatchSize: 100,
// Wait 10ms before batching
batchScheduleFn: callback => setTimeout(callback, 10)
}
);
};
// Advanced batching with joins
const createPostsLoader = (db) => {
return new DataLoader<string, Post[]>(
async (authorIds) => {
// Single query with all author IDs
const posts = await db.posts.query()
.whereIn('authorId', authorIds)
.select();
// Group by author ID
const postsByAuthor = authorIds.map(authorId =>
posts.filter(post => post.authorId === authorId)
);
return postsByAuthor;
}
);
};
// Multi-key loader
interface PostKey {
authorId: string;
status: string;
}
const createFilteredPostsLoader = (db) => {
return new DataLoader<PostKey, Post[]>(
async (keys) => {
// Extract unique author IDs and statuses
const authorIds = [...new Set(keys.map(k => k.authorId))];
const statuses = [...new Set(keys.map(k => k.status))];
// Single query for all combinations
const posts = await db.posts.query()
.whereIn('authorId', authorIds)
.whereIn('status', statuses)
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.