Search code examples
microservicescqrsevent-sourcing

How event sourcing and CQRS help in decoupling microservices?


How do event sourcing and CQRS help to achieve decoupled architecture for microservices.

We can have microservices which own their data and others accessing that data via service even by having traditional means of persistence. Isn't?


Solution

  • Event sourcing and CQRS are not intended to be used to decouple services.

    The main goal achived by using CQRS is to improve the performance of a service because you can use different persistence type for writes (command) and for reads (query).

    Thanks to that, you can use a higly performance write type persistence like event log to store all events that happen in the service and use a relational model for example for reads where you store the information in the way that you need for your queries.

    The way to achieve consistency between the two models is normally by using events generated by the command model that are consumed by the query to update the read model. The drawback of this appproach is the eventual consistency, because the update of the read model does not happen inmediately.

    Higly related with cqrs is event sourcing that states that all modifications in the model should be stored like events in an event store. This way you have an historic of all the actions made in the application. The advantage of this is that you have an historic of all changes for audit purposes and that writes are extremely fast. The drawback is that if you want to get the current state you have to replay all the events since the begining.

    To solve this, you use cqrs to get the actual state to make queries