CQRS в чистой архитектуре
Узнайте, как разделение ответственности команд и запросов отделяет модели записи от моделей чтения и как естественно встроить его в границы чистой архитектуры.
«CQRS в чистой архитектуре» — бесплатный урок Clean Architecture & Design Patterns in Practice на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Clean Architecture & Design Patterns in Practice, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Clean Architecture & Design Patterns in Practice содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
One Model Doing Too Much
As systems grow, a single model that handles both writes and reads often strains.
Writes need rich validation and invariants; reads need fast, shaped data for screens. CQRS splits these concerns.
Commands vs Queries
CQRS divides operations into two kinds:
- Commands change state and return nothing meaningful.
- Queries return data and never change state.
This is the Command-Query Separation principle, scaled to architecture.
Separate Write and Read Models
The write side uses rich entities enforcing invariants. The read side uses simple, denormalized DTOs tailored to each view.
They can even use different storage, optimized for their job.
A Command
A command captures intent and is handled by a write-side interactor.
class PlaceOrderCommand {
final String customerId;
final java.util.List<String> items;
PlaceOrderCommand(String c, java.util.List<String> i) {
this.customerId = c; this.items = i;
}
}A Command Handler
The handler loads entities, enforces rules, and persists — pure use-case logic.
class PlaceOrderHandler {
private final OrderRepository repo;
PlaceOrderHandler(OrderRepository repo) { this.repo = repo; }
void handle(PlaceOrderCommand cmd) {
Order order = Order.create(cmd.customerId, cmd.items);
repo.save(order);
}
}A Query
The read side bypasses rich entities and returns a shape built for display.
class OrderSummaryDto {
public String orderId;
public String status;
public double total;
}
interface OrderQueries {
OrderSummaryDto getSummary(String orderId);
}How It Maps to Clean Architecture
Both sides honor the dependency rule:
- Command handlers are interactors using repository output ports.
- Query interfaces are also ports, implemented in the outer layer.
CQRS adds no new violation; it just doubles the use-case shape.
Optional: Eventual Consistency
In advanced setups the read model is built asynchronously from events emitted by the write side.
This brings eventual consistency: reads may briefly lag writes. Adopt it only when scale truly demands it.
When CQRS Pays Off
- Read and write workloads differ dramatically.
- Complex domains where write invariants clutter read queries.
- High-read systems needing tailored projections.
For simple CRUD, plain repositories are enough.
The Cost Side
CQRS adds moving parts: two models, possibly two stores, and synchronization.
That complexity is justified only when the separation buys real clarity or performance. Do not adopt it by default.
A Pragmatic Middle Ground
You can apply logical CQRS without separate databases: just split command handlers from query services in code.
This captures most of the clarity benefit with little extra infrastructure.
Quick Check
Test your understanding of CQRS.
Recap
You learned CQRS within Clean Architecture.
- Commands change state; queries read it.
- Separate write (rich entities) and read (DTOs) models.
- Both remain ports honoring the dependency rule; adopt it only when complexity warrants.
Часто задаваемые вопросы
Урок «CQRS в чистой архитектуре» бесплатный?
Да — полный текст урока «CQRS в чистой архитектуре» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Clean Architecture & Design Patterns in Practice, подпишись на CoddyKit PRO. Курс Clean Architecture & Design Patterns in Practice содержит 4 уроков всего.
Чему я научусь в уроке «CQRS в чистой архитектуре»?
Узнайте, как разделение ответственности команд и запросов отделяет модели записи от моделей чтения и как естественно встроить его в границы чистой архитектуры. Ты практикуешь Clean Architecture & Design Patterns in Practice с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Clean Architecture & Design Patterns in Practice?
Предыдущий опыт не требуется. Clean Architecture & Design Patterns in Practice на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «CQRS в чистой архитектуре»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Clean Architecture & Design Patterns in Practice?
Да. Каждый урок Clean Architecture & Design Patterns in Practice включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Работа со сквозными аспектами
- Чистая архитектура на основе событий
- Чистая архитектура в микросервисах
- CQRS в чистой архитектуре