CQRS in Java Microservices

Using Event Sourcing to implement CQRS

Randal Kamradt Sr
Javarevisited

--

Nuerons
Image by Gerd Altmann from Pixabay

Command Query Responsibility Separation (CQRS) is a pattern in service architecture. It is a separation of concerns, that is, separation of services that write from services that read. Why would you want to separate read and write services? One of the advantages of microservices is the ability to scale services independently. We can often say with some level of certainty that one set of services will be busier than others. If they are separate, they can be scaled to best fit the normal use case and conserve cloud cycles.

I will be looking into CQRS provided by the Axon library. Axon implements CQRS with event sourcing. The idea behind event sourcing is that your commands are executed by sending events to all subscribers. Instead of storing state in your persistence store, you store the immutable events, so you always have a record of the events that led up to a particular state.

Inside your program, you will have an aggregate, which represents a stateful object but is ephemeral in that the system can bring it in and out of existence as needed. You will also have projections, which are the data that is ready for your read service. The projections are updated via the events, the same as the aggregate. One advantage of that is that the projections can take a different shape than the…

--

--