# Communication Patterns
> **In one sentence:** to make separate components work together safely, translate between their
> models, publish events reliably, and coordinate multi-step processes without pretending they're one transaction.

## Model translation

Recap from Chapter 4: partners and shared kernels coordinate directly. In customer–supplier
relationships where the downstream side won't conform, someone has to **translate**: the
downstream side with an **anticorruption layer (ACL)**, or the upstream side with an **open-host
service (OHS)** and its published language. The techniques are the same for both.

### Stateless translation (on the fly)

The translating side acts as a **proxy**: it intercepts requests or messages and maps one model to the other.

- **Synchronous:**
  - Put the mapping in the bounded context's own code (OHS for incoming requests, ACL for outgoing calls).
  - Or move it to an **API gateway** (open-source or cloud-managed). For an OHS, a gateway makes it
    easy to serve **several API versions** side by side.
  - A shared ACL used by several consumers effectively becomes its own small **interchange context**.
- **Asynchronous:** a **message proxy** subscribes to the source, transforms each message, can
  **filter out noise**, and forwards it on.
  - Important for an OHS: **don't expose internal domain events as they are.** Translate them into
    the published language so internals stay private. This separates **private events** (for
    internal use) from **public events** (for integration).

### Stateful translation (needs its own storage)

- **Aggregating incoming data:** batching many small requests for efficiency, or combining several
  fine-grained events into one. A gateway can't do this, so it needs storage, a custom component or
  a stream or batch platform.
- **Unifying several sources:**
  - **Backend-for-frontend:** one component combines data from several services for a UI.
  - An **ACL in front of a complex context** collects data from many upstream contexts, so the
    context deals with business complexity instead of integration complexity.

## Outbox

Aggregates communicate through domain events, but **how do you publish them safely?**

**Two tempting but broken approaches:**
1. *Publish from inside the aggregate.* The event goes out **before** the state is saved. If the
   save then fails, you've announced something that never happened, and you can't take it back.
2. *Publish from the application layer after saving.* Better, but if the process crashes or the
   bus is down between "saved" and "published", the event is **lost forever**.

**The outbox pattern:**
1. Save the aggregate's new state **and** its new events in **one atomic transaction**.
2. A **relay** reads the unpublished events.
3. The relay publishes them to the bus.
4. Then it marks them published, or deletes them.

- **Relational database:** a dedicated outbox table, written in the same transaction.
- **Document store without multi-document transactions:** embed an `outbox` array inside the aggregate's own document.
- **How the relay finds events:**
  - **Pull (polling publisher):** keep querying for unpublished rows, with good indexes.
  - **Push (transaction log tailing):** react to the database's change feed or change streams.
- **Delivery is at least once.** A crash after publishing but before marking means a resend, so
  **subscribers must handle duplicates**.

## Saga

The rule from Chapter 6 still applies: one aggregate per transaction. So how do you run a business
process that spans several aggregates or contexts?

A **saga** is a **long-running process**: long in *transactions*, not necessarily in time (it can
take seconds or months). It **listens for events** and **issues commands** in response. If a step
fails, it issues **compensating actions** to put things back in order.

*Example, a marketplace order:*
- `OrderPlaced` → command `ReserveStock` to the warehouse
- `StockReserved` → command `ChargePayment` to billing
- `PaymentDeclined` → **compensate**: `ReleaseStock`, then `CancelOrder`

- **Simple sagas** just map events to commands and need no state.
- **Stateful sagas** track what they've done so they know what to undo. You can build one as an
  event-sourced aggregate, and **send its commands through an outbox-style relay** (record a
  "command issued" event, and let the relay execute it), so a crash can't lose a step.
- **Consistency is eventual.** Only the data *inside* one aggregate is strongly consistent. If you
  keep needing sagas to keep data in step that really has to be consistent together, the
  aggregate boundaries are probably wrong.

## Process manager

Similar machinery, but a different purpose.

| | Saga | Process manager |
|---|---|---|
| Flow | Linear: event → command matching | **Branching business logic** decides the next step |
| How it starts | Implicitly, when a trigger event appears | **Explicitly**, because the process is a thing in its own right |
| State | Optional | Always has its own ID and state |

**Rule of thumb:** if your "saga" is full of `if/else` deciding what to do next, it's a process manager.

*Example, onboarding a new employee:* create accounts, then wait for the manager's equipment choice.
If the equipment isn't in stock, order it and adjust the start date. Then book the induction
session. If HR rejects the documents, pause everything and notify the recruiter. No single event
"owns" this flow; the onboarding *is* the process.

Process managers are usually built as aggregates (state-based or event-sourced) that subscribe to
the relevant events and record "command issued" events for an outbox relay to execute.

## Check yourself

1. Which integration patterns need translation logic: conformist, ACL, OHS?
2. What is the outbox for?
3. Is the outbox only useful for message buses?
4. Which are true? (a) a process manager is started explicitly, a saga by an event; (b) a process
   manager never stores state; (c) sagas require event-sourced participants; (d) process managers
   suit complex workflows.

<details><summary>Answers</summary>

1. ACL and OHS.
2. To publish messages reliably.
3. No. Any "do X after commit" side effect can use it, such as saga or process-manager commands.
4. (a) and (d).

</details>
