DEV Community

oaltena
oaltena

Posted on

3

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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️