CodeMosa

Master LeetCode Patterns

CQRS

Data & Consistency

Separate command (write) and query (read) models for scalability and flexibility

Core Idea

#

Split responsibilities: writes validate and emit events; reads use optimized materialized views. Scale and evolve each side independently.

When to Use

#

When read and write workloads/SLAs differ significantly, or when you need specialized read models and high scalability.

Recognition Cues

#
Indicators that this pattern might be the right solution
  • Read-heavy vs write-heavy asymmetry
  • Complex queries requiring denormalized views
  • Independent scaling and SLAs for read/write

Pattern Variants & Approaches

#

Overview

#
Separate write (commands) and read (queries) paths with distinct models; propagate changes via events to update read stores.

Overview Architecture

CommandUpdatePublishConsumeQueryRead/Update👤Client⚙️Write API⚙️Read API📬Event Bus💾Write DB💾Read DB

When to Use This Variant

  • Read-heavy workloads
  • Different read/write access patterns
  • Projection lag management

Use Case

High-scale APIs needing tailored read models and independent scaling of reads/writes.

Advantages

  • Optimized reads
  • Independent scaling
  • Clear separation of concerns

Implementation Example

# CQRS flow sketch
POST /cmd -> writeModel + publish(event)
GET /query -> readModel
consumer(event) -> update(readModel)

Tradeoffs

#

Pros

  • Independent scaling and optimized reads
  • Clear separation of concerns
  • Supports multiple tailored read stores

Cons

  • Operational complexity and more services
  • Eventual consistency
  • Requires strong observability

Common Pitfalls

#
  • Inconsistent projections without outbox/CDC
  • Overusing CQRS for simple domains
  • Hard to debug cross-pipeline issues
  • Opaque failure modes in projection pipelines

Design Considerations

#
  • Use outbox/CDC to feed read models
  • Explicit consistency guarantees per endpoint
  • Reconciliation and replayer tooling
  • Schema registry and versioning
  • Backfill with throttling and monitoring

Real-World Examples

#
LinkedIn

Search and feed projections from Kafka

Billions of events/day
eCommerce

Order writes vs catalog reads separation

Global storefronts
Fintech

Ledger commands + analytic read models

Strict SLAs, audits

Complexity Analysis

#
Scalability

High - Read stores scale independently

Implementation Complexity

High - Pipelines and projections

Cost

Medium to High - Extra infrastructure