Skip to content

Avoiding N+1 Queries ​

An N+1 query is one query for a list, then one more query for each item in it. A page of 20 posts that loads each post's comments separately runs 21 queries; with 100 posts, 101. Each query is fast on its own, but the round trips add up, and the page gets slower as the data grows.

Runcobo has no lazy associations, so it never runs a hidden query for you. An N+1 is always visible in your code — a store call inside a loop or a template:

crystal
posts = store.list_posts(row_limit: 20, row_offset: 0)
posts.map do |post|
  comments = store.list_comments_for_post(post_id: post.id)   # ❌ one query per post
  {id: post.id, title: post.title, comments: comments.size}
end

The same applies to templates: a store call inside a Jbuilder array! block or a Water each loop runs once per item.

There are two fixes. Pick by what you need from the related rows.

Need a number or a few columns? JOIN ​

When you need an aggregate — a count, a sum, the latest date — or a few columns of a parent row, compute it in SQL:

db/queries/posts.sql
sql
-- name: ListRecentPostsWithCommentCounts :many
SELECT posts.id, posts.title, posts.created_at, count(comments.id) AS comments_count
FROM posts
LEFT JOIN comments ON comments.post_id = posts.id
GROUP BY posts.id
ORDER BY posts.id DESC
LIMIT sqlc.arg(row_limit);
crystal
posts = store.list_recent_posts_with_comment_counts(row_limit: 20)
posts.each { |post| post.comments_count }   # an Int64, already loaded

One query, whatever the number of posts. Use LEFT JOIN so posts without comments still appear, with a count of 0.

When you need the related rows themselves, load them for the whole list at once, then group them in Crystal:

db/queries/comments.sql
sql
-- name: ListCommentsForPosts :many
SELECT id, post_id, author, body, created_at FROM comments
WHERE post_id = ANY(sqlc.arg(post_ids)::bigint[])
ORDER BY id;
crystal
posts = store.list_posts(row_limit: 20, row_offset: 0)
comments = store.list_comments_for_posts(post_ids: posts.map(&.id.as(Int64?))).group_by(&.post_id)

posts.each do |post|
  comments[post.id]? || [] of Blog::Store::ListCommentsForPostsRow   # this post's comments
end

Two queries, whatever the number of posts — what Active Record calls eager loading. For another level (each comment's author), repeat the pattern: collect the IDs from the comments and load the authors in one more query.

MySQL and SQLite

ANY(array) is PostgreSQL. On MySQL and SQLite, write WHERE post_id IN (sqlc.slice('post_ids')). The generated method takes an array, but raises ArgumentError for an empty one, so skip the call when the page is empty. See the crsql query guide.

Prove it with a spec ​

The generated store reports every query it runs to an observer. Attach one in a spec and assert the exact list, so an N+1 fails the build instead of slowing production:

spec/posts_spec.cr
crystal
it "loads the comments of a page with a fixed number of queries" do
  3.times do |i|
    post = TEST_STORE.create_post(title: "Post #{i}", body: "...")
    TEST_STORE.create_comment?(post_id: post.id, author: "Ada", body: "Nice")
  end
  queries = [] of String
  store = TEST_STORE.with_observer(->(event : Blog::Store::QueryEvent) { queries << event.query_name; nil })

  dispatch("GET", "/posts", handler: Blog::RouteHandler.new(store)).status_code.should eq(200)

  queries.should eq(["ListPosts", "CountPosts", "ListCommentsForPosts"])
end

Create at least two or three rows: with one, an N+1 looks the same as a batch.

The same observer can log slow queries in production — see the crsql production guide.

Checklist ​

  • No store call inside a loop, a map, or a template's array!/each block.
  • Counts and sums come from SQL (count, sum, GROUP BY), not from loading rows to call .size.
  • Related rows are loaded with one ANY(...) query per level and grouped with group_by.
  • Each list endpoint has a spec that checks its queries.

The blog example uses both fixes.

Released under the MIT License.