Records Architecture decision

ADR-056

Incubate an Extractable NATS Event-Sourcing Framework

Accepted Decided 2026-07-30 Source file
Updated
2026-10-08

ADR-088 extends the shared framework with prepared reducers, coordinated components, one apply barrier, and component-shaped projection snapshots. The framework remains application-neutral and independently versioned.

The framework has one projection snapshot shape. Every snapshot contains components, and each component contains parts. A single-payload projection is one component with one part. The projector therefore has one configuration, one capture, and one restore path. An application can store single-payload snapshots in a different format. Chatto keeps its single-generation format for these projections and its cohort format for ServerContentView.

KeyValue and the retried resource provisioning moved from pkg/events to the separate shared module pkg/jetstreamutil, together with the OCC conflict classifier from Chatto's internal/jetstreamutil. They are JetStream client helpers, not event-sourcing mechanics, and both applications can use them without the event framework. pkg/events keeps a private copy of the classifier so that it does not depend on another module. The sections below that describe KeyValue now describe jetstreamutil.KeyValue.

Context

ADR-033 deliberately chose a small internal Go package instead of a third-party event-sourcing framework. That package now owns proven NATS JetStream mechanics for OCC, ordered projection replay, read-your-writes barriers, failure propagation, and optional restore capabilities.

ADR-073 later names the wider application pattern around this framework the Loom Architecture. This ADR continues to define the narrower package boundary and current ownership split.

Chatto's composition layer has also accumulated application policy around those mechanics: stable diagnostic keys, display names, memory estimates, snapshot eligibility, domain model ownership, and the concrete evtv1.Event envelope. Combining those concerns into a richer Chatto-specific runtime abstraction would make today's wiring shorter but make a future standalone library harder to identify and extract.

Projection-aware models additionally received projections and projectors as separate constructor arguments. Nothing in those signatures proved that the projector owned the supplied projection, so a wiring mistake could combine a read model with another projection's replay frontier.

Decision

Treat the nested pkg/events/ module, imported as github.com/chattocorp/chatto/pkg/events, as the incubator for a small Event Sourcing on NATS framework that may later move to a standalone repository.

Framework-owned responsibilities are:

  • optional ID interning and compact string storage through the standard-library-only intern subpackage; applications retain table scope, sharing, and lifetime;
  • opaque-byte event-log reads, OCC-guarded publishing with an explicit unguarded path for state-independent facts, and atomic append mechanics, including duplicate-aware results and optional per-record broker TTL;
  • exact-sequence stream-message reads with bounded concurrency and an optional process-local cache with sliding idle expiry;
  • stream positions and projection readiness barriers;
  • ordered consumer, replay, startup batching, and failure lifecycles;
  • bounded durable pull-worker execution over application-configured consumers, including progress heartbeats, confirmed acknowledgement, delayed retry, and poison-delivery termination;
  • optional snapshot and local-checkpoint capability hooks that bind persisted state to an opaque application-supplied stream identity; and
  • a typed ProjectionHandle that keeps a projection with the exact projector constructed for it.

Chatto-owned responsibilities remain:

  • the concrete event envelope, event vocabulary, subjects, and aggregate choices;
  • domain projections, services, authorization, and response assembly;
  • stable registration keys, display names, admin memory estimates, and diagnostic inventory;
  • stream identity discovery, metadata naming, format, and validation;
  • durable consumer names, stream selection, subject filters, delivery policy, domain decoding, idempotency, and terminal-state decisions;
  • snapshot enablement, repository, encryption, retention, and worker policy; and
  • runtime composition in ChattoCore.

evtstream.NewProjectionHandle is Chatto's normal construction path over events.NewDecodedProjectionHandle. Code adapting an already-created projector may use evtstream.BindProjectionHandle, which rejects a projector built for a different projection. Both constructors require pointer projection implementations so the projector and read side cannot receive separate value copies. Projection-aware models consume handles rather than parallel projection/projector arguments.

EncodedEventLog is the envelope-neutral storage boundary. It owns NATS message-ID deduplication, OCC headers, atomic batches, stream positions, and opaque record reads. A record may request physical broker expiry when the application-owned stream enables per-message TTL, but semantic expiry remains application policy enforced by projections and APIs. Atomic batches report a typed duplicate-ID failure so an application can fall back to idempotent single-record appends without losing a committed prefix.

StreamMessageReader is the envelope-neutral exact-read boundary. It binds stream sequences to one stream handle, limits concurrent broker reads, removes duplicate sequences in one request, and preserves request order. Its optional cache stores copied opaque bytes, not decoded application objects. Successful access extends an entry's idle lifetime. Failed reads are not cached. The reader supplies explicit sequence invalidation and complete clearing, and its run lifecycle removes expired entries. The cache is disposable and is not a projection, checkpoint, snapshot, or source of domain truth.

The framework uses github.com/jellydator/ttlcache/v3 for synchronized cache storage, sliding expiry, and expired-entry deletion. It keeps stream validation, read limits, byte copying, invalidation fencing, and lifecycle scheduling in the framework because those rules belong to the exact-read contract. This focused dependency replaces local cache storage and expiry mechanics.

TypedEventLog[E] is the shared mechanical adapter over that boundary, extracted once Chatto and Authling had duplicated the same encode, batch, mutation, and paged-read plumbing in their per-application publishers. It maps one application event type through application-supplied encoder and decoder functions; applications keep their envelope codecs, subjects, semantic validation, aggregate command methods, and composition. This extraction follows the two-consumer rule above rather than a desire to shorten one application's wiring.

jetstreamutil.KeyValue (formerly events.KeyValue) is the consistent-read boundary for key-value buckets. It wraps a bucket handle and keeps its interface. JetStream serves the bucket's Get through a direct get when the bucket allows it. Any replica can then answer, and a replica that lags behind a committed write returns an older revision or no entry. Chatto observed this failure: a refresh grant read its session again right after a committed rotation and rejected the valid credential. KeyValue.Get and GetRevision therefore read through the stream leader. Latest reads the newest entry for a filter through the leader, including removal markers. GetAnyReplica is the bucket's own read, for hot paths that accept a result quickly and decide a negative result again with Get. UpdateWithTTL adds the revision-checked TTL update that the bucket API does not have. Chatto and Authling bind all of their buckets through this type. Applications keep bucket names, configuration, value codecs, and the choice of which hot reads accept an older revision.

The framework is configured with a concrete JetStream stream; it does not assume that an application has only one event log or that the log is named EVT. Chatto's evtstream.Publisher is the typed adapter that validates evtv1.Event, uses its stable ID, and protobuf-encodes or decodes at the primary domain boundary. internal/notificationstream independently adapts the bounded notificationv1.NotificationEvent envelope and NOTIFICATIONS stream through the same mechanics. Both adapters own their application-specific subjects, identities, validation, and retention policy.

NewDecodedProjector is the matching envelope-neutral replay boundary. Applications supply an EventDecoder[E] and EventProjection[E]; the framework retains ordered consumption, subject filtering, startup batching, readiness, snapshots, checkpoints, and failure handling. internal/evtstream owns Chatto's NewProjector, Projection, SequencedEvent, and publisher APIs as specializations over evtv1.Event and its unchanged protobuf codec. The events module has no production dependency on Chatto protobufs or subject policy.

DurableWorker is the matching envelope-neutral effect-execution boundary. Applications supply an already configured durable JetStream pull consumer and an opaque-byte handler. The framework bounds local concurrency and owns message heartbeats, acknowledgement, retry, termination, and shutdown handoff. The application still defines what constitutes valid input, successful completion, and an idempotent retry. Transient pull failures are retried so an embedded worker does not turn a recoverable broker restart into a process failure. If the supplied consumer is deleted or no longer exists, the worker returns an error instead of retrying a stale handle forever. Recreating, replacing, or retiring that application-owned consumer remains outside the framework. Handlers must honor cancellation: the framework first cancels any outstanding pull, then stops heartbeats and schedules active-delivery redelivery just beyond the maximum pull lifetime so an orphaned server-side request cannot reclaim the handoff. It retains lifecycle ownership until those handlers return. Chatto's asset-processing runtime unit was the first production consumer and retains its existing durable consumer contract. The notification materializer and notification Alert worker now exercise the same framework against EVT and NOTIFICATIONS, respectively.

Chatto owns a versioned incarnation format for each application event log: chatto.evt.incarnation through internal/evtstream and chatto.notifications.incarnation through internal/notificationstream. Composition passes the matching resolver into each projector's snapshot and checkpoint configuration. At restore time the projector invokes it with the same fresh StreamInfo used for sequence bounds, preventing an old identity from being combined with a recreated stream's bounds. The projector and snapshot repository require only a non-empty opaque result and never impose a Chatto metadata key or identity syntax. Snapshot capture carries the identity bound to that projector run alongside its state and cutoff; application publication does not maintain a second identity value.

The framework is exposed as the independently versioned incubation module github.com/chattocorp/chatto/pkg/events, so code outside Chatto's module can compile and test against the same exported surface Chatto uses. The module remains pre-1.0 and does not promise API stability. Its repository path is pkg/events/, and its release tags use pkg/events/v<version>. ADR-059 licenses the complete shared module under Apache-2.0 without changing its pre-1.0 stability status. A future repository move should preserve the module identity unless a deliberate rename justifies an import migration.

Chatto declares the module dependency explicitly and uses a repository-local replace while the framework is co-developed here. This keeps GOWORK=off builds honest about the module boundary without requiring a framework release before an atomic Chatto change can compile. Consumers outside this repository use normal tagged module versions; the local replacement is not part of the framework module itself.

Extraction will happen only when concrete framework users show the smallest useful public API. An external-package consumer contract acts as the first such user: it owns a non-Chatto JSON envelope, subject policy, typed event-log adapter, and projection while exercising only exported framework APIs. Future generic surface should be justified by friction in this kind of consumer rather than by a desire to shorten Chatto-specific wiring. Authling is the first concrete second application. It can drive incremental extraction when it needs a proven mechanic through this public seam, without importing Chatto's internal packages.

Consequences

Projection ownership and replay readiness can no longer be mismatched silently in normal wiring. Model constructors are shorter, and the reusable lifecycle unit is visible both in the core runtime and the independently runnable bundled search provider.

New event-sourcing mechanics should be evaluated for the pkg/events/ module; new Chatto policy should stay in internal/core or the owning runtime unit. This creates a reviewable extraction boundary without forcing premature API stability or generic abstractions.

Durable workers can share transport and process-lifecycle mechanics without turning product effects into a framework-owned business outbox. Because the consumer configuration remains application-owned, rolling-deployment policy and persisted consumer names stay visible at the composition boundary. ADR-069 defines the explicit application-owned lifecycle and retirement policy for those durable resources.

The handle adds one small generic API and an identity check for adapting existing projectors. It intentionally does not absorb registration metadata or snapshot policy, so some application composition remains explicit.

Extraction still requires deliberate work. The reusable module does not depend on any Chatto production package: its production imports are limited to the Go standard library, nats.go, ttlcache/v3, and golang.org/x/sync/errgroup, the reviewed allowlist in pkg/events/AGENTS.md. It privately classifies the JetStream wrong-last-sequence errors needed to preserve ErrConflict rather than depending on Chatto's application-wide JetStream helpers. Generic projection replay can use another application envelope or another log in the same application without changing the ordered lifecycle, while Chatto's typed adapters keep each storage contract explicit.

The external consumer contract proves live OCC publication, read-your-writes waiting, conflict reporting, projector shutdown, and cold replay through the same public surface. It is an executable extraction seam, not a second production event model or a promise that the current package API is stable.

The framework test suite is portable with the module: it owns its in-process JetStream fixture and no-op logger instead of borrowing Chatto test helpers. Tests add only nats-server/v2 to the dependencies allowed in production. The repository workspace composes the module for local development, while mise test-events also tests it with GOWORK=off.

ADR-057 temporarily places Authling in the same repository so it can drive this extraction without making either product part of the other.

Records that name this record

Esc