# Architectural Patterns
> **In one sentence:** an architectural pattern decides where business logic sits relative to UI,
> storage and integrations, and the right choice depends on which business-logic pattern you use.

## Why organize at all

A codebase also has to take input, show output, store data and call other systems. Without clear
boundaries, business rules leak into controllers, SQL and UI code, or get copied between them.
Then nobody knows what a change will break. Architectural patterns set the rules for what each
part may know and depend on.

## Layered architecture

Horizontal layers, each depending **only on the layer directly below it**:

| Layer | Responsibility today |
|---|---|
| **Presentation** | Every way into or out of the program: web UI, CLI, public API, message subscriptions, outgoing event topics. |
| **Business logic** | Rules and decisions. This is where transaction scripts, active records or a domain model live. |
| **Data access** | Every persistence and outside dependency: several databases, object storage, an internal message bus, third-party APIs and managed cloud services. |

### Service layer variant

An extra **service (application) layer** between presentation and business logic. It exposes the
system's operations (`register_member`, `cancel_booking`, …) and handles orchestration such as
transactions and error mapping, so controllers stay thin.

- *Benefits:* one service layer can serve both a UI and an API without duplication, related
  operations are grouped in one place, and it's easier to test.
- *Not always needed:* transaction scripts already *are* a service layer. Active record, on the
  other hand, needs one to orchestrate it.
- It's a **logical** boundary, not a separately deployed service.

**Other names:** presentation is the UI layer; service is the application layer; business logic is
the domain (or model) layer; data access is the infrastructure layer.

**When to use it:** good with **transaction script or active record**. It's awkward with a domain
model, because the logic layer *depends on* data access, while domain objects should know nothing about infrastructure.

> **Layers versus tiers:** a *layer* is logical, and all layers ship together as one unit. A *tier*
> is physical and deployed independently (browser, reverse proxy, app server, database server).

## Ports & adapters

Start from layers and make two changes:

1. Combine presentation and data access into one **infrastructure** layer, since both are just
   technology at the edges.
2. **Invert the dependency** (the Dependency Inversion Principle): the business logic depends on
   nothing, and infrastructure depends on it. Add an **application layer** as the façade for the
   system's operations.

**How it plugs together:** the core defines **ports** (interfaces it needs, such as "publish an
event" or "load a booking"), and infrastructure provides **adapters** (concrete implementations
for a specific database or queue), connected through dependency injection or at startup.

```python
# core (business logic) defines the port
class EventPublisher(Protocol):
    def publish(self, event: DomainEvent) -> None: ...

# infrastructure provides an adapter
class KafkaPublisher(EventPublisher):
    def publish(self, event): ...
```

- **Also known as:** hexagonal, onion and clean architecture. The same idea with different labels
  (application = use-case layer; business logic = domain or core layer).
- **When to use it:** the natural home for a **domain model** or an **event-sourced domain model**.

## CQRS

**Command-Query Responsibility Segregation.** It's organized like ports & adapters, but the data
lives in **more than one persistent model**.

### Why more than one model?

- One model rarely suits every need. Transactional work and analytics want different shapes.
- **Polyglot persistence:** no database is perfect, so you might use a document store for writes,
  a search engine for queries and a column store for reports.
- **Event sourcing** can only query one aggregate's events at a time. CQRS turns projections into
  queryable databases. CQRS started there, but it's useful with *any* business-logic pattern.

### Two kinds of model

- **Command execution model:** the single model used to change state and enforce rules. It's the
  only **strongly consistent** source of truth, with optimistic concurrency.
- **Read models (projections):** as many as you need, precomputed for display or for other systems.
  They're **read-only**, stored anywhere (a database, files, a cache), and can be **wiped and rebuilt
  from scratch**, so you can add new ones later.

### Keeping projections up to date

- **Synchronous (catch-up subscription):** a projection engine asks the write store for
  "everything changed after checkpoint *N*", updates the read models and saves the new checkpoint.
  The checkpoint must be **strictly increasing and consistent** (a database row-version, or your
  own counter), or records get skipped. Rebuilding is easy: reset the checkpoint to 0.
- **Asynchronous:** the write side publishes changes to a message bus and projectors subscribe.
  It scales well, but out-of-order or duplicate messages can corrupt views, and rebuilding is harder.
- **Advice:** always have the synchronous path, and add asynchronous on top if needed.

### A common myth

"Commands must never return data." **Wrong.** A command should report success or failure and why,
and it may return data the caller needs, **as long as that data comes from the strongly consistent
command model**, not from a projection that may not have caught up yet.

### When to use it

When the same data must live in several models or stores, and it's **required for an
event-sourced domain model**. It fits DDD's habit of using the best model for each job.

## Scope: per module, not per system

None of these patterns has to cover a whole system or even a whole bounded context. A context can
contain several subdomains, each needing different logic and architecture. Add **vertical slices**
(modules per subdomain) on top of the horizontal layers, and choose the right pattern for each
slice. That keeps a monolith modular, and those slices can later be split into separate bounded contexts.

| Business logic pattern | Natural architecture |
|---|---|
| Transaction script / active record | Layered |
| Domain model | Ports & adapters |
| Event-sourced domain model | CQRS |

## Check yourself

1. Which architectures can host active records?
2. Which ones keep business logic free of infrastructure?
3. In ports & adapters, where does the code for a managed cloud queue go?
4. True or false: a CQRS command can return data.
5. CQRS keeps several models in one bounded context. Does that break the "one model per context" idea?

<details><summary>Answers</summary>

1. Layered, and also ports & adapters and CQRS. All three can work.
2. Ports & adapters and CQRS.
3. The infrastructure layer, as an adapter.
4. True, as long as it comes from the strongly consistent model.
5. No. The read models are projections of the one command model, not competing models.

</details>
