0
0
Flaskframework~8 mins

Repository pattern for data access in Flask - Performance & Optimization

Choose your learning style9 modes available
Performance: Repository pattern for data access
MEDIUM IMPACT
This pattern affects how data is fetched and managed, impacting server response time and client perceived loading speed.
Fetching user data multiple times in different parts of the app
Flask
class UserRepository:
    def __init__(self):
        self.cache = {}

    def get_user(self, user_id):
        if user_id not in self.cache:
            self.cache[user_id] = User.query.filter_by(id=user_id).first()
        return self.cache[user_id]

class UserService:
    def __init__(self, repo):
        self.repo = repo

    def get_user_name(self, user_id):
        return self.repo.get_user(user_id).name

    def get_user_email(self, user_id):
        return self.repo.get_user(user_id).email
Caches user data on first fetch, avoiding repeated database queries and reducing server load.
📈 Performance GainSingle database query per user, reducing server response time and improving LCP.
Fetching user data multiple times in different parts of the app
Flask
class UserService:
    def get_user_name(self, user_id):
        return User.query.filter_by(id=user_id).first().name

    def get_user_email(self, user_id):
        return User.query.filter_by(id=user_id).first().email
Multiple queries to the database for the same user cause repeated database hits and slow response.
📉 Performance CostTriggers multiple database queries, increasing server response time and delaying LCP.
Performance Comparison
PatternDatabase QueriesServer Response TimeClient Load ImpactVerdict
Direct multiple queriesMultiple per userHighSlower LCP[X] Bad
Repository with cachingSingle per userLowFaster LCP[OK] Good
Rendering Pipeline
The repository pattern reduces redundant data fetching, which lowers server processing time and speeds up sending data to the client, improving the critical rendering path.
Server Processing
Network Transfer
Client Rendering
⚠️ BottleneckServer Processing due to multiple database queries
Core Web Vital Affected
LCP
This pattern affects how data is fetched and managed, impacting server response time and client perceived loading speed.
Optimization Tips
1Cache data in the repository to avoid repeated database queries.
2Minimize server processing time to improve LCP.
3Use repository pattern to centralize and optimize data access.
Performance Quiz - 3 Questions
Test your performance knowledge
How does using a repository pattern with caching affect database queries?
AReduces repeated queries by caching data
BIncreases the number of queries
CHas no effect on queries
DMakes queries slower
DevTools: Network
How to check: Open DevTools, go to Network tab, reload the page, and observe the number and timing of API calls fetching data.
What to look for: Look for repeated API calls fetching the same data; fewer calls indicate better repository caching.