What is CQRS, and why would you consider using it?

CQRS (Command Query Responsibility Segregation) is a software pattern, which in its simplest form, looks at segregating Commands from Queries.

Most applications do far more reading from writing, and in this scenario, CQRS can really improve scalability. Databases do not normally scale easily or cheaply (in a cloud environment you may have to jump up a tier based on the resource usage, and this can quickly become costly!)

What are the benefits of CQRS?

Scaling and Optimisations

It is possible to scale resources independently. An example of this may be you have a 20%, 80% split for commands, to queries. Using CQRS means you can have a smallish instance database for commands, of which has automatic replication to a larger database which is used for queries or a completely different type of datastore, which is more optimised for reads.

Redundancy and Eventual Consistency

Commands and Queries can fail independently of each other, and this can be achieved by adding a layer of redundancy between the commands and the database, by using something like a message queue.

If the command cannot be executed straight away, and queued, Querying the data for something that was going to be changed will still work, although will not be up to date. This is referred to as eventual consistency and adds a layer of resiliency to an application, as it eventually is run (or rerun in the event of an error).

Performance

Since the queries are separate, it is possible to generate views or precalculate query outputs rather than using complex joins when querying the data. An example of this may be that you store data for writes in a relational database, but then have a task which generates and updates queryable data within a document database, which does not require complex joins, it effectively performs the complexities of the query at a time of choosing, rather than at the time the data is requested.

Technologist who enjoys writing and working with software and infra. I write up all the things I learn as I go along to share the knowledge! beardy.digital

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store