I have a spring boot application where i want to implement a saga pattern. Let’s suppose i am sending a #CreateOrderCommand, then in the @CommandHandler before firing an #OrderCreatedEvent is it ok to inject a service which saves the order on the database and then emits the event so the saga listener can handle it ? I am reading various posts around the internet where they just emit an #OrderCreatedEvent and then they handle the event on a separate @EventHandler. It seems a bit confusing to my eyes, to emit an #OrderCreatedEvent without creating the order. Am i missing something or my assumption is correct?
First and foremost, welcome to the forum, @Alekos_argyriou
Now, on to your question.
I am going to assume that this is one of your earliest event-driven applications, @Alekos_argyriou, based on your question. From that point of view, I fully comprehend that it “feels” roundabout to separate the updating of a projection from the process/saga you’re invoking, based on an event that is published.
However, by separating the concern of "updating a database’ and “starting a saga,” you can optimize for each use case. While, if you lump them together, you are required to choose which task is more important.
Furthermore, separating them based on the events allows you to break these components into separate services as well. So, microservices. Although you may not need this right away, having the ability to separate these processes in the future is very powerful. It gives you a level of flexibility you wouldn’t get when the actual implementation (so, the classes), are “mixed.”
There is one more point to stress here. Specifically, why the event is published first, and the processes come next. When going for an Event Sourced system, you essentially choose that the events are:
- The source of truth of all changes in your system
Hence, you have a single data store that defines what happened. Any other model, process, or projection that’s based on this, can thus be recreated based on your single source of truth.
That’s what I wanted to share about the “message-driven architecture” you’d be going for when using Axon Framework. I hope this clarifies things for you, @Alekos_argyriou! And if not, be sure to ask follow-up questions.
Thanks for your explanation, a very detailed one, covered all of my inquiries.
That’s great to hear, @Alekos_argyriou! I’ve marked my reply as the ‘solution’ to your question as a response to this. If that’s incorrect, feel free to adjust it.
And, if you have any further questions in the future, you know where to reach us!