How does the command handler internally work?

Hello,

I was curious to know how the command handler internally works.
Say we have Axon with Event Sourcing.

When someone want to send a command, we first need to validate the invariance inside the aggregate.

To do this, axon has to reconstruct (rehydration) the aggregate based on the events in the event store. But while it reads those events, maybe other services are putting more records in the event store. How does it handle this concurrency issue? (In my opinion - and maybe it’s wrong - when it is reconstructing the aggregate

Also, what happens when a command is dispatched?

  • The event is written on event store, and then put in the message broker
  • The event i’s written on the message broker, and then put in the event store

Thanks a lot for the help!
FP

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