Understanding Cartesian Product Explosion
You'll learn how eagerly loading multiple collections can create unexpectedly massive result sets and how to prevent this from crippling your application.
What Is Cartesian Product Explosion?
When you eagerly load multiple collections from related tables, your ORM often generates a JOIN query. If you JOIN across several one-to-many relationships simultaneously, you get a cartesian product — every row from one collection is paired with every row from another collection, multiplying the result set size dramatically.
Imagine an Author with 10 Books and each Book has 5 Reviews. If you eagerly load both collections in a single query, you don't get 15 rows (10 + 5). You get 50 rows (10 × 5) — one for each possible Book-Review pair, even though they belong to the same Author. With three collections, it becomes even worse: 10 × 5 × 8 = 400 rows.
The Problem in Practice
Author JOIN Books JOIN Reviews
Author data repeated 50 times in memory
Book data repeated 5 times each
Enormous network payload and memory usage
Your database sends redundant data across the wire, your ORM must reassemble duplicated parent objects, and both memory and processing time explode.
Strategies to Avoid Explosion
Use separate queries: Instead of one giant JOIN, issue multiple focused queries (one per collection). Modern ORMs can batch these efficiently.
Limit eager loading scope: Only eagerly load what you truly need. Don't load every collection "just in case."
Paginate collections: Apply limits to child collections to bound the result set size.
Consider lazy loading selectively: For some collections, lazy loading might be preferable to cartesian explosion.
Key Takeaway: Eagerly loading multiple collections in one query creates cartesian products that multiply rows exponentially; use separate queries or selective loading to maintain performance.