I'm writing an app based on event sourcing and CQRS principles. The app is basically a "transaction tracker" and to exemplify the problem we can think that each Transaction
is linked to an Asset
.
class Asset(models.Model):
code = models.CharField(...)
current_price = models.DecimalField(...)
sector = models.CharField(...)
...
def get_roi(self, percentage: bool = False) -> Decimal:
# Expensive calculation using several joins in multiple tables
return self.transactions.roi(incomes=self.incomes.sum(), percentage=percentage)["ROI"]
class Transaction(models.Model):
asset = models.ForeignKey(to=Asset, on_delete=models.CASCADE, related_name="transactions")
...
class Income(models.Model):
asset = models.ForeignKey(to=Asset, on_delete=models.CASCADE, related_name="incomes")
...
My list endpoints for the assets has several fields that are costly to calculate in a normalized DB. Those fields changes if:
- a
Transaction
is created or deleted - an
Income
is created or deleted current_price
changes
In order to scale and for several other reasons that you probably already know I want to separate those computational-costly fields from the write model. My questioning arises from the fact that a read model would have to have some fields that will probably never change and that has no relation with the events above.
For example, I have a report that aggregates the ROI
s per sector
. With a read model I must have a sector
field to generate this report. If so, I'd have to sync the read model every time that sector
changes as well.
As I have several fields like this, it's just easier to also trigger the read model update if the given write Asset
is touched (created, updated or deleted). This looks both odd and some sort of overkill at the same time to me. The main reason for this thought it's that changing a "report field" has nothing to do with the Asset
aggregate domain and its business rules.
With all that being said, one alternative that came to my mind was to simply extend the write model with the denormalized fields. Doing so raises some red flags besides also looking odd to me.
What would you say it's the best approach here?