Working with Domain Driven Design
with Mongodb
and an external service. Let's say we have two services Service A (for aggregate A)
and Service B for aggregate B
. Whenever an Aggregate A
is created, a corresponding Aggregate B
is also created. This is done synchronously via an API call
to ensure real-time operations. In case the creation of Aggregate B
fails, the creation of Aggregate A
needs to be rolled back.
The Domain Event Aggregate_A_Created
is fired once the Aggregate A
is stored in DB (handled via ORM). Before the Aggregate B
is created.
The problem I face is quite simple, if the Aggregate A
was created, the event is fired but if the Aggregate B
creation fails, the Aggregate A
is deleted from the database but the Domain Event was fired that already signifies that Aggregate_A_Created
. This might lead the system into an invalid state where other services think that Aggregate A
exists but in reality it fails.
I can fire another event Aggregate_A_deleted
but what if a service receives the Deleted
event before the Created
event?
I am stuck here, some insights would be great. Can I change the Spring Implementation to fire the domain event only when both operations have succeeded? I read that Spring Mongodb doesn't support Transactional calls
If Aggregate A and Aggregate B cannot be separated, should they not be parts of a common aggregate root?
If they are really separate, B should listen to A being created and only acknowledge that event, if B creation succeeds. This way - provided that you have persistent events - a B will be created even if the system goes down after A has been created and gets restored to that state.
Regarding transactions: as mongodb itself can handle transactions, don't let your choice of libraries limit you. If spring cannot do it, use the driver directly.