by BehindJava
What is CQRS Pattern in Microservices
In this tutorial, we are going to learn about CQRS Pattern in Microservices.
CQRS Pattern in Microservices
- CQRS stands for command query responsibility segregation.
- Since each microservice has its own database. The microservices don’t have access to the database of other microservices, and it is not possible to run a SQL query across multiple tables in multiple domains across different microservices.
- Now to support and fix this problem the microservice that needs to run the SQL query maintains a view of the data it needs to execute the query.
- So it has a table or a database that includes data from other microservices that is needed in order to run our SQL query on it.
- Now to generate the table or view of the database up to date. Microservices subscribes to domain events via event streaming.
- In an event driven design, microservices raise events and publish them to an event streaming platform. Such as Kafka.
- When the events are received the database gets updated.
In this example, we have order, kitchen, delivery, and accounting microservices.
- Now we want to have history of all the orders.
- So Order History Service subscribes to the events generated by ordering kitchen delivery and accounting microservices.
- And then when the events are received, it generates order history view database and then puts their information in that database.
- Now, if you want to run SQL queries. Such as find order or find order history, the order history service simply queries that database to retrieve the data.