# CQRS: Split the Code That Changes Data From the Code That Reads It

> CQRS gives writes and reads their own models, and sometimes their own data stores, so each can be designed and scaled alone. The cost is that reads can lag behind writes.

**In short:** CQRS gives the code that changes data and the code that reads it separate models, and sometimes separate data stores, so each can be designed and scaled alone.

From "System design", a free course by Venkat R. Murty: https://designervenkat.online/learn/system-design/cqrs

## What You Will Learn

This lesson teaches CQRS, which stands for Command Query Responsibility Segregation. The name is long, but the idea is short: a system can use one model to change information and a different model to read it. Martin Fowler, who writes about software design, says he first heard the idea from Greg Young, and he places the core of the pattern in that split between updating and reading.

By the end you should be able to say what a command and a query are, explain why a team might split them, name the main cost of the split, and spot the cases where the split is not worth doing.

- **CQRS:** Command Query Responsibility Segregation. A design where writes and reads use separate models, and sometimes separate data stores.
- **Command:** A request that changes saved data, such as placing an order. It usually returns little or nothing.
- **Query:** A request that asks for data and never changes it, such as loading an order history page.
- **Model:** The shape a team gives its data and the code that works with that data.
- **Write model:** The side that handles commands. It checks rules and saves changes.
- **Read model:** The side that handles queries. It is arranged so screens can load quickly.
- **Data store:** Any place where a system keeps its data, such as a database.
- **CRUD:** Create, Read, Update, Delete. The simple style where one model handles every kind of data action.
- **Business rule:** A rule the product must follow, such as stock never going below zero.
- **Stale data:** Information that was correct a little while ago but has since changed.
- **Eventual consistency:** A state where copies of data agree after a short delay, not at the same instant.

## What Is the Core Split?

Most small apps use one model for everything. They save a record and load the same record for a screen. This is the CRUD style. Fowler points out that as needs grow, a single model can become a poor fit for both jobs, because the same model has to do too much.

CQRS answers that problem by splitting the model in two. The idea goes back to a simpler rule called command-query separation. Wikipedia describes it as a method that should either perform an action or return data, but not both. CQRS applies that same rule at the level of whole services and data models.

### What Are Commands and Queries?

- **Commands change state:** A command asks the system to change something, such as adding a product to a cart or placing an order. State means the facts the system stores right now, such as how many mugs are left. A command should change that state and return little or nothing. Command names should describe a business task, like Place order, rather than a raw field edit.
- **Queries only read:** A query asks for data and leaves it alone. Opening a product list or an order history page is a query. The answer can be shaped for the screen, but running the query does not modify system state, aside from exceptions such as logging access.
- **Each side has its own model:** The write side holds the rules and the saving logic. The read side holds data arranged for quick screens. Sometimes each side even uses its own data store, which is the place where its copy of the data lives.

**Quick check:** A school app lets teachers enter grades. Parents open a page that shows each child's grades and average. When a teacher presses Save grade, the app first checks that the grade is between 0 and 100, then stores it. Which part of the app should handle the Save grade button?

A. The read model, because grades are shown to parents there
B. The write model, because saving a change after a rule check is a command
C. A query, because it sends the saved grade back to the teacher's screen
D. No part, because a page that only displays data never needs a model

**Answer:** B. Saving a change after checking a rule is a command. Commands belong to the write side, which enforces the rules. Parents only read, so their page uses the read side.

## Why Split Reads and Writes?

Reads and writes often look very different in a real system. They have different shapes, different loads, and different goals. Microsoft's guide says that a single model does not take this difference into account, and that read and write operations often need different performance and scaling. Fowler notes that if an application sees a big disparity between reads and writes, separating the load is very handy, and that CQRS can also help without that disparity.

- **Different shapes:** A write may only need the few fields that a rule checks. A screen may need data gathered from many tables at once. Forcing one model to serve both makes it awkward for each job.
- **Different loads:** Reads often arrive in far larger numbers than writes. CQRS lets a team add capacity to the busier side without changing the other side, so each side scales on its own.
- **Different goals:** The write side protects correctness with business rules. The read side protects speed, so it can keep data arranged for quick screens, with facts stored together that would otherwise need to be combined on each visit.

The benefit is real, but it has to be weighed. Fowler says the gain from CQRS must be balanced against the extra complexity of keeping two models. A team that gains little from separate models will pay for the split without much return.

## What Is the Cost of Separate Models?

The biggest trade-off appears when the read side is updated after the write side. Once a write is saved, the read side needs time to learn about it. Older Microsoft writing treats displayed data as always a little out of date, and CQRS accepts that fact rather than hiding it.

This is where the idea of eventual consistency matters. A system that uses it accepts that copies will agree after a short delay. The lesson on eventual consistency covers that idea in full. Here, the point is simple: a shopper may see an old stock count for a moment after someone else buys the last item.

- **Stale reads:** A user can save a change and then see the old value on a read screen for a brief time. Fowler's description of the flow says the change is routed to the separate command model for processing, and the resulting change is then communicated to the query model to render the updated state.
- **Extra parts:** A CQRS system has two models, a way to pass changes from one side to the other, and code to handle a change that arrives twice or late.
- **Harder reasoning:** Developers must keep in mind that the screen may lag. Debugging a bug where a page shows old data takes more effort than in one shared model.

Fowler is blunt about the risk. He warns that for most systems CQRS adds risky complexity, so it should be used only when the benefit is clear.

> **Tip:** Try CQRS on one busy area first, such as a product catalog or ticket browsing, and not on the whole app. Keep simple forms on one shared model. You can always split a part later if the need appears.

## Worked Example: An Online Store

Imagine an online store with a product page. The page has two buttons, Add to cart and Place order. The store also has two read screens: a product listing and an order history. The listing and history screens read from a separate read store, which is prepared ahead of time so that each screen loads fast. Follow one order through the system.

1. **Add to cart is a command:** Pressing Add to cart sends a command that adds one item to the shopper's cart. The command changes state, so it goes to the write side. It does not send back a product list.
2. **Place order checks the rules:** Pressing Place order sends a second command to the write model. The write model checks that stock is still available and that the price is current. If a check fails, the order is refused with a clear message.
3. **The write store saves the order:** When every check passes, the write model saves the order in its own store. It then announces that an order happened, so the other side can catch up.
4. **The read store catches up:** Moments later, the read store is updated. The stock count on the listing is lowered, and the new order is added to the history view. The read store holds data arranged for these screens, so the update is a simple copy.
5. **Screens only query:** When a shopper opens the listing or the order history, the page sends queries to the read store only. Those queries never run the business rules, and they never change stored data.

In this example, the shopper who just placed an order might briefly see the old stock count on the listing. That short gap is the trade-off described earlier. In exchange, checks stay strict on the write side, and the busy listing pages can be scaled on their own.

## The Split in Miniature

The next sample is a tiny version of the same idea. The write side changes a stock count and returns nothing. The read side only builds text from a copy of the data. The copy is refreshed only when we ask, which shows the delay in a simple way.

```python
# Write side: commands change stock and return nothing
stock = {"mug": 5}
read_view = {"mug": 5}

def place_order(item, qty):
    if stock.get(item, 0) < qty:
        raise ValueError("not enough stock")
    stock[item] -= qty

def refresh_read_view():
    read_view.update(stock)

# Read side: queries only build text and never change data
def show_listing(item):
    return item + ": " + str(read_view[item]) + " left"

place_order("mug", 2)
print(show_listing("mug"))
refresh_read_view()
print(show_listing("mug"))

```

Output:

```text
mug: 5 left
mug: 3 left

```

The first print shows the old count, because the read copy has not caught up yet. After the refresh, the second print shows the new count. This is a small model of eventual consistency. In a real system, the refresh would be triggered by an event or message, not by a call in the same program.

## When Should You Not Use CQRS?

CQRS is not a default choice. Fowler says many systems fit the CRUD style well and should be built that way. He also calls CQRS a significant mental leap, so the team should only take it on when the benefit is worth the effort.

- **Simple data apps:** A contact form, a notes app, or a small blog works well with one model. Splitting it would add parts and bugs without solving a real problem.
- **Small teams:** A team that is still learning its domain may struggle to keep two models in step. Simpler code is easier to change while the rules are still unclear.
- **Screens that must be exact:** If every read must show the latest write at once, the delay of separate stores is a poor fit. A single store that is always current may be safer for that part of the system.

## Test Your Understanding

Now try a larger case. Read it carefully, because it includes two different kinds of work.

**Quick check:** A ticketing site has 500 times more people browsing events than buying tickets. The browse pages need data joined from many tables. Buying a ticket needs strict checks so that one seat is never sold twice. Should the team use CQRS, and what should each side hold?

A. No. One shared model is always simpler, so keep browsing and buying in one store with the same code.
B. Yes. Put browsing on a read store shaped for the event pages, and put buying on a write model that checks seat availability strictly before saving.
C. Yes, but put both browsing and buying on the write model so that seat counts are always exact.
D. No. A read store can never be updated after a purchase, so the split cannot work here.

**Answer:** B. Browsing is a heavy read load with joined data, so a read store shaped for it fits. Buying changes state and needs strict rules, so it belongs on the write side. The brief delay on browse pages is acceptable, but a double sale is not.

To sum up, CQRS separates commands that change data from queries that read it. Each side can have its own model, and sometimes its own store, so each can be designed and scaled alone. The price is that reads may lag behind writes, and the design adds parts that must be kept in step. Use it where the split clearly helps, and keep simple parts of the system on one model.

## Sources

- [Microsoft Learn, Azure Architecture Center: CQRS pattern](https://learn.microsoft.com/en-us/azure/architecture/patterns/cqrs)
- [Martin Fowler, bliki: CQRS](https://martinfowler.com/bliki/CQRS.html)
- [Martin Fowler, What do you mean by Event-Driven?](https://martinfowler.com/articles/201701-event-driven.html)
- [Wikipedia: Command Query Responsibility Segregation](https://en.wikipedia.org/wiki/Command_Query_Responsibility_Segregation)
- [Wikipedia: Command-query separation](https://en.wikipedia.org/wiki/Command%E2%80%93query_separation)
- [Microsoft MSDN Magazine: CQRS on Microsoft Azure](https://learn.microsoft.com/en-us/archive/msdn-magazine/2011/april/azure-development-cqrs-on-microsoft-azure)
