Sobes.tech
Middle+

What is CQRS?

sobes.tech AI

Answer from AI

CQRS (Command Query Responsibility Segregation) is an architectural pattern that separates read (Query) and write (Command) operations on data into different models.

Main idea:

  • Commands change the system's state (create, update, delete).
  • Queries return data without changing the state.

Advantages of CQRS:

  • Allows optimizing data models for different tasks: normalized for writes, denormalized for reads.
  • Simplifies scaling: reading and writing can be scaled independently.
  • Improves support for complex business logic when changing data.

An example of a simplified structure in Go:

// Command — change of state
func CreateUserCommand(user User) error {
    // logic for creating a user
    return nil
}

// Query — data retrieval
func GetUserQuery(userID string) (User, error) {
    // logic for retrieving a user
    return User{}, nil
}

CQRS is often used together with Event Sourcing to manage state in distributed systems.