ADR-088 and ADR-089 partially supersede this ADR's one-projector-per-read-model structure for related Chatto content models. The event authority, process-local ownership, ordered replay, and aggregate OCC decisions remain in effect.
Context
ADR-006 established CRUD + audit log: KV buckets hold current state, streams capture history. As the codebase has grown on that pattern, several costs have become hard to ignore:
- Subject-index RAM. ADR-026 plus the per-event-ID subject pattern (
server.room.{kind}.{roomId}.msg.{eventId}) gives us O(1) message lookups viaGetLastMsgForSubject, but NATS keeps its per-subject index in memory. Subject cardinality scales 1:1 with message count. On busy instances this dominates RAM and grows without bound. - Migration ergonomics. Each schema change against a KV bucket needs a bespoke boot migration (
BackfillAttachmentRecords,DropLegacyAttachmentRecords,BackfillAttachmentLocatorData, …). KV gives us neither schema tooling nor a replay primitive; every change is its own one-off script. - A zoo of write disciplines. Best-effort publish for some events, store-then-publish for messages, OCC helpers for others, atomic-claim KVs for uniqueness — each pattern is locally reasonable but there is no shared write discipline across the codebase.
- The audit log is secondary. Stream retention can trim history. The audit log isn't really primary; it's a derived signal that happens to be persistent.
Event sourcing inverts the relationship: events are the truth, state is derived. The motivations match the costs above:
- Subject cardinality drops to O(aggregates). One subject per room, one per user, one per RBAC namespace — not one per message.
- Schema changes become projection rebuilds. Drop the projection, replay the stream, done. No boot migration code.
- One write model. Facts append to their aggregate subject; a write that depends on state carries an OCC guard.
- The audit log is the data, by construction. Not a side effect.
This is a large change. The migration is per-aggregate and phased; that strategy is the subject of ADR-035. The shape of the event log itself — single stream vs. many — is the subject of ADR-034. This ADR commits to the model.
ADR-073 later names the repository-wide application pattern built around this decision the Loom Architecture.
Decision
Adopt event sourcing as the storage pattern for domain state.
- The primary event stream is the source of domain truth. Domain mutations
are expressed as events appended to the single
EVTJetStream stream (see ADR-034). Current domain state for any read is derived from these events. Purpose-bounded secondary logs may record the lifecycle of finite derived resources when their retention and recovery contract differs from permanent domain history. They must derive from existing domain facts, must not become an alternate authority for those facts, and require an explicit decision;NOTIFICATIONSin ADR-076 is the first such log. - Projections are derived state. Each aggregate type has one or more projections rebuilt from the event stream that serve reads. Most are in-memory Go data structures maintained independently by every Chatto process. ADR-054 keeps projection persistence optional and permits disposable locally checkpointed projections, such as a disk-backed search index, while preserving
EVTas the reconstruction authority. - Decisions use optimistic concurrency control. A write whose records or permission depend on state carries an OCC guard: the expected last sequence of its subject, an aggregate filter, or the stream. This makes uniqueness claims and other invariants expressible as ordered subject sequences, and a conflict reruns the decision. A fact whose records and permission do not depend on state that a concurrent write can change publishes without a guard through
AppendEventuallyor theUnguardedmutation boundary. A guard could not change the outcome of such a fact, but NATS stores the guard headers with every message, and a guard on a shared subject serializes unrelated writers. Examples are audit facts, asset creation facts, and notification lifecycle facts. Last-writer-wins commands, such as room archive, unarchive, and unban, also publish without a guard: their state read only rejects a missing target or skips a no-op, and request-time authorization applies (ADR-087). A check-then-write that must not repeat, such as "record one ended fact for this call", is a decision and keeps its guard. Stable event IDs and JetStream message de-duplication keep retries of unguarded facts idempotent. When a write decision comes from projection state, the owning projection exposes a snapshot containing both the derived state and the applied stream sequence for the same OCC subject/filter; conflict retries wait for catch-up and decide from a fresh snapshot. - Read-your-writes via stream positions. Successful publish returns a stream sequence number, and the writer already knows the subject or subject filter it published/guarded against. Domain code wraps those into an
events.StreamPositionand asks the relevant projection owner to wait until its projector reaches that position. The projector verifies both sides of the contract: the sequence must belong to the supplied subject/filter, and the projection must consume the sequence's actual subject. Waiting on a raw sequence that the projection will never consume is a programming error, not a timeout-shaped control path. Reads from other actors see the new state on the projection's natural consumer cadence — typically sub-millisecond, never coordinated. - Restore mechanisms are optional capabilities. The base projection contract owns logical subjects and ordered event application. A projection may implement neither persistence mechanism and cold-replay every time. ADR-050 defines optional portable encrypted snapshots for eligible in-memory projections, while ADR-054 defines the opt-in capability boundary, including projection-owned local checkpoints. Neither changes the authority of
EVT. - Runtime state stays out. Presence, typing indicators, link-preview cache, auth tokens, image cache, and similar TTL-driven or content-addressed state are not part of the event log. Durable latest-value runtime state uses
RUNTIME_STATEper ADR-036; purely transient state can remain memory-backed, and binary/object data stays in object stores. Security-relevant workflow facts may still be appended to EVT for audit, but only as safe facts without raw tokens, links, passwords, auth codes, or raw IP addresses. - A thin internal Go package owns the abstractions. No third-party event-sourcing framework is adopted. The package exposes guarded and unguarded append methods,
StreamPosition, a projection interface, and aProjector(consumer + apply loop). Estimated size: ~1000–1500 lines, fully under our control.
This ADR supersedes ADR-006.
Consequences
- Subject-index RAM stops scaling with messages. The dominant memory cost on busy instances goes away. This is the most measurable single win.
- Schema changes become projection rebuilds. Adding a field, changing a derivation, computing a new index — all become "drop projection, replay stream." No boot migration code, no KV backfills. The maintenance surface from ADR-006's CRUD model collapses.
- One write model. A write publishes facts to their aggregate subject and returns their stream sequences. It carries an OCC guard when it depends on state. This replaces today's variety of KV writes, best-effort publishes, OCC helpers, and atomic claims.
- OCC on decisions has a real cost. Every guarded write must read the projection (or know the subject is fresh) to know the expected sequence. For high-contention aggregates this can mean retry loops on conflict. We accept this as the cost of removing every "did I race?" question from decisions. Facts that do not depend on state avoid this cost.
- Read-your-writes is per-process. A writer on process A waits for A's projection consumer to advance; a reader on process B sees the change on B's natural cadence. Cross-process consistency is eventual. In practice the delay is sub-millisecond and bounded by NATS Core latency. API responses from two processes can momentarily disagree; we treat this as acceptable for chat.
- Startup cost grows with stream length. Without a usable compatible snapshot, a long-running instance pays projection-rebuild time on restart. ADR-050 permits snapshots only as an optional accelerator, so complete replay remains the correctness baseline and fallback.
- Migration is per-aggregate and phased. See ADR-035. Big-bang migration is not feasible. The two systems coexist for the duration of the transition.
- Ops story shifts. Operators back up one primary domain stream instead of
many domain KV buckets. Restore of domain state is "replay
EVT." A purpose-bounded secondary log can add another coordinated backup resource when losing its finite user-visible lifecycle would be incorrect; ADR-076 defines that exception for notifications. Long-term domain storage and retention remain out of scope here. - Crypto-shredding model survives, with a deliberate ES exception for body payloads. ADR-007 per-user encryption applies to event payloads; deleting a user's key still renders their messages unreadable. The body/event split in ADR-011 now lives inside EVT as private body payload events plus public message facts, removing the old body-side-table coordination problem for migrated messages. Public message facts (
MessagePostedEvent,MessageEditedEvent,MessageRetractedEvent) remain immutable event-sourced history; privateMessageBodyEventpayload facts are retention-controlled content carriers and may be securely deleted to satisfy message deletion semantics. This is an explicit, narrow departure from strict event-sourcing immutability: a cold replay after deletion preserves the durable conversation facts but cannot reconstruct deleted body material. If we later introduce per-message DEKs in a separate non-backed-up key store, message deletion can shred that per-message key instead of deletingMessageBodyEvent, allowing these payload events to become immutable again and better align with textbook ES practice. - No third-party framework dependency. Trade: we own the abstractions and their evolution. Read both
looplab/eventhorizonandblinkinglight/beefor design vocabulary, but ship our own minimal package shaped to Chatto's needs. - Projection-owned consumers and readiness. Each
Projectorowns one NATSOrderedConsumerfor its lifetime, including snapshot restore, startup replay, and live consumption. This duplicates some JetStream delivery and protobuf decoding compared with process-local shared fanout, but isolates replay frontiers and failures and gives colocated and future out-of-process projections one lifecycle model.ChattoCorestill waits for every registered projection to become current before completing boot. - Projection subject declarations have separate roles. A projection's
Subjects()value is the logical consumption and readiness contract used by waits, live delivery, diagnostics, and tests. Optional replay subjects are a projection-owned physical consumer concern and may be broader for delivery efficiency or legacy compatibility. Broad filters remain intentional when a projection's snapshot exposes an OCC token for the full aggregate tail; focused filters are appropriate for stable derived indexes over selected event families. - Stable stream sequences are a framework concern. Projection
Applymethods receive the global stream sequence from the projector framework. Projections should not parse JetStream metadata or use consumer sequence numbers; reconnect replay, live delivery readiness, and projection-backed OCC all depend on the same stable stream sequence vocabulary. - Replay idempotency state is released when history permits it. Projections that need envelope-ID idempotency keep an event-ID set while replaying the startup target. When replay completes, a projection whose history contained no duplicate IDs releases that set and uses the monotonic EVT stream sequence as a constant-size steady-state guard. If replay observes a duplicate ID, that projection retains its set and first-event-wins behavior for compatibility with the existing history. This relies on the globally unique event IDs and publish deduplication established by ADR-026, while avoiding lifetime memory growth for conforming histories.
Out of scope for this ADR
- The shape of the event log itself (one stream vs. many) — see ADR-034.
- The migration strategy from today's CRUD+log model — see ADR-035.
- The runtime-state storage boundary — see ADR-036.
- Snapshot persistence and projection bootstrapping — ADR-050 defines optional encrypted snapshots, while ADR-054 defines optional persistence capabilities and local checkpoint replay frontiers.
- Long-term retention, archival, cold storage — also deferred.
- Multi-process coordination beyond "every process maintains its own projection." If we ever want a single authoritative projection across processes, that is a separate decision.