What exactly happens when a command handler calls AggregateLifecycle.apply(event) inside an aggregate?
Calling apply() does two distinct things in the same call. First, it publishes the event outward into the rest of the system — it gets durably stored and becomes available to any other component that's listening for it, such as a projection updating a read model. Second, it immediately routes that same event back to this aggregate instance's own matching @EventSourcingHandler method, updating the instance's in-memory fields right away, before the command handler method even returns. That second effect is what lets the aggregate keep its own state correct for the very next command that might arrive in quick succession, without needing to reload from anywhere in between. It also means any actual state change in an aggregate should only ever happen inside an event sourcing handler reacting to an applied event, never as a direct field assignment sitting inside the command handler itself.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response