Video

The N+1 Query Problem, Explained in 30 Seconds

Your Rails page looks fine. It's quietly running eleven queries.

THE SETUP
You load 10 posts, then display each post's author:

posts = Post.limit(10)
posts.each { |post| puts post.author.name }

That's 1 query for the posts, then one more for every post's author.
1 + N. The N+1 problem.

WHY IT HURTS
It isn't just "more SQL." Every query is a round trip to the database, and
that overhead is paid per record. Ten posts is survivable. A page that grows
to 200 rows is not — the cost scales with your data, which is why N+1 usually
ships fine and degrades later.

THE FIX — eager loading

posts = Post.includes(:author).limit(10)
posts.each { |post| puts post.author.name }

Active Record loads all the authors up front instead of one at a time:
one query for the posts, one for the authors.

A caveat worth keeping: eager loading does not always produce exactly two
queries. The actual SQL depends on the association, the query, and your
Rails version — `includes` may use a separate preload query or switch to a
JOIN when you reference the association in a `where`. And not every extra
query is an N+1; the signature is one query repeating per record.

HOW TO SPOT IT
Watch your development log for the same query repeating with different ids.
The bullet gem flags them automatically.

—
#Astmation — #software #systems , #automation , and #AI-powered #applications .
Build. Automate. Evolve.
https://astmation.com/

#Shorts #RubyOnRails #Rails #ActiveRecord #NPlusOne #BackendDevelopment #Performance #SQL #WebDevelopment #SoftwareEngineering


Watch on YouTube

Back to videos