0
0
Flaskframework~8 mins

Lazy loading vs eager loading in Flask - Performance Comparison

Choose your learning style9 modes available
Performance: Lazy loading vs eager loading
MEDIUM IMPACT
This concept affects how quickly data is fetched and rendered on the page, impacting initial load time and responsiveness.
Fetching related database records in a Flask app using SQLAlchemy
Flask
from sqlalchemy.orm import joinedload
posts = Post.query.options(joinedload(Post.author)).all()
for post in posts:
    print(post.author.name)
This loads posts and their authors in a single query, reducing database calls and speeding up rendering.
📈 Performance Gainsingle database query regardless of number of posts, reducing load time significantly
Fetching related database records in a Flask app using SQLAlchemy
Flask
posts = Post.query.all()
for post in posts:
    print(post.author.name)
This triggers a separate database query for each post's author (N+1 query problem), slowing down page load.
📉 Performance Costtriggers N+1 database queries, increasing load time linearly with number of posts
Performance Comparison
PatternDatabase QueriesInitial Load TimeNetwork OverheadVerdict
Lazy LoadingMultiple (N+1 queries)Lower if few accessedLower initially, higher if accessed later[!] OK
Eager LoadingSingle batched queryHigher upfrontHigher upfront, lower later[OK] Good
Rendering Pipeline
Lazy loading delays fetching related data until it is accessed, reducing initial data processing. Eager loading fetches all related data upfront, increasing initial processing but reducing later delays.
Data Fetching
Template Rendering
Network Requests
⚠️ BottleneckData Fetching stage due to multiple database queries in lazy loading
Core Web Vital Affected
LCP
This concept affects how quickly data is fetched and rendered on the page, impacting initial load time and responsiveness.
Optimization Tips
1Avoid lazy loading if it causes many database queries on page load.
2Use eager loading to fetch related data in one query for faster initial rendering.
3Balance eager and lazy loading based on data size and user interaction patterns.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance problem with lazy loading in database queries?
AIt loads all data upfront causing slow start
BIt blocks rendering completely
CIt causes many small queries increasing load time
DIt increases bundle size
DevTools: Network
How to check: Open DevTools > Network tab, reload page, and observe number of database API calls or data fetch requests.
What to look for: Multiple small requests indicate lazy loading with many queries; a single larger request indicates eager loading.