CQRS, lightweight event sourcing and outbox
Write side
A command handler loads the aggregate current state, validates, produces domain events, then commits through
eventstore.Store.Save in one MongoDB transaction:
- append the events to the
eventscollection (aggregate_type,aggregate_id,version,type,data,meta,occurred_at); a unique index on (aggregate_id,version) gives optimistic concurrency (ErrConcurrency→ HTTP 409concurrent_modification); - replace the current-state document (it acts as snapshot and is what queries read);
- insert the events and the audit records into the
outboxcollection.
Configuration-like data (statuses, training types, mandates, terms, settings, login history) uses plain CRUD
in a transaction that also writes audit records to the outbox (store.Tx / store.Audited).
Outbox relay
outbox.NewRelay runs in every writing service. Only the replica holding the relay lease publishes, so
order is preserved; it polls the outbox collection every 250 ms, publishes with kafkax.Producer and deletes
what was acknowledged. The topic of an event is derived from its type (outbox.TopicOf: members.member.created
→ members.member.v1); audit records go to audit.records.v1.
docs/specs/architecture.md describes the relay as a change stream with resume token; the implementation
polls the outbox collection under a lease.
Read side
- Simple reads use current-state documents with an index for every query path, read preference
secondaryPreferred(mongox.Connect) except read-after-write paths (mongox.Primary). - Cross-aggregate or cross-service views are projections built from Kafka events (e.g. the role history in members, login history in authz), rebuildable by replay.
Soft delete and background jobs
- Soft delete uses
deleted_at/purge_atfields; queries usemongox.NotDeleted. - Periodic jobs that must run once (member purge, membership renewal) use
pkg/leaseso that a single replica runs them.