Polski

Inventory with CQRS – separate write and read models

Warehouse commands validated on their own write model, events on a bus and a projection building a read model with a low-stock report. The read model can be rebuilt from events alone.

medium · typescript · javascript · python · csharp · java · go · 20 XP

A ceramics wholesaler has a single ORM Product model that handles both goods receipts and the "what to reorder" report. The report joins and sorts tables the write side also needs, and business rules (never ship more than is in stock) get mixed with view formatting. CQRS (Command Query Responsibility Segregation) separates these responsibilities: the write side accepts commands and guards the rules, the read side builds views shaped for queries – and events connect them.

Task

The EventBus (subscribe, publish) and the event types are ready: ProductRegistered(sku, name), StockReceived(sku, quantity), StockShipped(sku, quantity).

  1. Write side – InventoryCommands(bus) with the commands registerProduct(sku, name), receiveStock(sku, quantity), shipStock(sku, quantity):

    • validates against its own state (for example a sku → on hand dictionary), never the read model – it must work even when nobody subscribes to the bus;
    • errors in this order: Product already registered: <sku>, Unknown product: <sku>, Quantity must be positive, Insufficient stock for <sku>;
    • after successful validation it publishes one event; a rejected command publishes nothing;
    • commands return nothing (in Go – only an error).
  2. Read side – InventoryReadModel:

    • apply(event) – a projection updating { sku, name, onHand, shipped } views from events only;
    • getProduct(sku) – a copy of the view or "nothing";
    • lowStock(threshold) – products with onHand < threshold, sorted ascending by stock and, on ties, by sku;
    • queries return copies – changing a returned object does not change the model.

The tests connect both sides through the bus, but also check each one separately: commands with no subscriber and a read model rebuilt from a stored list of events. Names per language: register_product, low_stock, on_hand, ValueError (Python); InvalidOperationException (C#); IllegalStateException/IllegalArgumentException and Optional<ProductView> (Java); in Go NewInventoryCommands, NewInventoryReadModel, Product(sku) (ProductView, bool), lower-case error messages, and events published as values (ProductRegistered{...}).

Topics: CQRS, Event-Driven Architecture

Related articles

  • CQRS: one model for changing, another for reading

    Command Query Responsibility Segregation without overdoing it: from Bertrand Meyer's CQS, through three levels of CQRS, to projections and eventual consistency. Commands, queries and projections in C#, TypeScript, Java, Go and Python.