What is the N+1 Problem?
The N+1 problem is a performance issue where 1 main query triggers N additional queries.Problem Example
- 100 users = 101 queries
- 1000 users = 1001 queries
- Accumulated network round-trip time
- Increased database load
Sonamu’s Solution
Sonamu automatically solves the N+1 problem through Subsets.1. Define Subset
Define a Subset in the Entity:2. Use Subset
- Fetch users (1 query)
- Fetch all orders with user IDs in batch (1 query)
- Join in memory
Subset Usage Patterns
Single Relation
Multiple Relations
Nested Relations
Manual Solution with whereIn
When Subsets are not available, you can optimize with whereIn:DataLoader Pattern
Use the DataLoader pattern when repeated queries are needed:Practical Examples
API Endpoint Optimization
Dashboard Data
Detecting N+1
Query Logging
Detection with Tests
Performance Comparison
With N+1 Problem
Optimized with Subset
Best Practices
1. Always Consider Subset First
2. Define Necessary Subsets for API Responses
3. Consider JOIN for Complex Queries
4. Monitor Queries During Development
Checklist
To prevent N+1 problems:- Avoid DB queries inside loops
- Pre-load relation data with Subset
- Use whereIn for bulk queries
- Use JOIN for aggregations
- Enable query logging during development
- Verify query count with tests
- Monitor API response times