0
0
NestJSframework~8 mins

Relations in Prisma in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Relations in Prisma
MEDIUM IMPACT
This affects database query speed and server response time when fetching related data.
Fetching related data with Prisma relations
NestJS
const users = await prisma.user.findMany({ include: { posts: true } });
Fetches users and their posts in a single query, reducing database calls.
📈 Performance GainSingle database query regardless of number of users, greatly improving response time.
Fetching related data with Prisma relations
NestJS
const users = await prisma.user.findMany();
for (const user of users) {
  user.posts = await prisma.post.findMany({ where: { authorId: user.id } });
}
This triggers one query per user, causing many database calls and slow response.
📉 Performance CostTriggers N database queries for N users, increasing server response time linearly.
Performance Comparison
PatternDatabase QueriesServer Response TimeClient ImpactVerdict
N+1 Query PatternN+1 queriesHigh latencySlow interaction response[X] Bad
Single Query with include1 queryLow latencyFast interaction response[OK] Good
Rendering Pipeline
Relations in Prisma affect the server-side data fetching stage before rendering. Efficient queries reduce server processing time and speed up data delivery to the frontend.
Data Fetching
Server Response
Client Rendering
⚠️ BottleneckMultiple database queries increase server response time and delay rendering.
Core Web Vital Affected
INP
This affects database query speed and server response time when fetching related data.
Optimization Tips
1Avoid fetching related data inside loops to prevent many database queries.
2Use Prisma's include or select to fetch relations in a single query.
3Reducing database queries improves server response and user interaction speed.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance issue with fetching related data in a loop with Prisma?
AIt causes many database queries, increasing server response time.
BIt reduces database queries to one, improving speed.
CIt caches data on the client side automatically.
DIt improves browser rendering speed.
DevTools: Network
How to check: Open DevTools, go to Network tab, filter XHR requests, and observe the number of API calls made when loading related data.
What to look for: Multiple repeated API calls indicate N+1 query problem; a single call with all data is optimal.