0
0
Ruby on Railsframework~8 mins

Database query optimization in Ruby on Rails - Performance & Optimization

Choose your learning style9 modes available
Performance: Database query optimization
HIGH IMPACT
This affects how fast the page loads data from the database and how quickly the server responds to user requests.
Fetching related records in a Rails app
Ruby on Rails
posts = Post.includes(:comments).all
posts.each do |post|
  puts post.comments.size
end
Loads all comments in one query, avoiding multiple database hits.
📈 Performance Gainreduces queries from N+1 to 2, significantly lowering server response time
Fetching related records in a Rails app
Ruby on Rails
posts = Post.all
posts.each do |post|
  puts post.comments.count
end
This triggers a separate database query for each post to count comments, causing many queries.
📉 Performance Costtriggers N+1 queries where N is number of posts, increasing server response time
Performance Comparison
PatternDatabase QueriesData TransferredServer Response TimeVerdict
N+1 queriesMany small queries (N+1)More data due to repeated queriesHigh due to multiple DB hits[X] Bad
Eager loading with includesFew queries (usually 2)Less repeated dataLower due to fewer DB hits[OK] Good
Selecting all columnsSingle queryLarge data sizeMedium due to data size[!] OK
Selecting needed columnsSingle queryMinimal data sizeLow due to less data[OK] Good
Unindexed where clauseSingle queryDepends on dataHigh due to full table scan[X] Bad
Indexed where clauseSingle queryDepends on dataLow due to index use[OK] Good
Rendering Pipeline
Database query optimization reduces server processing time before HTML is sent to the browser, improving the critical rendering path by delivering data faster.
Server Processing
Network Transfer
First Contentful Paint
⚠️ BottleneckServer Processing due to slow or excessive database queries
Core Web Vital Affected
LCP
This affects how fast the page loads data from the database and how quickly the server responds to user requests.
Optimization Tips
1Avoid N+1 queries by using eager loading (includes).
2Select only the columns you need to reduce data size.
3Add indexes on columns used frequently in filters.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance problem with N+1 queries in Rails?
AIt triggers many database queries, slowing server response
BIt loads too many columns in one query
CIt causes layout shifts in the browser
DIt increases CSS selector complexity
DevTools: Network and Performance panels
How to check: Open DevTools, go to Network tab, reload page and check time for API/database calls; use Performance tab to record and analyze server response times.
What to look for: Look for long waiting times on database calls and multiple repeated requests indicating N+1 queries.