DEV Community

oaltena
oaltena

Posted on

Explain CQRS (Command and Query Responsibility Segregation)

What is CQRS? How do I use it?
What are the advantages and disadvantages?

Top comments (1)

Collapse
 
jamesmh profile image
James Hickey • Edited

CQRS just means modelling every action, ability or behaviour in your system as either:

(a) a command (write)
(b) a query (read)

Commands change the state of a system.
Queries just tell you the state of the system.

Loosely speaking, in a web app, you would model GET requests as queries and POST requests as commands.

Queries and commands can, at their simplest level, just be a class:

(TypeScript)

class CreateUserCommand {

    public handle(email: string, password: string): void {
        // do stuff....
    }
}
class UserProfileQuery {

    public handle(userId: number): UserProfileDetails {
        // Fetch and return some data.
    }
}

Benefits?

It just makes your system much easier to reason about and build. You aren't mixing responsibilities by changing the system AND returning a complex query, etc.

If you need to run your queries in a performant way, then no problem. Your write and read models are separate and not shared.

Your write logic (validation, business rules, etc.) aren't tied up into the same model you use to fetch data (which can become a huge "God" object quickly).

So better performance, easier to maintain, easier to build, etc.