Library

Volume 1 · Design Patterns

Notebook
Sign in

Section 18

Enterprise Architecture Patterns

1,988 words · about 9 min

18.1 Strangler Fig

Already covered in depth in Section 7.2 as a migration strategy — incrementally replace pieces of a legacy system behind a routing layer, retiring the legacy system piece by piece rather than in one risky rewrite. Repeated here as a named pattern for completeness:

Legacy Monolith → [Router/Gateway] → gradually redirect routes to new services
                                    → old code path shrinks over time
                                    → eventually the legacy system is an empty shell, decommissioned

18.2 CQRS (Command Query Responsibility Segregation)

                    ┌─────────────┐
  Commands ────────▶│  Write Model │────▶ SQL Server (normalized)
  (Create, Update)  │  (Domain)    │
                    └──────┬──────┘
                           │ Domain Events
                           ▼
                    ┌─────────────┐
  Queries ─────────▶│  Read Model  │────▶ Denormalized views / Redis / Elasticsearch
  (Search, List)    │ (Projections)│
                    └─────────────┘

When to use CQRS: read and write workloads have very different scaling needs; complex domain logic on writes but simple flat reads; you genuinely need different data models for reading vs writing (not just different queries); event-driven infrastructure is already in place. When NOT to use: simple CRUD apps, small/early-stage teams, no significant read/write asymmetry — CQRS roughly doubles the moving parts (write model + read model + projection mechanism) for no benefit if reads and writes are symmetric.

// Write side — command handler mutates the aggregate and raises domain events
public class CreateOrderHandler : IRequestHandler<CreateOrderCommand, OrderResult>
{
    public async Task<OrderResult> Handle(CreateOrderCommand cmd, CancellationToken ct)
    {
        var order = new Order(cmd.CustomerId, cmd.Items);
        await _repo.AddAsync(order);
        await _mediator.Publish(new OrderCreatedEvent(order.Id, order.Total), ct);
        return new OrderResult(order.Id, true);
    }
}

// Read side — a projection handler keeps a denormalized read model up to date
public class OrderCreatedProjectionHandler : INotificationHandler<OrderCreatedEvent>
{
    public async Task Handle(OrderCreatedEvent e, CancellationToken ct)
    {
        await _readDb.OrderSummaries.AddAsync(new OrderSummaryReadModel(e.OrderId, e.Total));
        await _readDb.SaveChangesAsync(ct);
    }
}
# CQRS in Python — separate write and read paths, connected by an event
class CreateOrderCommandHandler:
    def __init__(self, order_repo, event_bus):
        self._repo = order_repo
        self._bus = event_bus

    def handle(self, customer_id: str, items: list) -> str:
        order = Order.create(customer_id, items)
        self._repo.save(order)
        self._bus.publish("OrderCreated", {"order_id": order.id, "total": str(order.total)})
        return order.id


class OrderSummaryProjection:
    """Read-side projection — subscribes to events, maintains a denormalized view."""
    def __init__(self, read_db):
        self._read_db = read_db

    def on_order_created(self, event: dict) -> None:
        self._read_db.order_summaries.insert({
            "order_id": event["order_id"], "total": event["total"],
        })

18.3 Event Sourcing

Instead of storing current state, store the full sequence of events that produced it. Current state is always derivable by replaying events — giving a complete, immutable audit trail and the ability to build new projections retroactively.

public class BankAccount : EventSourcedAggregate
{
    public decimal Balance { get; private set; }

    public void Deposit(decimal amount)
    {
        if (amount <= 0) throw new DomainException("Amount must be positive");
        Apply(new MoneyDepositedEvent(Id, amount, DateTime.UtcNow));
    }

    public void Withdraw(decimal amount)
    {
        if (amount > Balance) throw new DomainException("Insufficient funds");
        Apply(new MoneyWithdrawnEvent(Id, amount, DateTime.UtcNow));
    }

    private void On(MoneyDepositedEvent e) => Balance += e.Amount;
    private void On(MoneyWithdrawnEvent e) => Balance -= e.Amount;
}
// Event Store: [AccountCreated] → [Deposited $100] → [Deposited $50] → [Withdrawn $30]
// Current Balance = $120, rebuilt entirely by replaying the event stream
# Event Sourcing in Python
class BankAccount:
    def __init__(self, account_id: str):
        self.id = account_id
        self.balance = 0
        self._uncommitted_events: list[tuple] = []

    def deposit(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("Amount must be positive")
        self._apply(("MoneyDeposited", self.id, amount))

    def withdraw(self, amount: float) -> None:
        if amount > self.balance:
            raise ValueError("Insufficient funds")
        self._apply(("MoneyWithdrawn", self.id, amount))

    def _apply(self, event: tuple) -> None:
        event_type, _, amount = event
        if event_type == "MoneyDeposited":
            self.balance += amount
        elif event_type == "MoneyWithdrawn":
            self.balance -= amount
        self._uncommitted_events.append(event)

    @classmethod
    def replay(cls, account_id: str, events: list[tuple]) -> "BankAccount":
        """Rebuild current state purely from history — the essence of event sourcing."""
        account = cls(account_id)
        for event in events:
            account._apply(event)
        account._uncommitted_events.clear()   # these are historical, not new
        return account

18.4 Saga

Fully covered in Section 9.2 (choreography vs orchestration with code). As an enterprise pattern summary: Saga is the standard way to maintain data consistency across multiple services/databases without a distributed transaction, using a sequence of local transactions plus compensating actions for rollback.

18.5 Outbox

Fully covered in Section 9.3 with C# and Python code. Summary: solves the dual-write problem (DB write + message publish) by writing the event to an outbox table in the same local transaction as the business write, then publishing asynchronously from that table.

18.6 Repository

Mediates between the domain and the data-mapping layer, presenting persistence as if it were an in-memory collection of domain objects — the domain layer never depends on EF Core/SQLAlchemy/CosmosDB directly.

public interface IRepository<T> where T : class, IEntity
{
    Task<T?> GetByIdAsync(int id);
    Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate);
    Task AddAsync(T entity);
    void Update(T entity);
    void Remove(T entity);
}

public class EfRepository<T> : IRepository<T> where T : class, IEntity
{
    protected readonly DbContext _context;
    protected readonly DbSet<T> _dbSet;

    public EfRepository(DbContext context) { _context = context; _dbSet = context.Set<T>(); }

    public async Task<T?> GetByIdAsync(int id) => await _dbSet.FindAsync(id);
    public async Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate)
        => await _dbSet.Where(predicate).ToListAsync();
    public async Task AddAsync(T entity) => await _dbSet.AddAsync(entity);
    public void Update(T entity) => _dbSet.Update(entity);
    public void Remove(T entity) => _dbSet.Remove(entity);
}
# Repository pattern in Python (SQLAlchemy-backed, but the domain never imports SQLAlchemy)
from abc import ABC, abstractmethod


class IOrderRepository(ABC):
    @abstractmethod
    def get_by_id(self, order_id: str) -> "Order | None": ...
    @abstractmethod
    def add(self, order: "Order") -> None: ...
    @abstractmethod
    def find(self, **filters) -> list["Order"]: ...


class SqlAlchemyOrderRepository(IOrderRepository):
    def __init__(self, session):
        self._session = session

    def get_by_id(self, order_id: str):
        return self._session.query(OrderModel).filter_by(id=order_id).first()

    def add(self, order) -> None:
        self._session.add(OrderModel(**order.__dict__))

    def find(self, **filters) -> list:
        query = self._session.query(OrderModel)
        for key, value in filters.items():
            query = query.filter(getattr(OrderModel, key) == value)
        return query.all()

“The Repository pattern is foundational to DDD — it abstracts away the ORM/database so the domain layer has zero infrastructure dependency. It also makes code far easier to unit test: mocking IOrderRepository requires no database connection at all.”

18.7 Unit of Work

Coordinates writes across multiple repositories into one atomic commit — ensures either everything in the business transaction is saved, or nothing is.

public interface IUnitOfWork : IDisposable
{
    IRepository<Order> Orders { get; }
    IRepository<Product> Products { get; }
    Task<int> SaveChangesAsync(CancellationToken ct = default);
}

public class UnitOfWork : IUnitOfWork
{
    private readonly AppDbContext _context;
    public IRepository<Order> Orders { get; }
    public IRepository<Product> Products { get; }

    public UnitOfWork(AppDbContext context)
    {
        _context = context;
        Orders = new EfRepository<Order>(context);
        Products = new EfRepository<Product>(context);
    }

    public async Task<int> SaveChangesAsync(CancellationToken ct) => await _context.SaveChangesAsync(ct);
    public void Dispose() => _context.Dispose();
}

// Usage — both repository changes commit together, or neither does
await using var uow = new UnitOfWork(dbContext);
await uow.Orders.AddAsync(order);
uow.Products.Update(product);   // e.g., decrement stock
await uow.SaveChangesAsync();
# Unit of Work in Python — using a context manager
class UnitOfWork:
    def __init__(self, session_factory):
        self._session_factory = session_factory

    def __enter__(self) -> "UnitOfWork":
        self.session = self._session_factory()
        self.orders = SqlAlchemyOrderRepository(self.session)
        self.products = SqlAlchemyProductRepository(self.session)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is not None:
            self.session.rollback()
        else:
            self.session.commit()
        self.session.close()


# Usage
with UnitOfWork(session_factory) as uow:
    uow.orders.add(order)
    uow.products.decrement_stock(product_id, quantity)
    # commits automatically on clean exit; rolls back automatically on exception

18.8 Interview Q&A

Q1: When would you choose CQRS + Event Sourcing over traditional CRUD?

Choose CQRS + Event Sourcing when you need a complete audit trail (financial, healthcare, compliance-heavy domains), when read and write patterns are dramatically different (e.g., 100:1 read:write ratio), when the domain has many complex state transitions (order lifecycle, workflow engines), or when multiple downstream systems need to react to every state change. Choose traditional CRUD when the domain is simple and straightforward, the team lacks event-sourcing experience, there’s no regulatory driver for an audit trail, read and write loads are similar, and time-to-market is critical — CQRS/ES adds real complexity that has to be justified. A concrete example: on a document-processing platform, writes went through a complex ingestion pipeline (validation, enrichment, classification) while reads were simple flat search/listing queries served from Elasticsearch projections — and because every document state change was captured as an event, the same event stream fed compliance reports and ML training data as a side benefit.

Q2: How do you implement the Outbox pattern for reliable messaging?

Covered in full in Section 9.3 — the short version: write the business entity and an outbox row in the same local database transaction, then a background worker (or CDC via Debezium) publishes unprocessed outbox rows to the broker and marks them processed after a successful publish. This avoids the dual-write problem without needing distributed transactions.

Q3: Explain Repository and Unit of Work — aren’t they redundant with a modern ORM’s DbContext/Session?

There’s real overlap — DbContext in EF Core or a SQLAlchemy Session already implements a change-tracking Unit of Work internally. I still introduce an explicit IRepository/IUnitOfWork abstraction at the domain boundary specifically so the domain layer has zero dependency on the ORM — it depends only on interfaces it owns, which keeps domain unit tests running with in-memory fakes and no database at all, and gives me the option to swap persistence technology behind the interface without touching domain code. Where I’d skip the extra abstraction is in a small application or a read-only reporting service, where the ORM’s own session is already a perfectly adequate unit of work and the extra interface layer would be pure ceremony.

Q4: What’s the difference between the Strangler Fig pattern and CQRS/Event Sourcing — they both seem to involve gradual, incremental change?

They solve different problems. Strangler Fig is a migration strategy — a way to safely replace a legacy system’s routes/capabilities one at a time behind a router, with a rollback path at every step, until the legacy system can be decommissioned. CQRS and Event Sourcing are steady-state architectural patterns for how a system represents and separates its read/write concerns — they describe the target architecture, not how you get there. In practice they combine well: I might use Strangler Fig to migrate a legacy monolith’s order module out service by service, and choose CQRS + Event Sourcing as the target architecture for the new Order service specifically because the domain has complex state transitions and an audit-trail requirement.