user449689
user449689

Reputation: 3154

Event sourcing: in-memory read model, does it make sense to apply events during read?

I'm working on an application that uses event sourcing for storing data. For many reasons a persisted read model is not used, therefore we need to implement an in-memory read approach.

The idea is that some data from an aggregate should be read with the current date, but also with past dates. Therefore the approach I'm thinking is to process all the events of that aggregate and Apply the event in the aggregate in order to have the state at the specified date.

But, I'm reading in various articles that the Apply method should only be used when the command is emittend and not during the reading phase.

Does it make sense to use the Apply method during the reading phase? Or maybe the same logic should be replicated in a different method (some sort of processor)?

I'm not posting any code here because what I'm looking for is to understand what the right approach should be and to understand better how to user Event Sourcing.

Upvotes: 1

Views: 806

Answers (2)

Constantin Galbenu
Constantin Galbenu

Reputation: 17683

Reading the internal and private state of an aggregate should be avoided as it break it's encapsulation. Also, an Aggregate stores whatever state it needs in order to check for its invariants and querying that state would force the Aggregate to maintain additional state that it is not needed.

In conclusion, avoid reading the write side.

Upvotes: 3

Eben Roux
Eben Roux

Reputation: 13246

I don't think that it is necessarily the case that the Apply method may only be called when emitting events. If the purpose of the Apply method is to load the event into the aggregate then it will be invoked when restoring the aggregate to its current state.

It seems as though you need processing for your aggregate that would represent it for some window period (start/end date). It may be more appropriate to create a read model that represents the bits that you are interested in and store them as time-sensitive data and then rather query that.

If the processing is too intensive you may even want to issue a command that requests a report or view of sorts but that would still work through the time-sensitive read model and then produces the required output. Once done the user can be notified that the results are ready for perusal.

As @Constantin Galbenu stated: you should avoid your aggregate's internal state and this ties in with not querying your domain model.

Upvotes: 1

Related Questions