SYS ARCHITECTLearning Platform
Settings
Theory

CQRS (Command Query Responsibility Segregation)

📋 Overview

CQRS is an architectural pattern that separates the models for reading and writing data. In traditional systems, the same data model is used for both updates (Commands) and fetches (Queries). However, as applications scale, the requirements for these two operations diverge: writes need high integrity and complex business logic, while reads need high performance and complex aggregations. CQRS allows you to optimize each path independently, often using different databases for each.


🏗️ Core Principles & Characteristics

  • Command Model: Handles operations that change state (Create, Update, Delete). Returns void or a status/ID. Focuses on Domain Logic and Validation.
  • Query Model: Handles data retrieval. Returns a DTO. Focuses on speed, denormalization, and UI requirements.
  • Task-Based UI: Instead of a generic UpdateUser, the UI sends specific intents like RelocateUser or UpgradeSubscription.
  • Projection Engine: A background process (using CDC or Events) that synchronizes the Read DB with changes from the Write DB.
  • Eventual Consistency: The Read model might lag slightly behind the Write model, a necessary trade-off for scalability.

⚖️ Trade-offs: Pros & Cons

  • Pros:
    • Independent Scaling: Scale your Read replicas to millions of users without needing a massive Write master.
    • Optimized Data Schemas: Use a Normalized SQL DB for writes (Consistency) and a Document/Search DB (Elasticsearch) for reads (Performance).
    • Reduced Complexity: Simplifies the domain model by removing query-specific logic.
  • Cons:
    • High Complexity: Requires more infrastructure (Message brokers, multiple DBs, synchronizers).
    • Eventual Consistency: Users might not see their own updates immediately, requiring "Optimistic UI" tricks.
    • Code Duplication: Often requires separate models and DTOs for the same conceptual entity.

🌍 Real-World Implementation

  • E-commerce: Write DB handles order placement and inventory; Read DB (Elasticsearch) handles product search, filters, and categories.
  • Social Media: Write path handles posting/liking; Read path serves the "News Feed," which is a pre-computed denormalized view.
  • Analytics Dashboards: Raw events are written to a stream; a projection service aggregates them into a Timeseries DB for fast querying.
  • Tools: Axon Framework (Java), MediatR (.NET), Kafka/Debezium for projections.

💡 Interview "Gotchas" & Tips

  • Is CQRS same as Event Sourcing? No. They are often used together, but you can have CQRS without Event Sourcing (using simple triggers or CDC to update the read view).
  • Handling the Lag: If asked how a user sees their own update instantly: "Use a local UI state update (Optimistic UI) or have the client poll the read-model with a version ID until it matches."
  • When to avoid: Never use CQRS for simple CRUD apps. It adds massive "Architectural Tax" with no benefit if the read and write models are identical.
  • The "Saga" Pattern: Used in CQRS architectures to manage long-running business processes that span multiple aggregates.

📐 Suggested Architecture Primitives

  • Write DB: (PostgreSQL/MySQL) for the source of truth.
  • Read DB: (Redis/Elasticsearch/Mongo) for high-speed queries.
  • Message Broker: (Kafka/RabbitMQ) to propagate changes.
  • Command Bus: To route commands to their respective handlers.
  • Projection Service: A microservice that consumes events and updates the Read DB.
Canvas