Using MongoDB change streams for event sourcing.
Instruction: Explain how you would use MongoDB change streams to implement an event sourcing architecture.
Updated
Official answer
Event sourcing stores domain events as the authoritative history and derives current state by replaying them. Watching mutations to a current-state collection is change data capture; it does not automatically recover the original business intent or create a complete permanent event history.
For an event-sourced design, append an immutable event with aggregate identity, event identity, sequence/version, type and payload. Use appropriate uniqueness and concurrency controls so two commands cannot both append the same expected aggregate version. Define schema evolution and deterministic replay behavior.
A MongoDB change stream can notify projection workers of new event documents. Persist checkpoints after durable processing and make projection updates idempotent. A crash can lead to replay, and a slow consumer can lose the ability to resume after oplog history expires. Rebuild from the authoritative event collection when necessary; do not rely on the stream as infinite retention.
If the application instead owns mutable state, a transactional outbox can record intended domain events alongside state changes. Relaying that outbox still requires deduplication and reconciliation. Adding Kafka does not automatically eliminate gaps or create exactly-once external effects.
Test concurrent commands, duplicate delivery, projection rebuilds and schema changes. Keep authorization, sensitive-data retention and operational costs explicit before choosing event sourcing.