Add Module 2: Database Telemetry & Latency Attribution with N+1 Query Problem Demo #7
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Pull Request: Module 2 - Database Telemetry & Latency Attribution
Title
Description
Summary
This PR adds Module 2: Database Telemetry & Latency Attribution, building on Module 1 to demonstrate database instrumentation and the identification/resolution of the N+1 query problem—the most common performance bug in modern applications.
🎯 What's New
Database Integration:
N+1 Problem Demonstration:
New Endpoints:
GET /users/analytics- Naive implementation (N+1 problem)GET /users/analytics/optimized- Optimized implementation (JOIN)📦 Implementation Breakdown
Phase 1: Persistence Layer Integration
Database Schema:
Instrumentation:
logfire.instrument_sqlalchemy(engine)after Logfire configSeed Data:
user_01throughuser_20)Phase 2: Naive Implementation (The Trap)
Endpoint:
GET /users/analyticsThe Problem:
Performance Metrics:
Educational Value:
Phase 3: Optimized Implementation
Endpoint:
GET /users/analytics/optimizedThe Solution:
Performance Metrics:
Improvement:
🧪 Test Results
Side-by-Side Comparison
Naive Endpoint:
{ "implementation": "naive", "warning": "This endpoint uses N+1 queries - check traces!", "total_users": 20, "users": [ {"id": 1, "username": "user_01", "email": "user01@example.com", "order_count": 3}, ... ] }Optimized Endpoint:
{ "implementation": "optimized", "info": "This endpoint uses a single efficient query", "total_users": 20, "users": [ {"id": 1, "username": "user_01", "email": "user01@example.com", "order_count": 3}, ... ] }Result: Identical data, vastly different performance!
📊 Performance Comparison
With 1000 users:
📁 Files Changed
New Files
Modified Files
Total Changes: 6 files, 1,371 insertions, 141 deletions
🎓 Learning Objectives Demonstrated
1. N+1 Query Problem
Definition: Making N+1 database queries when 1 would suffice
How to Identify:
How to Fix:
joinedload()orselectinload()2. Latency Attribution
Question: Is the app slow or is the database slow?
Naive Answer (from traces):
Conclusion: Database is the bottleneck!
Optimized Answer (from traces):
Conclusion: Well balanced!
3. Database Instrumentation
Automatic Capture:
Zero Code Changes for basic instrumentation!
4. Query Parameter Sanitization
Security Feature: Parameters are replaced with
?in tracesExample in Trace:
Why: Prevents sensitive data (emails, passwords, PII) from appearing in logs
5. Trace Analysis
Skills Taught:
📖 Documentation
MODULE2.md (Comprehensive Guide)
Contents:
Length: 650+ lines of detailed documentation
README.md (Updated)
Now Includes:
🔍 Code Quality
Database Module (
database.py)Main Application (
main.py)Depends(get_db)Documentation
✅ Testing Checklist
🚀 Usage
Start the Application
cd observability-lab pip install -r requirements.txt python main.pyTest Both Implementations
Compare in Logfire Dashboard
logfire authpython main.py🎯 Key Takeaways
For Junior Engineers
For Mid-Level Engineers
For Senior Engineers
🔗 Related Documentation
Test Plan
To verify this PR:
Install and run:
cd observability-lab pip install -r requirements.txt python main.pyTest naive endpoint:
Test optimized endpoint:
Verify performance difference:
time curl ...ls -lh observability_lab.db(Optional) View in Logfire:
Summary
This PR demonstrates production-ready database instrumentation and teaches the critical skill of identifying and fixing the N+1 query problem—a fundamental capability for any backend engineer.
The implementation includes:
This module makes the N+1 problem unforgettable by showing it visually in traces—once you see it, you'll spot it everywhere!