0
0
Ruby on Railsframework~8 mins

Eager loading (N+1 prevention) in Ruby on Rails - Performance & Optimization

Choose your learning style9 modes available
Performance: Eager loading (N+1 prevention)
HIGH IMPACT
This concept affects database query efficiency and page load speed by reducing the number of queries needed to fetch related data.
Loading a list of posts with their authors
Ruby on Rails
posts = Post.includes(:author).all
posts.each do |post|
  puts post.author.name
end
Eager loading fetches posts and their authors in two queries regardless of number of posts, reducing database hits.
📈 Performance GainTriggers only 2 database queries, significantly reducing load time and server work.
Loading a list of posts with their authors
Ruby on Rails
posts = Post.all
posts.each do |post|
  puts post.author.name
end
This triggers one query for posts plus one query per post to fetch the author, causing many database hits (N+1 queries).
📉 Performance CostTriggers 1 + N database queries, increasing page load time and server load.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
N+1 queries (lazy loading)NormalMultiple due to delayed dataHigher due to slower data[X] Bad
Eager loading with includesNormalSingle or fewerLower due to faster data[OK] Good
Rendering Pipeline
Eager loading reduces the number of database queries, which speeds up data retrieval before rendering. This leads to faster style calculation and layout since data is ready sooner.
Data Fetching
Layout
Paint
⚠️ BottleneckData Fetching (database queries)
Core Web Vital Affected
LCP
This concept affects database query efficiency and page load speed by reducing the number of queries needed to fetch related data.
Optimization Tips
1Avoid N+1 queries by using eager loading with includes or preload.
2Batch related data fetching to reduce database round trips.
3Monitor database queries in DevTools Network tab to detect N+1 issues.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance problem caused by N+1 queries?
AMany small database queries increasing load time
BToo much CSS causing slow paint
CLarge JavaScript bundles blocking rendering
DExcessive DOM nodes causing reflows
DevTools: Network
How to check: Open DevTools, go to Network tab, filter by XHR or fetch, reload page, count number of API/database calls made.
What to look for: Look for multiple repeated queries fetching related data separately (bad) versus fewer batched queries (good).