# CQS and CQRS

## CQS (Command Query Separation)

CQS **separates methods** which are used for commands (writes) and queries (reads). CQS does not forbid the use of same model[^1] for both read and write.

{% hint style="info" %}
Please note that it is very rare for someone to talk about CQS. Usually they talk about CQRS instead.
{% endhint %}

## CQRS (Command Query Responsibility Segregation)

CQRS is the extension of CQS (which means CQRS also separates mutation command (write query) from read queries). But here's the difference, CQRS **uses different** [**model**](#user-content-fn-1)[^1] for write (command) and read (query) with the main goal of optimizing write and read operations.

There will be a data model to handle the writes, and another to handle the reads. By splitting the responsibility of reads and writes to different data model, it will become easier to optimize the read and write operations. The only downside is that the system must be able to handle data inconsistencies (because it is very unlikely to have the data 100% synced all the time with CQRS).

On the picture below, each data model is assigned to a different database:

<figure><img src="https://41416392-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FihUywrGs2FqFA4ROWhcg%2Fuploads%2FL3nmzYBcdU2rFYH9RIWT%2Fcqrs.png?alt=media&#x26;token=47cec99a-9ab1-409a-ba17-a95b641efcab" alt=""><figcaption></figcaption></figure>

The structure of the read database should be different with the structure of the write database to optimize each operations. To sync the data between the write and read database, some sort of messaging mechanism can be used. The message then can be consumed to update the read database **asynchronously**.

### Event-Sourcing with CQRS

The most common use case for CQRS is when you're planning to use event sourcing. You might want to read more about event-sourcing here: [event-sourcing](https://note.levelcode.org/software-engineering-notes/event-sourcing "mention")

Here's a good video refresher for event-sourcing with CQRS using Kafka:&#x20;

{% embed url="<https://youtu.be/lg6aF5PP4Tc?si=unoS465IO3MtYAYy&t=118>" %}

Kafka was used in the CQRS event sourcing example on the video for the write side. Meanwhile a DB was used for the read side.

[^1]: A "model" here refers to the data structure or schema which represents the data.
