CQRS (Command Query Responsibility Segregation) Implementation for Web Application
CQRS separates write (Commands) and read (Queries) models in application. Instead of one model that simultaneously accepts changes and answers queries, two independent sides are created: Command Side handles business operations and changes state, Query Side returns denormalized representations for UI.
Motivation
Standard CRUD architecture breaks under load when:
- Reads far exceed writes — need independent scaling
- Data form for writing differs from reading form (normalization vs. denormalization)
- Complex business rules on write conflict with query performance
- History changes or audit needed
CQRS solves these at cost of increased system complexity. For simple CRUD app it's excessive.
Command Side Structure
Command — intention to change state. Contains everything needed for operation:
// Commands — immutable intention objects
interface CreateOrderCommand {
readonly type: 'CreateOrder';
readonly customerId: string;
readonly items: Array<{ productId: string; quantity: number; price: number }>;
readonly shippingAddress: Address;
}
interface CancelOrderCommand {
readonly type: 'CancelOrder';
readonly orderId: string;
readonly reason: string;
readonly requestedBy: string;
}
Command Handler — processes one command type, contains business logic:
class CreateOrderCommandHandler {
constructor(
private orderRepo: OrderRepository,
private productRepo: ProductRepository,
private eventBus: EventBus
) {}
async handle(command: CreateOrderCommand): Promise<string> {
// 1. Load aggregate or create new
const order = Order.create(command.customerId);
// 2. Apply business rules
for (const item of command.items) {
const product = await this.productRepo.findById(item.productId);
if (!product.isAvailable(item.quantity)) {
throw new InsufficientStockError(item.productId);
}
order.addItem(item);
}
order.setShippingAddress(command.shippingAddress);
order.submit();
// 3. Save aggregate
await this.orderRepo.save(order);
// 4. Publish domain events
await this.eventBus.publishAll(order.pullDomainEvents());
return order.id;
}
}
Command Bus — routes commands to appropriate handlers:
class CommandBus {
private handlers = new Map<string, CommandHandler>();
register<T extends Command>(type: string, handler: CommandHandler<T>) {
this.handlers.set(type, handler);
}
async dispatch<T extends Command>(command: T): Promise<unknown> {
const handler = this.handlers.get(command.type);
if (!handler) throw new Error(`No handler for ${command.type}`);
// middleware: validation, logging, retry
return handler.handle(command);
}
}
Query Side Structure
Query — data request without side effects:
interface GetOrderDetailsQuery {
readonly type: 'GetOrderDetails';
readonly orderId: string;
}
interface GetCustomerOrdersQuery {
readonly type: 'GetCustomerOrders';
readonly customerId: string;
readonly status?: OrderStatus;
readonly page: number;
readonly perPage: number;
}
Read Model — denormalized representation optimized for specific UI:
interface OrderDetailsReadModel {
id: string;
status: string;
customer: { id: string; name: string; email: string };
items: Array<{
productId: string;
productName: string;
quantity: number;
unitPrice: number;
subtotal: number;
}>;
shippingAddress: Address;
totals: { subtotal: number; shipping: number; tax: number; total: number };
timeline: Array<{ event: string; occurredAt: Date; actor: string }>;
createdAt: Date;
updatedAt: Date;
}
Query Handler — reads directly from Read Model without loading aggregate:
class GetOrderDetailsQueryHandler {
constructor(private db: Database) {}
async handle(query: GetOrderDetailsQuery): Promise<OrderDetailsReadModel> {
return this.db.queryOne(`
SELECT
o.id, o.status, o.created_at, o.updated_at,
c.id as customer_id, c.name as customer_name, c.email,
json_agg(json_build_object(
'productId', oi.product_id,
'productName', p.name,
'quantity', oi.quantity,
'unitPrice', oi.unit_price,
'subtotal', oi.quantity * oi.unit_price
)) as items,
o.shipping_address,
o.total_amount
FROM orders_view o
JOIN customers c ON c.id = o.customer_id
JOIN order_items_view oi ON oi.order_id = o.id
JOIN products p ON p.id = oi.product_id
WHERE o.id = $1
GROUP BY o.id, c.id
`, [query.orderId]);
}
}
Read Model Synchronization
Read Model updates asynchronously via domain events. Eventual consistency — Read Model can temporarily lag Write Model.
class OrderReadModelUpdater {
// Subscribed to events from EventBus or Kafka
async on(event: DomainEvent) {
switch (event.eventType) {
case 'OrderCreated':
await this.db.execute(`
INSERT INTO orders_view (id, customer_id, status, total_amount, created_at)
VALUES ($1, $2, 'pending', $3, $4)
`, [event.aggregateId, event.payload.customerId,
event.payload.total, event.occurredAt]);
break;
case 'OrderStatusChanged':
await this.db.execute(`
UPDATE orders_view
SET status = $2, updated_at = $3
WHERE id = $1
`, [event.aggregateId, event.payload.newStatus, event.occurredAt]);
break;
case 'OrderItemAdded':
await this.db.execute(`
INSERT INTO order_items_view (order_id, product_id, quantity, unit_price)
VALUES ($1, $2, $3, $4)
ON CONFLICT (order_id, product_id) DO UPDATE
SET quantity = EXCLUDED.quantity
`, [event.aggregateId, event.payload.productId,
event.payload.quantity, event.payload.price]);
break;
}
}
}
Scaling
Write Side — vertical scaling of main DB, sharding by aggregate_id.
Read Side — horizontal scaling of PostgreSQL read replicas, Redis cache for hot data, Elasticsearch for full-text search, separate table or schema per Read Model.
CQRS Implementation Levels
| Level | Description | Complexity |
|---|---|---|
| Logical separation | Separate methods/classes for commands and queries | Low |
| Different data models | Commands → normalized DB, Queries → denormalized views | Medium |
| Different databases | Write DB (PostgreSQL), Read DB (Redis/Elastic) | High |
| Different services | Write and Read — separate microservices with independent deploy | Very high |
Start with logical separation. Move to different DBs only if necessity proven.
Implementation Timeline
- Refactor existing app to Command/Query separation — 1–2 weeks
- New app with CQRS from start — 2–3 weeks
- Full CQRS + Event Sourcing + async Read Models — 4–8 weeks depending on domain complexity







