SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
  • Client-Server
  • Monolithic Architecture
  • Microservices
  • Serverless
  • Event-Driven Architecture
  • Peer-to-Peer (P2P)
  • Hexagonal Architecture
  • CQRS
  • Event Sourcing
  • Domain-Driven Design (DDD)
  • Layered (N-Tier) Architecture
  • Containers and Docker
  • Kubernetes Basics
  • Clean Architecture and Modular Monolith
  • Multi-Tenancy
  • Cloud Basics: Regions, Zones and Edge
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Architecture/Architectural Patterns

CQRS

Use one model to write data and a different one to read it.

⏱ 14 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

CQRS (Command Query Responsibility Segregation) means using one model to change data and a different model to read data.

  • A command changes something: "place order", "cancel order". It returns success or failure, not a big result.
  • A query only reads something: "show my orders". It never changes data.
  • The two sides can have different code, different shapes of data and even different databases, so each can be tuned and scaled on its own.
  • If the sides use separate stores, the read side is updated a little later. This is eventual consistency.

02Concept: What is it?

Most apps use one model for everything. The same Order object and the same tables serve the checkout screen (writes with strict rules) and the order history screen (reads that join many tables). These two jobs pull in different directions.

  • Writes need rules, validation, locks and a clean, normalised model so data stays correct.
  • Reads need speed and a shape that fits the screen, often a flat, ready-made view with data from many places.

CQRS grows from Bertrand Meyer's old rule CQS (Command Query Separation: a method either changes state or returns data, not both). Greg Young applied it at the level of the whole model and called it CQRS.

One model vs CQRS
One model
📱Client
↕reads and writes
🗄️One database
CQRS
✍️Commandchange
🔎Queryread
🗄️Write store
⇢⇣sync / events
📚Read store
With CQRS, commands go to the write model. Changes are copied to a read model that is shaped for queries.
🧠CQRS is a spectrum
You can start small: same database, but separate command code and query code. Go further with a separate read database only if you need it. Many teams stop at the first step.

03Real-Life Example

🍵The Restaurant: Kitchen and Menu Board
In a restaurant, taking an order and telling customers what is available are two different jobs. Waiters write orders in a strict form and send them to the kitchen. Customers do not read the kitchen's messy stock sheets. A menu board shows a simple, ready-made view: "Pasta: available". When the kitchen runs out of pasta, someone updates the board a minute later. For a short moment the board may be wrong, but it is fast to read and anyone can read it at the same time.
Restaurant
CQRS
A waiter writing an order
A command (change something)
The kitchen and its stock sheets
The write model and write store
The menu board
The read model, made for reading
Updating the board after the kitchen changes
A projection that syncs the read model
Board is a minute behind
Eventual consistency
Many diners read the board at once
Reads scale on their own
Asking 'what is on the menu?'
A query (changes nothing)
The life of one order
✍️CommandPlaceOrder
→↓
🧩Write modelcheck rules, save
⇢⇣event
🔄Projectionupdate the view
→↓
📚Read modelquery it

04Why Do We Need It?

⚡Fast reads
The read model is already shaped for the screen: no joins at request time.
📈Scale each side
Most apps read far more than they write. Add read replicas without touching writes.
🧠Simpler models
The write model only worries about rules. The read model only worries about display.
🎯Right database for each job
Writes in PostgreSQL, search views in Elasticsearch, counters in Redis.
🔐Different security
It is easy to give read-only access to some users and tools.
👥Team split
One team can work on commands while another builds new screens from views.
Reads and writes have different needs. Give each its own model, so neither slows the other.

05Where Do We Use It?

📊Read-heavy systems
Dashboards, catalogues and feeds where reads are 100 times more than writes.
🧮Complex rules
Domains with rich write rules (finance, bookings, insurance).
🔎Search screens
Writes go to a database and a copy goes to a search index for fast queries.
🧾With Event Sourcing
Events are the write side. Projections build the read side.
🧩Microservices
A service keeps its own write data and publishes events. Others build local read views.
🌍Multi-region reads
Read stores placed near users while writes stay in one place.
⚠️Not for every screen
A simple admin form that edits and shows one record does not need CQRS. Use it where the read and write needs are really different.

06Types / Parts / How It Works

Levels of CQRS

LevelWhat is separateConsistencyEffort
1. Code onlyCommand handlers and query handlers, same databaseImmediateLow
2. Different models, same databaseWrite tables and read views or materialized views in one databaseImmediate or near immediateMedium
3. Separate read storeRead model in another database, synced by events or change data captureEventualHigh
4. With Event SourcingWrite side stores events. Read side is built by projectionsEventualHighest
Level 3: a separate read store
✍️Commands
→↓
🗄️Write DBPostgreSQL
⇢⇣events
📨BrokerKafka, queue
→↓
🔄Projector
→↓
📚Read DBElastic, Redis
Write side Messaging Read side
A message broker carries the change events from the write side to the projection that updates the read store.

Commands vs queries

CommandQuery
PurposeChange stateRead state
Name styleVerb in the imperative: PlaceOrder, CancelBookingQuestion: GetOrderHistory, ListOpenTickets
ReturnsSuccess, failure, maybe an idData shaped for the screen
Side effectsYes, rules and eventsNone. Safe to repeat and cache
Can fail because ofRule broken, conflictNot found, no permission
VisualizerShare the load, then watch the read side lagRaise reads and compare one model with CQRS. Then place orders in CQRS mode and see that the read store is behind until the projection catches up.
Model
Single database (writes + reads with joins)145%
The one database needs 145% of its capacity. It is overloaded: reads and writes block each other.
Try the delay between the two sides
Database (used by both)
empty
Query result (same database)
empty
Orders written
0
Orders visible to readers
0
Lag
0
in sync
With one model a new order is visible straight away. Simple, but reads and writes share one design and one limit.

Simplified model: a write costs 5 units, a read 1 (x3 with joins in a single model), and one database handles 1000 units per second. Real numbers differ.

07How to Use It / Steps / Implementation

Introducing CQRS step by step

  1. 1
    Find the pain
    Look for slow reads that need heavy joins, or write code that is complicated by display needs. If there is none, do not start.
  2. 2
    Split the code first
    Create command handlers and query handlers. Queries must never change data. Keep one database at this stage.
  3. 3
    Shape the read model
    Build views or tables made for the screen, with the fields already joined and sorted as the UI needs.
  4. 4
    Publish changes
    When the write side changes, record an event (or use change data capture) that says what happened.
  5. 5
    Build projections
    A projector listens to the events and updates the read store. Make it idempotent, so the same event twice does no harm.
  6. 6
    Handle the delay
    After a command, return the new id or state. Let the UI show it right away, or wait until the view catches up.
  7. 7
    Monitor lag
    Measure the time between a write and its appearance in the read store. Add a way to rebuild a view from scratch.
💡Read your own writes
Users hate to save something and then not see it. Show the saved result from the command response, or read from the write side for that user for a few seconds.

08Key Terms to Know

TermMeaning in easy words
CommandA request to change something, with a clear business meaning
QueryA request to read data. It changes nothing
Write modelThe model with rules that decides what changes are allowed
Read modelA model or view shaped for fast display and search
ProjectionCode that builds or updates a read model from changes
Eventual consistencyThe read side catches up after a short delay
CQSCommand Query Separation: a method either changes or returns, not both
Command handlerCode that runs one command and applies the rules
Change data capture (CDC)Reading the database log to find out what changed
Idempotent projectionApplying the same event twice gives the same result
RebuildCreate the read model again by replaying history

09Pros, Cons and Trade-offs

✅ Pros
  • Reads and writes scale separately
  • Read views are fast and simple to query
  • Write rules stay clean and focused
  • Each side can use the best database for its job
  • Fits event-driven and event-sourced designs
⚠️ Cons
  • More parts: handlers, projections, extra stores
  • Eventual consistency confuses users and developers
  • Two models can drift apart if a projection has a bug
  • More to monitor and to test
  • Overkill for simple apps

Trade-offs

ChoiceWe gainWe lose
Separate read databaseFast, scalable reads in the right shapeDelay, extra storage and a sync pipeline
Same database, separate codeSimple and still consistentReads and writes still share hardware
Synchronous projectionRead is up to date immediatelySlower writes, tighter coupling
Asynchronous projectionFast writes, loose couplingReads can be stale for a moment
Many specialised viewsEach screen is very fastMore projections to build and keep right
Few shared viewsLess to maintainSome screens still need extra work

10Common Problems and Mistakes

Common mistakes

  1. Using it everywhere. Applying CQRS to a simple CRUD screen only adds code and delay.
  2. Queries that change data. A "get" that also updates a counter breaks the idea and makes caching unsafe.
  3. Ignoring the delay. The user clicks save, the list reloads, and the new item is missing. Plan the user experience for it.
  4. Not idempotent projections. A message delivered twice then double counts.
  5. No way to rebuild. A bug in a projection leaves wrong data with no way to fix it.
  6. Commands that return big data. Commands should answer small. Let a query fetch the full result.

Things to watch

⏱️Projection lag
Track how far the read side is behind and alert when it grows.
🔁Duplicate events
Brokers often deliver at least once. Use event ids to ignore repeats.
🔀Out-of-order events
Use version numbers so an older change does not overwrite a newer one.
🧩Schema changes
A new field needs a new projection and often a full rebuild of the view.

11Real-World Examples

🛒Online shops
Orders are written to a transactional store. Product search and listing pages read from a search index.
🏦Banking
Transactions go through strict rules. Balances and statements are read from prepared views.
🚕Ride apps
Trip state changes are commands. Maps and driver lists read from fast, nearby copies.
📺Streaming
Viewing history is written in bulk. Home screen rows are built as read models for each user.
📰Social feeds
A post is one write. Each follower's feed is a precomputed read view.
🧾Tools
Often built with Kafka, Axon, EventStoreDB, MediatR (.NET) or plain handlers and database views.
📝Note
Companies seldom use full CQRS everywhere. They apply it to the few parts where reads and writes truly differ.
Mini case: product page
📦WarehouseUpdateStock command
⇢⇣StockChanged
🔄Projector
→↓
📚Product viewprice + stock + rating
←GetProductPage
📱Shopper
The page loads from a flat read model, while the stock count is changed by commands.

12Related Topics to Read Next

Event Sourcing→

Often paired with CQRS: events on the write side, projections on the read side.

Event-Driven Architecture→

Events carry changes from the write side to the read side.

Materialized Views→

A simple way to get a read model inside one database.

Denormalization→

Read models copy data on purpose for speed.

Replication→

Read replicas are the lightest form of separate read capacity.

Message Queues→

Often used to move events to the projection.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: separate models for writes (commands) and reads (queries).
  • ✔Command: changes state, returns little. Query: reads, changes nothing.
  • ✔Levels: split code, split views, split database, plus Event Sourcing.
  • ✔Sync: projections update the read model from events or CDC.
  • ✔Cost: eventual consistency, more parts, projections to maintain.
  • ✔Make safe: idempotent projections, version numbers, lag alerts, rebuild option.
  • ✔Use when: read and write needs differ a lot. Skip for simple CRUD.
  • ✔One line: “Write with rules, read from a view built for reading.”
← Previous
Hexagonal Architecture
Next →
Event Sourcing