N+1 Queries or Memory Problems: Why not Solve Both?

submited by
Style Pass
2024-10-14 13:00:02

❶ Author of How to Open Source (.dev). A book to take you from coder to contributor. ❷ Creator of CodeTriage, a free service helping developers contribute to open source. ❸ Core committer to ruby/ruby. ❹ Married to Ruby, literally.

This post is going to help save you money if you’re running a Rails server. It starts like this: you write an app. Let’s say you’re building the next hyper-targeted blogging platform for medium length posts. When you login, you see a paginated list of all of the articles you’ve written. You have a Post model and maybe for to do tags, you have a Tag model, and for comments, you have a Comment model. You write your view so that it renders the posts:

See any problems with this? We have to make a single query to return all the posts - that’s where the @posts comes from. Say that there are N posts returned. In the code above, as the view iterates over each post, it has to calculate post.comments.count - but that in turn needs another database query. This is the N+1 query problem - our initial single query (the 1 in N+1) returns something (of size N) that we iterate over and perform yet another database query on (N of them).

If you’ve been around the Rails track long enough you’ve probably run into the above scenario before. If you run a Google search, the answer is very simple – “use includes”. The code looks like this:

Leave a Comment