Skip to Content
Course content

189: N+1 Prevention in GraphQL with Batch Loading

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Why does GraphQL make N+1 problems so much worse than a standard Rails controller?

In a typical REST API, you're the boss. You write a controller action, you call Post.includes(:author).all, and you send back a JSON blob. You know exactly what data the client is getting, so you can optimize the query right there in the controller.

GraphQL flips the script. The client decides what they want. If a client asks for 20 posts and includes the author field for each, the GraphQL engine executes the author resolver for every single post. If you're just calling object.author inside that resolver, you've just triggered 21 queries (1 for the posts, 20 for the authors). I've seen this crash production environments because a frontend developer decided to nest three levels deep in a query without realizing they were triggering hundreds of database hits.

Can't I just use .includes in the top-level resolver?

You can, but it's a game of whack-a-mole. To do that, you'd have to inspect the lookahead (the AST of the incoming query) to see if the client even asked for the author. If they did, you add the include. But what happens when they ask for author { profile { settings } }? Now you're writing complex logic to dynamically build an includes array based on the query depth.

It's brittle and honestly, it's a waste of your time. Instead of trying to predict the future at the start of the request, we use batch loading. This allows the resolver to say, "I don't have this author yet, but please put this ID on a list and let me know when you've gathered all the IDs from the other posts."

How do I actually implement the batch-loader gem in a resolver?

The batch-loader gem is the industry standard here because it's lightweight and doesn't force you into a specific architecture. Instead of returning the author object immediately, you return a "promise" (a loader object). When GraphQL finishes traversing the tree, the gem executes the batch block once.

Here is how I usually set this up for a PostType:

def author
  BatchLoader::GraphQL.for(object.author_id).batch do |author_ids, loader|
    # author_ids is an array of all author_ids collected across all Post objects
    Author.where(id: author_ids).each do |author|
      loader.call(author.id, author)
    end
  end
end

Notice that we aren't calling Author.find(object.author_id). We're using Author.where(id: author_ids). This turns those 20 separate queries into one single SELECT * FROM authors WHERE id IN (...) query. It's a massive performance win.

Does this mean I have to wrap every single association in a batch loader?

Technically, yes, if you want to be completely safe from N+1s. But practically? Use your judgment. If a field is rarely queried or you know the dataset is tiny, you might not notice the hit. However, for any "has_many" or "belongs_to" relationship that's likely to be used in a list, I always use a batch loader. It's a habit that saves you from 3 AM wake-up calls when the database CPU spikes to 100% because someone wrote a recursive query.

One tip: if you find yourself repeating this pattern everywhere, I recommend moving the batch loading logic into a separate AuthorLoader class or a service object so your Types files don't become bloated with database logic.




📋 Practical Task

Fixing the Book-to-Author N+1 Leak

You've been handed a GraphQL schema for a library app. The BookType currently has a resolver that triggers an N+1 query every time a list of books is requested with their authors.

Your Task: Rewrite the author resolver in the code below to use the batch-loader gem. Ensure that you collect the author_ids and perform a single Author.where query to resolve the authors for the entire batch.

class Types::BookType < Types::BaseObject
  field :id, ID, null: false
  field :title, String, null: false
  field :author, Types::AuthorType, null: false

  def author
    # CURRENT LEAKY IMPLEMENTATION:
    # This hits the DB for every single book in the list.
    Author.find(object.author_id)
  end
end

Implement the fix using BatchLoader::GraphQL.for(...) and the .batch block.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.