Query optimization techniques in GraphQL

From the GraphQL cheat sheet · Performance Optimization · verified Jul 2026

Query optimization techniques

javascript
// Query depth limiting
const depthLimit = require('graphql-depth-limit');

const server = new ApolloServer({
  typeDefs,
  resolvers,
  validationRules: [
    depthLimit(5) // Max depth of 5
  ]
});

// Query complexity analysis
const { 
  createComplexityLimitRule 
} = require('graphql-validation-complexity');

const server = new ApolloServer({
  typeDefs,
  resolvers,
  validationRules: [
    createComplexityLimitRule(1000, {
      onCost: (cost) => console.log('Query cost:', cost),
      scalarCost: 1,
      objectCost: 2,
      listFactor: 10,
      introspectionCost: 1000,
    })
  ]
});

// Caching with Redis
const Redis = require('ioredis');
const redis = new Redis();

const resolvers = {
  Query: {
    popularPosts: async (parent, args, context) => {
      const cacheKey = 'popular_posts';
      
      // Check cache
      const cached = await redis.get(cacheKey);
      if (cached) {
        return JSON.parse(cached);
      }
      
      // Fetch from database
      const posts = await db.post.findMany({
        where: { published: true },
        orderBy: { views: 'desc' },
        take: 10
      });
      
      // Cache for 5 minutes
      await redis.setex(cacheKey, 300, JSON.stringify(posts));
      
      return posts;
    }
  }
};
💡 Use DataLoader for batching
⚡ Implement query depth limiting
📌 Add query complexity analysis
🔥 Cache with Redis or in-memory
Back to the full GraphQL cheat sheet