简体   繁体   中英

CQRS: Read model projection update in an API

I would like to have a simple CQRS implementation on an API. In short:

  1. Separate routes for Command and Query.
  2. Separate DB tables (on the same DB at the moment). Normalized one for Command and a de-normalized one for Query.
  3. Asynchronous event-driven update of Query Read Model, using existing external Event Bus.

After the Command is executed, naturally I need to raise an event and pass it to the Event Bus. Event Bus would process the event and pass it to it's subscriber(s). In this case the subscriber is Read Model which needs to be updated.

So I need a callback route on the API which gets the event from Command Bus and updated the Read Model projection (ie: updating the de-normalized DB table which is used for Queries).

The problem is that the update of the Read Model projection is neither a Command (we do not execute any Domain Logic) nor a Query.

The questions is: How should this async Read Model update work in order to be compliant both with CQRS and DDD?

How should this async Read Model update work in order to be compliant both with CQRS and DDD?

I normally think of the flow of information as a triangle.

  • We copy information from the outside world into our "write model", via commands
  • We copy information from the write model into our "read model"
  • We copy information from the read model to the outside world, via queries.

Common language for that middle step is "projection".

So the projection (typically) runs asynchronously, querying the "write model" and updating the "read model".

In the architecture you outlined, it would be the projection that is subscribed to the bus. When the bus signals that the write model has changed, we wake up the projection, and let it run so that it can update the read model.

(Note the flow of information - the signal we get from the bus triggers the projection to run, but the projection copies data from the write model, not from the event bus message. This isn't the only way to arrange things, but it is simple, and therefore easy to reason about when things start going pear shaped.)

It is often the case that the projection will store some of its own metadata when it updates the read model, so as to not repeat work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM