Johnny.sh

CQRS

CQRS stands for Command Query Responsibility Segregation. This is a software design pattern that I first saw when I was doing some work for Nike. In my experience, it is used for asynchronous APIs, for flattening out heavy loads into asynchronous processing.

The Concept

Command Query Responsibility Segregation is a pattern in which two distinct models (in the sense of an MVC model) are used for write and read operations. This is in contrast with a traditional CRUD pattern, in which the same model has separate methods for writing (create, update) and reading (read).

In CQRS, we’d break a traditonal CRUD model into two “models” — one for writing, and one for reading. This allows better separation of responsibility, and allows for each individual model to be considered its own distinct domain, even. For example, reading models from a database has a whole set of concerns and logic, purely around the querying of data of a certain model. There might be 1000 lines of code purely for querying Product from a database. This doesn’t need to be mixed in with create Product logic. At the same time, there might be a bunch of operations that need to happen when we create Product, totally outside the concern of end users querying products.

This seperation allows us to be better set up for handling heavy loads, asynchronous processing, or for abstracting into an event-driven system.

In Practice

Using Product from above, we would have a ProductCommand model and a ProductQuery model. Additionally, we’d probably have a ProductWorker

The ProductCommand model would probably dispatch events, which would be handled by the ProductWorker. The ProductQuery model would be purely for querying products out of a shared DB.

Last modified: August 15, 2021
/about
/uses
/notes
/talks
/projects
/podcasts
/reading-list
© 2022