0

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 ROIs 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?

1 Answer 1

0

In general, the biggest benefit of CQRS is that you can optimize the write-side for exactly what you need in order to validate commands and optimize the read-sides for exactly what you need for efficient querying (almost always at the cost of introducing a consistency delay).

It's also important to note that the aggregate concept from DDD is really only applicable to the write-side: the read-side doesn't intrinsically have to respect aggregate boundaries.

So if something like "change the sector of this asset", the question to ask is, "how would this command change the response to future commands". If there's some command against an asset that would depend on that command, then that's a strong sign that the command (and thus the associated validations, like "an asset can only ever be in one sector") are part of the aggregate's business rules so the associated fields should be part of that aggregate.

But if changing an asset's sector has no effect beyond that report, and you're willing to tolerate potentially observable periods of inconsistency (e.g. if a company relists from the London to the New York exchange, so you move it from the "European durable-goods manufacturing sector" to "US durable-goods manufacturing sector", there may be a period where if you query the read-model it's in both sectors or neither of them), you can have a sector aggregate which is basically tracking a collection (a set basically) of asset IDs and emits "asset added to sector"/"asset deleted from sector". The read-sides which are interested in these can then subscribe to those events. Then you can normalize or denormalize based on requirements in the read model.

4
  • The aggregate is well established and changing the sector has no impact at all on it. The only "use case" is when an user accidentally inputs the wrong value and then has to correct it. The thing is that if I denormalize my data to another dedicated table then when the Asset's metadata (one of many field such as sector) change I have to emit an event like AssetUpdated in order to update the read model and consequently the reports. While if I denormalize in the same table I don't have to emit anything - which kinda makes more sense since it's not part of the aggregate. Mar 21 at 22:46
  • Please, note that I didn't mention "periods of inconsistency" because this is kind implicit in the CQRS strategy so yes I do tolerate such periods. Mar 21 at 22:48
  • Nonetheless, I'm more inclined towards the separation because it'll be easier to scale and it also makes more sense to me to have this explicit separation of contexts. For instance, if we decided to go full into the denormalization in a NoSQL database then it'll be much easier. Mar 21 at 22:52
  • If changing the sector has no impact on the Asset aggregate, then it shouldn't be part of that aggregate at all (because there's no consistency requirement with any other operation on the aggregate), so changing the sector doesn't change the asset (it will just eventually change some read model which is effectively joining the events for the Sector aggregate and the Asset aggregate). Mar 22 at 0:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.