Saga that relies on a projection

Hi all,

I’m new to Axon and to CQRS in general. CQRS looks like a good fit for some things at work so I’m putting together a prototype to illustrate Axon working with our business domains.

I have an aggregate root which raises an event, and a saga which listens for that event and will start when that event occurs, in the normal way.

The saga needs to read some data from a projection, but that projection is also maintained by processing which listens for the same event from the aggregate root.

(Stop me here please if I’m already doing something crazy!)

First off I implemented two event listeners for the event from the aggregate root - one to update the projection and another to kick off the saga. But I can’t guarantee what order the event listeners will fire in (can I?) and so there’s the possibility that the saga will start before the projection has been updated, and so the saga will see out-of-date data, which would be bad.

Then I reduced down to one event listener - just the saga - and had the saga maintain the projection itself. But that means that the projection cannot be recreated by replaying events, as to do so would have the saga go on to do other things which have side-effects.

Am I missing some trick about how to wire together events, sagas, and project-maintainers? Should I do something like have the event pass through the entire internal state of the aggregate instead?

Thanks in advance for help and happy to clarify anything that isn’t clear from my description.

Many thanks,

Renny

Hi Renny,

having a Saga depending on a projection can be ok in certain situations. You will have to be able to rely on the “correctness” of the projection, however. If it is a projection maintained by another application or from another bounded context, it is probably better to rely on a query than to listen to all events from that context. The latter would create too tight coupling.

If both the projection and the saga that relies on the projection are created from the same events, I would separate them entirely. Have the saga maintain whatever is important from the events it receives and build the projection on the side. Ultimately, this will create the best scalable solution. Guaranteeing ordering is technically possible, but something you would rarely want to do. There is no “switch” in Axon to do so; you’d have to use a Cluster implementation that forwards events to listeners in a specific order. As you remarked, this kills the possibility to replay events.

Hope this helps.
Cheers,

Allard

Thanks - that helped me think things through.