
Catching N+1 Queries With strict_loading in Rails
So everybody has heard about includes, we also, and anyway the N+1 comes back each time somebody puts one more name into a partial, that is why we made on Rails 8.1 and Postgres a toy with 200 posts which have authors, and went to see what exactly strict_loading catches and what it lets go.
First without any protection, 20 posts, author name for each, and the log counted 21 queries, with includes it is 2, and on all 200 posts it was 22.4 ms against 2.4 on the same laptop, so nine times slower, only who will feel it in development where the table has five rows? Then we hung strict_loading on it, error at once, StrictLoadingViolationError, and same error for author company when only author was in includes.
posts = Post.strict_loading.limit(20)
posts.each { |post| post.author.name }
# ActiveRecord::StrictLoadingViolationError
posts = Post.strict_loading.includes(:author).limit(20)
user = User.find(params[:id])
user.strict_loading!(mode: :n_plus_one_only)
user.posts.each { |post| post.title } # allowed
user.posts.each { |post| post.comments.to_a } # raises
After this we were feeling safe, too early. We wrote Comment.where post_id inside the loop and counted, 21 queries, strict loading said nothing at all. Worse was the next one, we preloaded comments and then called comments.where published true, 22 queries! Preload was done and thrown away, and no error, because calling a scope on the association is a new query and not a loading what strict is watching.
posts.each { |post| Comment.where(post_id: post.id).count }
posts.each { |post| post.comments.published.to_a }
What saved us there, has_many published_comments with own condition, preload that, 2 queries again, so now we don't believe strict alone, it sleeps sometimes.
has_many :published_comments, -> { where(published: true) }, class_name: "Comment"
config.active_record.action_on_strict_loading_violation = :log
test "the project list does not grow queries with rows" do
sign_in users(:owner)
small = count_queries { get projects_path }
10.times { |i| Project.create!(name: "P#{i}", client: clients(:acme)) }
large = count_queries { get projects_path }
assert_equal small, large
end
def count_queries(&block)
count = 0
counter = lambda do |*, payload|
count += 1 unless payload[:cached] || payload[:name] == "SCHEMA"
end
ActiveSupport::Notifications.subscribed(counter, "sql.active_record", &block)
count
end
See also: Active Record patterns and keeping a suite fast.