Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading data from database on Write Side in CQRS

Background :

Diagrams explaining CQRS usually will have clear separation of read and write paths and one-way data flow, like in this example (source : Demystified CQRS) : enter image description here

Question :

I would like to clarify,

If a Command execution in back-end requires some data from the database,

  • should a "write side" have some read capabilities from write database?
  • or it should completely rely on "read side" for any reads?
  • or perhaps command should contain all the required data supplied by caller to be fulfilled?
like image 856
Edgars Pivovarenoks Avatar asked Jan 05 '17 09:01

Edgars Pivovarenoks


1 Answers

should a "write side" have some read capabilities from write database?

Probably -- the most straight forward way to load the entity that is going to be running the command is by reading its state from the "write database". For instance, in event sourced architectures, a command to update an event sourced entity is typically handled by loading the history of that entity from the write model, rehydrating the entity from that history, evaluating the command, and appending new changes to the history.

Reading state about entities that are not handling the command is a different matter -- the ddd vocabulary helps here; the state you are modifying belongs to exactly one aggregate, state that lives outside of the aggregate should be passed to the model, rather than fetched, whenever it is possible to do so.

That could mean that the remote client needs to provide the data, or it could mean that the application handling the command fetches the required read model and provides the answer. There are a number of different concerns which can drive the choice you make here

  • if the read model used by the client in producing the command is significantly different from the view used by the app in handling the command, then there is some risk.
  • keeping a stable API allows you the freedom to redesign the aggregate boundaries in your model without requiring that you update the clients).

So no one best answer, just trade offs between different concerns.

A recent example of the latter came up -- if your business model requires that some commands require the authority of a specific user, then we shouldn't be taking the commands from the client at face value; we need the application to verify the identity of the command issuer, and then passing a representation of that identity to the model so that it can determine what action to take.

like image 151
VoiceOfUnreason Avatar answered Sep 25 '22 01:09

VoiceOfUnreason