Chapter 12. Command-Query Responsibility Segregation (CQRS)

In this chapter, we’re going to start with a fairly uncontroversial insight: reads (queries) and writes (commands) are different, so they should be treated differently (or have their responsibilities segregated, if you will). Then we’re going to push that insight as far as we can.

If you’re anything like Harry, this will all seem extreme at first, but hopefully we can make the argument that it’s not totally unreasonable.

Figure 12-1 shows where we might end up.

Tip

The code for this chapter is in the chapter_12_cqrs branch on GitHub.

git clone https://github.com/cosmicpython/code.git
cd code
git checkout chapter_12_cqrs
# or to code along, checkout the previous chapter:
git checkout chapter_11_external_events

First, though, why bother?

apwp 1201
Figure 12-1. Separating reads from writes

Domain Models Are for Writing

We’ve spent a lot of time in this book talking about how to build software that enforces the rules of our domain. These rules, or constraints, will be different for every application, and they make up the interesting core of our systems.

In this book, we’ve set explicit constraints like “You can’t allocate more stock than is available,” as well as implicit constraints like “Each order line is allocated to a single batch.”

We wrote down these rules as unit tests at the beginning of the book:

Our basic domain tests ...

Get Architecture Patterns with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.