CQRS (Command Query Responsibility Segregation) - Separates operations that change state (commands) from operations that read state (queries). - Write side: rich domain model, validation, business rules and transactions. - Read side: models optimised for queries — projections, denormalised tables, caches or search indexes — which can live in a separate store and scale independently. - Read models are often updated from domain events, so the read side may be eventually consistent. - Use it when read and write needs differ significantly (complex domains, heavy read traffic, reporting); avoid full CQRS for simple CRUD. - .NET implementation: command and query handlers (MediatR or plain handler classes), EF Core for writes, Dapper or EF Core projections for reads. Saga - Manages a business transaction that spans several services, each with its own database, where a single ACID transaction is impossible. - A saga is a sequence of local transactions; if a step fails, compensating transactions undo previous steps. - Example (order flow): create order (pending), reserve stock, charge payment, confirm order. If payment fails: release stock, cancel the order. - Two styles: - Choreography: each service listens for events and reacts (StockReserved triggers payment). Simple for small flows, but harder to follow as flows grow. - Orchestration: a central orchestrator sends commands and tracks state (MassTransit state machines, NServiceBus sagas, Durable Functions, Temporal). Easier to understand and monitor complex flows. - Requirements: idempotent steps, reliable messaging (outbox), timeouts, and compensations that are business actions (refunds), not technical rollbacks. BFF (Backend for Frontend) - A dedicated backend layer for each type of client (web, mobile, partner), shaped around that client's needs. - Responsibilities: aggregating data from several microservices into one response, transforming payloads for the UI, handling client-specific authentication (for example keeping OAuth tokens server-side and issuing secure cookies to browsers), caching, and protecting the UI from internal service changes. - Benefits: fewer round trips from clients, simpler frontends, and independent evolution per client. - Risks: duplicated logic across BFFs, and business logic creeping into the BFF (it should orchestrate and shape, not own business rules). Ownership by the frontend team usually works best. - .NET tools: an ASP.NET Core service, often with YARP for proxying, or the Duende BFF library for secure SPA authentication. How they fit together A mobile app calls its BFF, which aggregates data from the Orders and Catalog services. The Orders service uses CQRS internally, and placing an order starts a saga coordinating Inventory and Payment services through messaging.
Ravindra Wadile · · 0 likes