Hi Federico,
The concern you’re placing, the one that several domain events can be inserted for a given aggregate, is tackled internally by the LockingRepository
.
What Axon does if you publish a command on the CommandBus/CommandGateway, is that it will either create a new instance or load an aggregate from the aggregate Repository
. In the scenario you sketch, this is an EventSourcingRepository
. In between the Repository
interface and the EventSourcingRepository
implementation sits the LockingRepository
which places a lock on the Aggregate being loaded.
As such, multiple threads within a single application cannot load the Aggregate at the same point and thus you cannot concurrently insert events for a given Aggregate.
In a multi node set up this of course could still occur. What an Axon application does on inserting an Event in the EventStore, is that it is assigned an unique global index. If another event is being inserted with an identical global index, Axon will throw a ConcurrencyException
stating the given event ‘was already inserted’.
If this occurs, you’ve typically not correctly set the Routing Strategy of commands in your distributed set up (although that’s a story for a different day I think).
For your second question, your first scenario fits, although there are some other intricacies in place.
When you publish an Event from an Aggregate, first all the @EventSourcingHandlers
for that given event contained within your Aggregate and its Entities. Second, the event will be saved in the prepare commit phase of the [UnitOfWork](https://docs.axonframework.org/v/3.1/part-i-getting-started/messaging-concepts#unit-of-work)
(read: stored in the EventStore).
After that, any SubscribingEventProcessors will receive the event from the EventBus (I wouldn’t state ‘message broker’ as the right term within Axon for this component, as messages might be commands, events or queries). Additionally, any TrackingEventProcessor in your application will be able to pull the event from the EventStore themselves, as it has been stored.
Hope this gives you some insight Federico!
Cheers,
Steven