CQRS (Command Query Responsibility Segregation)
Separates read and write operations into different data models.
Structure and behavior
Follow the arrows step by step.
Reads and writes have separate responsibilities. Separate databases and event sourcing are not required.
Expected benefits
Independent optimization of read and write models can improve performance, scalability, and security.
Trade-offs
Introduces eventual consistency and read lag between data stores.
Not suitable where a write must be visible immediately in the same data, such as bank balances, inventory, or safety-critical control.
Operations and adoption guide
Synthesis, distinct from items backed by source excerpts. Validate before applying in production.
When to use
Fits systems where reads and writes have very different loads and require high throughput, low latency, complex domain logic, or strict audit and regulatory controls. Examples include stock trading and e-commerce with separate order and inventory queries.
Scenario
A midsize online shop handles thousands of product queries per second and relatively few order writes. A delay of a few seconds is acceptable when showing stock and order status just after ordering. The write side validates order and inventory commands, persists them to the write DB, and publishes events. The read side updates a separate model for product lists and order lookup. On the post-payment confirmation screen, use read-your-writes to show what was just saved and monitor read-model lag.
Placement principles
- Use the write model and DB as the authority for command validation and transactions
- Keep the read model and DB read-only, using replicas or cache as needed
- Pass domain events from writes to reads through a broker
- Deploy projection workers or indexers separately to update the read model
- In Kubernetes, separate write and read services, Redis master and replicas, and Helm charts.
On premises
Deploy containerized command and query services, broker, and read/write stores to internal Kubernetes or VMs. Review network and storage isolation, security, privacy, TCO, and backup and recovery. Monitor replica lag and broker backlog, and standardize deployment and upgrade procedures.
Cloud
Use managed Kubernetes, databases, caches, and brokers to scale reads and writes independently. Test containers and orchestration locally and in staging before release. Apply autoscaling, multi-AZ deployment, read replicas, observability, and cost tags.
Kubernetes
Deploy command and query services, projection workers, read/write stores, and brokers as separate Deployments or StatefulSets with Services. Manage them with Helm or Kustomize. Run Redis master and replicas, Kafka, or Pulsar via a StatefulSet or Operator. Verify HPA, PDB, NetworkPolicy, resource requests and limits, rolling upgrades, and idempotent projection replay.
Incident response
Read-model lag or divergence can hide a just-saved change and cause users to submit it again. Other failures include broker backlog, stopped projections, and corruption when a deployment or replay applies changes twice. Track projection offsets, lag and gaps; mitigate with read-your-writes or caching. Make projections idempotent and add a repeat-log replay test to CI. Recover by clearing backlog, restarting projections, then rebuilding read models as needed.
Evidence by criterion (14 total)
Evidence availability at the time of research. Assess source accuracy and currency separately.
Definition and overviewEvidence available
Separates read and write operations into different data models.
Segregate the read and write operations for a data store into separate data models.Problem addressedEvidence available
Addresses the difficulty of optimizing different read and write performance and scaling needs with one model.
As applications grow, it can become increasingly difficult to optimize read and write operations on a single data model.Key components and resourcesEvidence available
May include a web application or microservices and separate read and write stores.
It has basically three components: * A web app written in NodeJS (which can be thought of a microservice)Data and asset placementEvidence available
Separate the authoritative write store from read replicas or read models.
A 'write' datastore (implemented using Redis master instance) * A 'read' datastore (implemented using Redis replica instances )Typical use casesEvidence available
Fits systems with high performance or scaling needs, complex domains, or strict audit and regulatory requirements, such as a stock trading platform.
CQRS is great for a stock trading platform where performance, scalability, and regulatory compliance are paramount.Example scenarioEvidence available
A user submits a form, sees previous data because the read model lags, and submits again.
the command succeeds, the read model has not caught up, the user's next page load shows old dataWhen to avoid and caveatsEvidence available
Not suitable where a write must be visible immediately in the same data, such as bank balances, inventory, or safety-critical control.
banking balances, inventory counts at checkout, safety-critical controls- don't tolerate eventual consistency well.On premises: development, deployment, and operationsEvidence available
Containerized microservices can run on on-premises Kubernetes.
You can take a containerized microservices-based application and deploy it into an on-premises Kubernetes cluster.Cloud: development, deployment, and operationsEvidence available
Containerize the workload, then deploy and test on managed Kubernetes such as OCI Kubernetes Engine.
After you containerize your microservices, you can deploy them to OCI Kubernetes Engine.Kubernetes: development, deployment, and operationsEvidence available
Use tools such as Node.js, Redis, and Helm to deploy and operate CQRS components on Kubernetes.
implementation of CQRS (Command Query Responsibility Segregation) architectural pattern on Kubernetes using NodeJS, Redis and Helm.Incident responseEvidence available
The read model updates after the write, so queries may briefly omit the latest change.
the read models are updated after the write, so for a short interval a query may not reflect a changeBenefitsEvidence available
Independent optimization of read and write models can improve performance, scalability, and security.
This approach allows you to optimize each model independently and can improve the performance, scalability, and security of an application.Drawbacks and trade-offsEvidence available
Introduces eventual consistency and read lag between data stores.
The CQRS pattern typically results in eventual consistency between the data stores.Representative tools and technologiesEvidence available
Examples include Kubernetes, Node.js, Redis, and Helm.
on Kubernetes using NodeJS, Redis and Helm.Additional references (21)
- CQRS Pattern - Azure Architecture Center | Microsoft Learn ↗
- bliki: CQRS ↗
- Untitled result ↗
- An introduction to command query responsibility segregation ↗
- Command Query Responsibility Segregation (CQRS) ↗
- CQRS Pattern Explained: When To Use It And When Not To ↗
- CQRS pitfalls and patterns • Particular Software ↗
- Applying simplified CQRS and DDD patterns in a microservice - .NET | Microsoft Learn ↗
- Follow these 8 best practices for cloud-native app development | TechTarget ↗
- Design a Microservices-Based Application ↗
- Building Kubernetes Native SaaS applications: iterating quickly by deploying in-cluster data planes | Pixie Labs Blog ↗
- Command-Query Responsibility Segregation (CQRS) ↗
- EZF-006. Should You Use Kubernetes?; CQRS. Command Query Responsibility Segregation; gRPC API Architecture; API Design: 51 ✔️DO's and ❌DON'Ts; Functional Requirements (FR) vs Non-functional (NFR) ↗
- code2k13/cqrs-example: An opiniated sample implementation of CQRS architectural pattern on Kubernetes using NodeJS, Redis and Helm ↗
- An illustrated guide to CQRS data patterns ↗
- CQRS Journey | Microsoft Learn ↗
- CQRS: Separating Reads from Writes Without Losing Your Mind - The HLD Handbook ↗
- CQRS and Projection Architecture | System Design Patterns ↗
- chapter_12_cqrs.asciidoc at master · cosmicpython/book ↗
- 2.20 Error handling and resilience patterns — Software Engineering Guide ↗
- System Design, Plainly — Season 3, Part 3: Event Sourcing & CQRS - DEV Community ↗