Skip to Content
Course content

135: N+1 Query Detection with Bullet

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

If you've been building Rails apps for a while, you've probably felt that moment where a page just... drags. You look at the logs, and you see a wall of identical-looking SQL queries scrolling past your terminal. You've just hit the N+1 query problem. It's a classic. I've seen it bring down production environments that were otherwise perfectly tuned, simply because a developer added one small line to a view that triggered a hundred extra database calls.

The "Invisible" Performance Leak

Let's look at a common scenario. Imagine we're building a blogging platform. We have Post models, and each post has many Comment models. In our index view, we want to show the title of the post and the username of the person who wrote the most recent comment.

# Controller
def index
  @posts = Post.limit(10)
end

# View (ERB)
<% @posts.each do |post| %>
  <p><%= post.title %> - Latest comment by: <%= post.comments.last>.user.name </%p>
<% end %>

On the surface, this looks fine. But look closer at what's happening in the background. First, Rails hits the database once to get the 10 posts. Then, for each of those 10 posts, it fires a query to find the last comment, and then another query to find the user associated with that comment. That's 1 query for the posts, plus 20 more for the associations. That's 21 queries to render 10 rows of data. If you increase that limit to 50, you're suddenly hitting the DB 101 times. Your database is spending more time negotiating connections than actually returning data.

Fixing the Leak with Eager Loading

The fix is includes. By telling Rails exactly what we need upfront, we can collapse those dozens of queries into just a few efficient ones. I usually tell my juniors to think of it as "shopping with a list" instead of walking back and forth to the store for every single ingredient.

# Controller
def index
  @posts = Post.includes(comments: :user).limit(10)
end

Now, Rails will load the posts, then load all the related comments and users in one or two bulk queries. The total query count drops from 21 down to 3, regardless of whether you're displaying 10 posts or 100. The trade-off is a slightly larger memory footprint in Ruby because you're loading more objects into RAM at once, but in 99% of web cases, the database round-trip is the real bottleneck, not the RAM.

Letting Bullet Do the Heavy Lifting

Here is the problem: in your development environment, you might only have three posts. Three posts mean seven queries, which happens so fast you'll never notice it. You push to production, the site hits a real dataset, and suddenly the app crawls to a halt. You can't rely on your eyes to catch this.

That's where the bullet gem comes in. I consider it a non-negotiable part of my development stack. Instead of you having to manually audit every single controller action, Bullet monitors your queries in real-time. When it detects an N+1, it doesn't just log it—it screams at you. Depending on your config, it'll throw a JavaScript alert in your browser or a notification in your OS tray saying, "N+1 Query detected: Add to eager loading: Post.includes(:comments)."

But Bullet isn't just for finding missing includes. It also catches "unused eager loading." If you're using .includes(:comments) but you never actually call post.comments in your view, you're wasting memory and database resources. Bullet will nudge you to remove those unnecessary loads, keeping your controllers lean. It effectively turns a silent performance killer into a loud, fixable bug.




📋 Practical Task

Exercise: Silencing the Bullet in the Project Dashboard

You are working on a Project Management app. The DashboardController#index action loads a list of Project records. Each project belongs_to :client and has_many :tasks.

Currently, the view iterates through the projects and displays the Client's name and the total count of tasks for that project. After installing the bullet gem, you see the following alert in your browser:

N+1 Query detected: Project.includes(:client)

Your task: Modify the Project.all call in the DashboardController to eager load both the client and the tasks to eliminate the N+1 queries and satisfy the Bullet gem's requirements.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.