Search code examples
aggregatedomain-driven-designddd-repositories

How to avoid N+1 problem with DDD aggregate relations?


I’ve read an article from Vaughn Vernon where he states that aggregates should only reference each other by identity.

Lets say i have aggregate A which has a reference to the identity of aggregate B. I’d like to display a list containing aggregate A with some columns from aggregate B in my UI.

That would mean i have to query aggregate A first, then i’d have to query aggregate B with the reference from aggregate A.

This seems to be a N+1 problem, how could i solve this while respecting the “reference by identity” rule?


Solution

  • You should not query your domain objects since they typically don't lend themselves to querying. The domain is more concerned with the command / transactional side of things where you create and write away data.

    On the other hand querying / reporting is more concerned with reading data. To this end you can develop a light-weight query mechanism that is as close as is feasible to the data layer you are using. As such you return rather raw data or read models (DTOs) along with whatever joining and data aggregation you need.