Api Design medium
A GraphQL query fetches 50 users and their posts. The resolver fetches users (1 query), then for each user fetches posts (50 queries). How is this solved?
- A Implement the DataLoader pattern to batch IDs from the event loop tick and fetch all related posts in a single 'WHERE IN' database query.
- B Configure the GraphQL server to use deep-fragment caching, storing the result of every individual post resolver to avoid redundant database calls.
- C Modify the schema to include a 'post_list' field on the User type that performs a manual SQL join at the database layer during the user fetch.
- D Shift the responsibility to the client application to fetch users first, and then make 50 individual parallel REST calls to fetch posts per user.
Answer: A. Implement the DataLoader pattern to batch IDs from the event loop tick and fetch all related posts in a single 'WHERE IN' database query.
The **N+1 problem** occurs when a query fetches a list of N parent items (1 query), and then for each parent, executes a separate query to fetch child data (N queries). **DataLoader** solves this by batching requests. It collects all IDs from the individual resolvers in a single tick of the event loop and fetches them in one batch query, reducing the database load significantly.
One system design question a day, with spaced repetition so the ones you miss come back.
Get the appRelated questions
- You're designing a REST API for a blog. Which endpoint best represents 'get all comments for post 123'?
- A client wants to update only the 'status' field of an order, leaving other fields unchanged. Which HTTP method is most appropriate?
- A client calls POST /users with valid data, and the user is created. What status code should the server return?
- A client retries a failed 'POST /payments' request due to network timeout. The server receives the request twice. Without idempotency handling, what can happen?
- An API returns 10,000 products. Returning all in one response is impractical. Which pagination approach is simple and stateless?
- Your API serves both mobile apps and third-party integrations. Which authentication method is most appropriate?