Home > Back-end >  In CQRS with multiple databases, should I call database functions inside Command or inside repositor
In CQRS with multiple databases, should I call database functions inside Command or inside repositor

Time:09-15

I'm using cqrs pattern with multiples databases (one for query and another for search). Should I put the insert inside Repository

CommunityRepository{
     Add(Community community){
       Database1.Insert(community);
       Database2.Insert(community);
    }
 }

and then:

 CommunityCommands{
    Handler(AddCommunityCommand community){
         communityRepository.Add(community);
    }

or should i put this in Commands, like this:

 CommunityCommands{
    Handler(AddCommunityCommand community){
         db1.Insert(community);
         db2.Insert(community);
    }

or maybe something like this, using the main repository database2

 CommunityCommands{
    Handler(AddCommunityCommand community){
         communityRepository.Add(community);
         db2.Insert(community);
    }

CodePudding user response:

I would do neither of those options as you'd be basically coupling the Command and Query immplementations.

Instead, publish events from the Command side, like OrderPlacedEvent and subscribe to them from the Query side. This not only allows you to separate the implementations of the Command and Query sides, but it will also allow you to implement other side effects of the events without coupling the code from the multiple features (eg. "when an order is placed, send a confirmation email").

You can implement the pub/sub synchronously (in process) or asynchronously (with a messaging system). If you use messaging, note that you'll have to deal with eventual consistency (the read data is slightly behind the write data, but eventually it catches up).

CodePudding user response:

refreshing the Query Models should be handled in an offline operation. You should do something like this:

  • process your Command logic (whatever it is)
  • right before your Command handler returns, send an Event to a message bus

then in a background service you can listen to those Events and update the Query side.

Bonus tip: you can use the Outbox pattern to get more reliability. The idea is to store the Event messages in a table on your Write DB in the same transaction as your previous write operation, instead of sending them directly. A background service would check for "pending" messages and dispatch them. The rest is unchanged.

  • Related