0
0
NestJSframework~8 mins

Relations (OneToMany, ManyToOne, ManyToMany) in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Relations (OneToMany, ManyToOne, ManyToMany)
MEDIUM IMPACT
This affects database query performance and server response time, impacting how fast data loads and updates in the app.
Fetching related data with relations in NestJS using TypeORM
NestJS
const users = await userRepository.find({ relations: ['posts'] });
Fetches users and their posts in a single query using JOIN, reducing database calls.
📈 Performance GainSingle query regardless of number of users, greatly reducing response time.
Fetching related data with relations in NestJS using TypeORM
NestJS
const users = await userRepository.find();
for (const user of users) {
  user.posts = await postRepository.find({ where: { user: { id: user.id } } });
}
This triggers a separate database query for each user to get posts, causing many queries (N+1 problem).
📉 Performance CostTriggers N+1 queries, increasing server response time linearly with number of users.
Performance Comparison
PatternDatabase QueriesQuery CountResponse Time ImpactVerdict
N+1 Query PatternMultiple separate queriesN+1 queriesHigh response time, slower LCP[X] Bad
Eager Loading RelationsSingle joined query1 queryLow response time, faster LCP[OK] Good
ManyToMany without indexesJoin queries on large tables1 queryPotentially slow if unindexed[!] OK
ManyToMany with indexed join tableOptimized join query1 queryFast response, scalable[OK] Good
Rendering Pipeline
Relations affect server-side data fetching before rendering. Efficient queries reduce server response time, improving initial content paint.
Data Fetching
Server Response
Initial Render
⚠️ BottleneckDatabase query time due to inefficient relation loading
Core Web Vital Affected
LCP
This affects database query performance and server response time, impacting how fast data loads and updates in the app.
Optimization Tips
1Avoid N+1 query problem by using eager loading relations.
2Use explicit join tables with indexes for ManyToMany relations.
3Fetch related data in as few queries as possible to reduce server response time.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance problem with fetching related data in a loop without using relations?
AIt reduces the number of queries, speeding up response
BIt causes many database queries, slowing down response time
CIt caches data automatically, improving performance
DIt compresses data to reduce network size
DevTools: Network and Performance panels
How to check: Open DevTools, go to Network tab, filter XHR requests, observe API calls for data fetching. Use Performance tab to record page load and check server response times.
What to look for: Look for multiple API calls fetching related data separately (bad). Single API call with joined data (good). Faster server response times improve LCP.