Event Sourcing – Cross-Context Aggregate in Domain-Driven Design

cqrsdomain-driven-designevent-sourcing

I had this idea of different write models being used in different bounded contexts, but both being the same aggregate instance (the same events).

For example consider a User aggregate that is used in Administration and User contexts (that is the admin and the user-interface parts of the application). And the domain model says that the user (in User context) cannot do any action on itself (change email, change password, change address, whatever) unless he is logged in (which is the only action he is permitted to do if hes not logged in).

In administration context, however, the action does not need that user to be logged in (basically, an admin can change user's details on his behalf).

Can this be modeled with Event Sourcing as a single aggregate instance (same ID), but depending on the context a different object model would be built from the events? i.e. in admin context, the model does not verify the user is logged in, but in user context, the model does. This way the events would be shared between the contexts.

Is this a good idea? I can smell some issues but I am not completely sure.

Best Answer

I had this idea of different write models being used in different bounded contexts, but both being the same aggregate instance (the same events).

That strikes me as a bad idea; very much at contradiction with best practices.

The aggregate really needs to have one source of truth. In an event sourced implementation, that's really the history of the aggregate. The consistency of that history is guarded by the aggregate itself. If you have two different implementations of the aggregate (two different collections of business rules - which permit different states), then you are opening yourself up to a real mess when one implementation leaves the history in a state that the other is supposed to prevent.

Two different applications could (potentially) share the same domain model though. In your case, that could mean that one of the contexts permits the command when the other would forbid it.

However, in the original blue book, a bounded context is a boundary beyond which a model may not apply, where the ubiquitous language changes, and so on. If the words used to describe the business no longer mean the same thing, then sharing the same aggregates seems unwise.

See also: With all of these services, how can I not be anemic?

Note that there is absolutely nothing wrong with two different projections reading their state from the same history. The User context could have one view of the history, where the Administration context has a completely different view of that same history.