Event Sourcing
Event sourcing in Go — state as a fold of events, the event store and optimistic concurrency, aggregates, snapshots, event versioning, and process managers.
13 questions
JuniorTheoryCommonWhat is event sourcing, and how is an entity's current state obtained?
What is event sourcing, and how is an entity's current state obtained?
Instead of overwriting a row, the system stores every change as an immutable event in an append-only log, and that log is the source of truth. Current state is rebuilt by replaying the entity's events in order, applying each to an empty state.
Common mistakes
- ✗Treating the event log as an audit side table next to the real state rather than as the state itself
- ✗Storing commands instead of facts, so a replay re-runs validation and can produce a different result
- ✗Thinking events can be edited or deleted once a newer state is known
Follow-up questions
- →Why are events named in the past tense, like
MoneyDeposited? - →How would you answer a query like 'all accounts with a negative balance' in this model?
JuniorTheoryCommonDoes event sourcing require the read/write split pattern CQRS, and why are they often paired?
Does event sourcing require the read/write split pattern CQRS, and why are they often paired?
Neither requires the other: CQRS works over a CRUD database, and an event-sourced service can answer queries by replaying a stream. They pair because an event log is poor at ad-hoc queries, so projections build read models from events — the CQRS read side.
Common mistakes
- ✗Believing event sourcing forces a separate read database from day one
- ✗Thinking CQRS needs an event log to feed its read models
Follow-up questions
- →When would you answer a query by replaying one stream instead of reading a projection?
- →What does the read side lose when projections lag behind the event log?
JuniorTheoryOccasionalHow is a domain aggregate loaded from its stored events in a Go service?
How is a domain aggregate loaded from its stored events in a Go service?
Read the aggregate's stream ordered by version, create a zero-value aggregate and call Apply for each event in that order. Apply only mutates fields, so after the last event the struct holds the current state and the version for the next append.
Common mistakes
- ✗Validating events again during load and skipping the ones current rules reject
- ✗Ignoring the version order of the stream
- ✗Losing the loaded version, so the next append cannot detect a concurrent write
Follow-up questions
- →Why must
Applynever return an error? - →What happens to load time as a stream grows to millions of events?
JuniorTheoryOccasionalWhy is an event store append-only, and what is a stream in it?
Why is an event store append-only, and what is a stream in it?
Events are recorded facts, so they are never updated or deleted — a change is a new event, which keeps history replayable and auditable. A stream is the ordered sequence of one aggregate's events, identified by a stream id and numbered by version.
Common mistakes
- ✗Fixing a wrong event with UPDATE instead of appending a correcting event
- ✗Confusing a per-aggregate stream with a broker topic grouped by event type
Follow-up questions
- →How do you correct a mistake if an event can never be changed?
- →What is the store's global position used for, compared with a stream version?
MiddleCodeOccasionalImplement Apply and Load for an event-sourced bank account
Implement Apply and Load for an event-sourced bank account
Apply uses a type switch and only mutates state: Opened sets the id, owner and open flag, Deposited adds, Withdrawn subtracts, anything else is ignored. Load starts from a zero Account, applies the history in order and counts it into Version.
Common mistakes
- ✗Checking business rules inside
Applyand skipping events that break them - ✗Calling external services or
time.Now()fromApply, making replay non-deterministic - ✗Re-running commands during load instead of applying the recorded events
Follow-up questions
- →Where would the insufficient-funds check live if not in
Apply? - →How would you collect the new events a command produces before saving them?
MiddleTheoryOccasionalTwo commands append to the same event stream at once. How does the store keep it consistent?
Two commands append to the same event stream at once. How does the store keep it consistent?
Each append carries the expected version — the one the command saw at load. A unique (stream_id, version) constraint or a version check rejects the second writer, which reloads the aggregate, re-validates the command on the new state and retries.
Common mistakes
- ✗Retrying the same events with a bumped version instead of re-running the command
- ✗Locking the whole stream or table instead of checking an expected version
- ✗Assuming events never conflict, so invariants are checked only on the read side
Follow-up questions
- →How would you surface a version conflict to an HTTP client — a 409 or a silent retry?
- →Why can a per-stream version not order events across different streams?
MiddleTheoryOccasionalWhen are snapshots worth adding to an event-sourced aggregate, and how does loading change?
When are snapshots worth adding to an event-sourced aggregate, and how does loading change?
When long streams make replay measurably too slow — a load-latency number, not a guess. A snapshot stores the serialized state with the version of the last event it covers; loading reads the latest snapshot, then applies only events with a higher version.
Common mistakes
- ✗Deleting events once a snapshot covers them
- ✗Adding snapshots by default instead of after measuring slow loads
- ✗Selecting the tail by timestamp instead of by version
Follow-up questions
- →Why is it safe to delete every snapshot and rebuild them later?
- →What does a stream with millions of events tell you about the domain model?
MiddleTheoryOccasionalAn event's schema must change, but old events are stored forever. How do you evolve it?
An event's schema must change, but old events are stored forever. How do you evolve it?
Never rewrite history. An added field needs only a default for events that lack it; a breaking change gets a schema version, and an upcaster chain converts old payloads to the current shape on read, before Apply, so the aggregate knows one shape.
Common mistakes
- ✗Rewriting stored events in place instead of converting them on read
- ✗Spreading version branches across
Applyinstead of upcasting once before it - ✗Decoding strictly, so a newly added field breaks older readers
Follow-up questions
- →When is a new event type better than a new version of the old one?
- →How do you test that an upcaster chain still reads the oldest events?
SeniorDebuggingOccasionalAn event-sourced account resends its welcome email on every command — find and fix the bug
An event-sourced account resends its welcome email on every command — find and fix the bug
Apply runs on every load and replay, so Opened triggers the email each time the account is rebuilt. Keep Apply pure: Handle decides by emitting Opened, and a separate subscriber sends the email once per event, deduplicating by event id.
Common mistakes
- ✗Guarding the effect with an in-memory flag that resets on the next load
- ✗Making the effect asynchronous instead of moving it out of
Apply - ✗Sending from a subscriber without deduplication under at-least-once delivery
Follow-up questions
- →Why must the subscriber deduplicate even though each event is stored only once?
- →Where would a payment-provider call go if its result must become an event?
SeniorTheoryOccasionalA user requests erasure under the EU privacy law GDPR, but your event log is immutable. What do you do?
A user requests erasure under the EU privacy law GDPR, but your event log is immutable. What do you do?
Keep personal data out of events where possible, storing only a reference to a mutable PII store. Data that must live in events is encrypted with a per-person key, and erasure deletes the key — crypto-shredding. Read models, caches and backups need their own cleanup.
Common mistakes
- ✗Putting raw personal data into event payloads by default
- ✗Thinking an erasure event alone removes the data from the log
- ✗Forgetting the read models, caches and backups that already copied the data
Follow-up questions
- →How should a projection behave when it reads an event whose key has been shredded?
- →Which customer fields would you keep in the event and which move to a separate store?
MiddleTheoryRareWhat is a process manager, and how does it differ from an event handler and from choreography?
What is a process manager, and how does it differ from an event handler and from choreography?
A process manager is a stateful coordinator: it reacts to events, keeps the state of a long-running process and decides which command to send next, including on a timeout. A plain handler keeps no memory between events; choreography has no coordinator.
Common mistakes
- ✗Treating a stateless event handler as a process manager
- ✗Confusing a central process manager with choreography, where no component owns the process
- ✗Forgetting that a process manager must also react to an event that never arrives
Follow-up questions
- →How does a process manager relate to the distributed-transaction pattern saga?
- →Where would you store a process manager's state in an event-sourced system?
SeniorTheoryRareA process manager may crash before sending its next command, and a reply may never arrive. How do you cope?
A process manager may crash before sending its next command, and a reply may never arrive. How do you cope?
Save the new state, the outgoing command via an outbox and any deadline in one transaction, then ack the event, so a crash only causes a redelivery. Commands carry deterministic ids for receivers to dedupe, and a scheduler fires stored deadlines as timeout events.
Common mistakes
- ✗Keeping deadlines in in-process timers that vanish on restart
- ✗Sending the command before the state that caused it is saved
- ✗Counting on exactly-once delivery instead of idempotent commands
Follow-up questions
- →What should the process manager do when a reply arrives after its timeout already fired?
- →How would you choose deterministic command ids for each step of the process?
SeniorTheoryRareThe aggregate struct changed, and stored snapshots no longer match it. What do you do?
The aggregate struct changed, and stored snapshots no longer match it. What do you do?
Version snapshots with the aggregate's state schema. On load, a snapshot with an older schema version is ignored, the aggregate is rebuilt from its events and a fresh snapshot is written. Snapshots are only a cache, so you may also delete them all and rebuild.
Common mistakes
- ✗Loading an old snapshot leniently and trusting zero values for new fields
- ✗Treating snapshots as durable data that must be upcast instead of a disposable cache
- ✗Serializing the aggregate struct itself, tying the snapshot format to every refactor
Follow-up questions
- →How would you roll out a new snapshot version without a spike in load latency?
- →Why serialize a dedicated snapshot struct rather than the aggregate itself?