0
0
Expressframework~8 mins

Associations (hasMany, belongsTo) in Express - Performance & Optimization

Choose your learning style9 modes available
Performance: Associations (hasMany, belongsTo)
MEDIUM IMPACT
This affects how many database queries and data processing happen during page load and user interactions.
Fetching related data for a list of items with associations
Express
const posts = await Post.findAll({ include: [{ model: User, as: 'author' }] });
res.json(posts);
This fetches posts and their authors in a single query using JOIN, reducing database calls drastically.
📈 Performance GainSingle database query regardless of number of posts, reducing response time and server load.
Fetching related data for a list of items with associations
Express
const posts = await Post.findAll();
for (const post of posts) {
  post.author = await User.findByPk(post.userId);
}
res.json(posts);
This triggers one query for posts plus one query per post to get the author, causing many database calls.
📉 Performance CostTriggers N+1 database queries where N is number of posts, increasing response time linearly.
Performance Comparison
PatternDatabase QueriesResponse TimeServer LoadVerdict
Lazy loading associations (N+1 queries)N+1 queriesHighHigh[X] Bad
Eager loading associations (single query)1 queryLowLow[OK] Good
Rendering Pipeline
Associations affect the server response time which impacts when the browser can start rendering content. More queries mean slower data delivery.
Data Fetching
Server Response
Initial Render
⚠️ BottleneckData Fetching due to multiple database queries
Core Web Vital Affected
INP
This affects how many database queries and data processing happen during page load and user interactions.
Optimization Tips
1Avoid fetching associated data inside loops to prevent many database queries.
2Use eager loading (hasMany, belongsTo with include) to fetch related data in one query.
3Reducing database queries improves server response time and user interaction speed.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance problem with fetching associated data inside a loop?
AIt improves caching automatically.
BIt reduces server memory usage.
CIt causes many database queries, slowing response time.
DIt speeds up rendering on the client.
DevTools: Network
How to check: Open DevTools, go to Network tab, observe API calls and their timing when loading data with associations.
What to look for: Look for multiple API calls or long response times indicating many database queries or slow data fetching.