# Modeling the Dimension of Time
> **In one sentence:** instead of storing only *where things are now*, store *everything that
> happened* and work out the current state (and any other view) from that history.

The **event-sourced domain model** uses the same building blocks as Chapter 6: value objects,
aggregates and domain events. The only difference is **how aggregate state is persisted**.

## Event sourcing

### What a state table hides

Picture a `shipments` table with `id`, `status`, `address`, `eta` and `updated_at`. You can tell
each parcel's current status, but you can't answer:

- How many delivery attempts happened before it was delivered?
- How often did customers change the address after dispatch?
- Which depots cause most of the delays?

The table holds the latest **state** but has lost the **story**. Those missing answers are often
exactly what the business needs to improve a core process.

### Store the story

Event sourcing **adds time to the data model**. Every change to an aggregate is saved as an event:

```json
[
  { "seq": 0, "type": "shipment-registered", "address": "12 Elm St", "at": "..." },
  { "seq": 1, "type": "dispatched",          "depot": "North",       "at": "..." },
  { "seq": 2, "type": "delivery-attempted",  "result": "no-one-home", "at": "..." },
  { "seq": 3, "type": "address-changed",     "address": "Locker 7",  "at": "..." },
  { "seq": 4, "type": "delivered",                                   "at": "..." }
]
```

**Projection** means rebuilding a state by applying events in order:

```python
class ShipmentState:
    def apply(self, e):
        match e.type:
            case "shipment-registered": self.status, self.address = "NEW", e.address
            case "dispatched":          self.status = "IN_TRANSIT"
            case "delivery-attempted":  self.attempts = getattr(self, "attempts", 0) + 1
            case "address-changed":     self.address = e.address
            case "delivered":           self.status = "DELIVERED"
        self.version = e.seq
```

- **Time travel:** apply only the first *n* events to see the state at any point in the past.
- **Many views from one history:** a *search* projection that keeps every address ever used, an
  *analytics* projection that counts attempts per depot, and new projections added later from
  the same events. (Persisting these views is what CQRS in Chapter 8 is for.)

### Source of truth and event store

- The **events** are the source of truth, the only strongly consistent data.
- They live in an **event store**: **append-only**, with no updates or deletes (apart from rare
  cases such as migrations).
- At minimum it needs two operations: **fetch all events for an aggregate ID**, and **append new
  events with an expected version**. If the stored version moved on, it raises a concurrency
  error, which gives you optimistic concurrency.
- It isn't a new idea: an accounting ledger is an append-only log, and a balance is a projection of it.

## Event-sourced domain model

A regular domain model stores state and emits *some* events. An event-sourced one expresses
**every** state change as an event. Each operation follows the same four steps:

1. **Load** the aggregate's events.
2. **Rehydrate** by projecting them into an in-memory state used for decisions.
3. **Run the command**. The logic doesn't set fields directly; it **creates new events** and
   applies them to its own state.
4. **Append** the new events to the store (with the expected version).

*Naming note:* event sourcing can be used without the domain model, so "event-sourced domain model"
spells out that you're using both together.

## Trade-offs

**Benefits**
- **Time travel and retroactive debugging:** reproduce the exact state at the moment a bug happened.
- **Deep insight:** new projections can answer questions nobody had thought of yet, which is
  valuable for optimizing core subdomains.
- **Audit log for free**, and a strongly consistent one. It's great where regulation or money flows demand traceability.
- **Smarter concurrency:** on a conflict you can inspect *which* events were added in the meantime
  and decide whether they actually clash with your change.

**Costs**
- **Learning curve:** a very different way of thinking about data, so the team needs training.
- **Evolving events is hard:** events are immutable, so changing their shape is a discipline of its own (event versioning).
- **More moving parts** in the architecture (see CQRS).

Use it when the business really benefits, not by default (Chapter 10 gives heuristics).

## FAQ

- **Won't replaying events get slow?** Measure it. Most aggregates live for well under a hundred
  events, and replay usually only hurts at around ten thousand or more. If it does, add **snapshots**:
  cache a projected state and replay only the events after it. That's an optimization that needs
  a justification. First check whether the aggregate is simply too big.
- **Does it scale?** Yes. Operations always target one aggregate, so you can **shard the store by aggregate ID**.
- **What about deleting personal data (for example GDPR)?** Use the **forgettable payload** pattern
  (also called crypto-shredding): encrypt sensitive fields with a key per aggregate held in a
  separate key store, and delete the key to make the data unreadable.
- **Why not just write logs to a file?** That's two separate writes (database and file) without a
  shared transaction, so they drift apart.
- **Why not a log table in the same transaction?** Someone will eventually forget to write the log
  row, and since the state stays the source of truth, the log format decays.
- **Why not a database trigger that copies rows to a history table?** It records *what* changed but
  not *why*, and that business intent is what makes new projections possible.

## Check yourself

1. How do domain events relate to value objects?
2. How many projections can you build from one aggregate's events?
3. True or false: only event-sourced aggregates emit domain events.
4. In a support-ticket product, which fits event sourcing best: the ticket lifecycle, the admin screens, or staff rotas?

<details><summary>Answers</summary>

1. Events use value objects to describe what happened.
2. As many as you like, including new ones added later.
3. False. Both kinds emit them, but only event-sourced ones use them as the source of truth (and record *every* change).
4. The ticket lifecycle, because it's complex, core and benefits from history.

</details>
