Skip to main content




CQRS is a very good tool when it comes to programming. It is really helpful and can make many things easier for you, keep reading and learn everything about CQRS.

What is CQRS?

CQRS es un patrón arquitectónico, donde el acrónimo significa Segregación de Responsabilidad de Consulta de Comando (o Command Query Responsibility Segregation, en inglés). Podemos hablar de CQRS cuando las operaciones de lectura de datos se separan de las operaciones de escritura de datos y ocurren en una interfaz diferente.

En la mayoría de los sistemas CQRS, las operaciones de lectura y escritura utilizan diferentes modelos de datos, a veces incluso diferentes almacenes de datos. Este tipo de segregación hace que be más fácil escalar, leer y escribir operaciones y controlar la seguridad, pero agrega complejidad adicional a tu sistema.

Node.js at Scale, is a collection of articles that focus on the needs of companies with larger Node.js installations and advanced Node.

The level of segregation can vary in CQRS systems:

  • Single data stores and separate model for reading and updating data.
  • Separate data stores and separate model for reading and updating data.

In the simplest datastore separation, we can use read-only replicas to achieve segregation.

Why and when to use CQRS?

In a typical data management system, all CRUD operations (create delete read update) run on the same interface of entities in a single data store. How to create, update, query and delete table rows in a SQL database through the same model.

CQRS really shines compared to the traditional approach (using a single model) when building complex data models to validate, and meet your business logic when data manipulation occurs. Read operations versus update and write operations can be very different or much simpler, such as accessing only a subset of your data.

A very vivid example

En nuestra herramienta de monitoreo Node.js , usamos CQRS para segregar el almacenamiento y la representación de los datos. Por ejemplo, cuando ve una visualización de seguimiento distribuido en nuestra user interface, los datos detrás de ella llegaron en trozos más pequeños de los agentes de aplicaciones de nuestros clientes a nuestra API de recopilador público.

In the Collector API, we just do thin validation and send the data to a messaging queue for processing. At the other end of the queue, workers consume messages and resolve all necessary dependencies through other services. These workers are also saving the transformed data in the database.

If a problem occurs, we return the message with an exponential fallback and a maximum limit to our messaging queue. Compared to this complex data write flow, on the rendering side of the flow, we only query a read replica database and visualize the result for our clients.

CQRS and its event source

He visto muchas veces que las persons están confundiendo estos dos conceptos. Ambos son muy utilizados en infraestructuras dirigidas por eventos como en micro-servicios controlados por eventos, pero tienen significados muy diferentes.

Report Database - Denormalizer

In some event-driven systems, CQRS is implemented so that the system contains one or more reporting databases.

Una base de datos de informes es un almacenamiento de solo lectura completamente diferente que modela y conserva los datos en el mejor formato para representarlos. Está bien almacenarlo en un formato des-normalizado para optimizarlo para las necesidades del client. En algunos casos, la base de datos de informes solo contiene datos derivados, incluso de múltiples fuentes de datos.

In a microservices architecture, we call a Denormalizer service if it listens for some events and maintains a database of reports based on them. The client is reading the reporting database from the denormalized service.

Un ejemplo puede ser que el servicio de perfil de Username emita un event user.edit with useful information {id: 1, name: 'Mary Anne', Status: 'churn'}, Denormalizer service listens for it, but only stores it in its Reporting Database {name: 'Mary Anne'}, because the client is not interested in the internal churn state of the user.

It can be difficult to keep a reporting database in sync. Usually, we can only aim for eventual consistency.

Other

CQRS is a powerful architectural pattern to segregate read and write operations and their interfaces, but it also adds additional complexity to your system. In most cases, you shouldn't use CQRS for the whole system, only for specific parts where complexity and scalability make it necessary.

To read more about CQRS and reporting databases, I recommend checking out the following resources:

  • CQRS - Martin Fowler
  • CQRS - MSDN
  • CQRS, Task Based UI, Event Source Again! - Greg Young
  • CQRS and Event Source - Code on the Beach 2014 - Greg Young
  • Reports Database - Martin Fowler

Congratulations on completing this lesson!