Back to Blog
August 30, 2024 1 min read

N+1 Query Bug in GraphQL Resolvers

Bug Fix
Depth: ●●○○○
Share:

How I discovered and fixed an N+1 query problem that was causing 50+ database queries per request.

Discovery

API responses were taking 2+ seconds. Logging revealed 50-100 database queries per request. Each workout was triggering a separate query to fetch its exercises.

Root Cause

GraphQL resolver for 'exercises' field was fetching exercises one workout at a time. With 50 workouts in a plan, that's 50 separate queries.

The Fix

Implemented DataLoader to batch and cache database queries. All exercises now fetched in a single query with WHERE workout_id IN (...). Response time dropped to 150ms.