Design patterns and optimization · Intermediate

Reconstruct state from authoritative event history

Use deposits, withdrawals and snapshots to reason about deterministic replay, concurrent append, event evolution, corrections and external effects.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Make committed history the source of truth
  2. Replay deterministically and represent corrections explicitly
  3. Protect append with an expected version
  4. Preserve event meaning across schema evolution
  5. Account for rebuilding and ongoing operations
  6. Keep rejected commands distinct from accepted facts
  7. Solve snapshot and historical-rate exercises
  8. Ask Logeia about this articleCheck your understanding

Make committed history the source of truth

Instead of storing only balance eighty, retain deposit one hundred and withdrawal twenty and derive eighty by replay. Event sourcing makes the event sequence authoritative. Read state machines and CQRS first. Conventional current-state updates with an auxiliary audit log differ in which representation recovers the other. A file named log is not automatically a complete reconstructible source of truth.

An event records an accepted business fact, not an unvalidated request. Validate a withdrawal against current authoritative conditions, then append the accepted withdrawal event. Replaying raw requests through today's rules can produce different state from the same supposed history. Define where invariants are enforced and which fact became committed. This boundary separates accepting commands from interpreting already accepted history and explains why replay must not casually re-run every present-day side effect or validation policy.

Replay deterministically and represent corrections explicitly

Starting from zero, deposit one hundred produces one hundred and withdrawal twenty produces eighty. A new corrective deposit five produces 85. Silently editing the old withdrawal to 25 changes history previously observed by readers and audit. Define correction as a business fact rather than rewriting an event's meaning. Retention and deletion obligations also affect what should be stored in an authoritative history.

A deterministic apply function maps the same initial state and events to the same result. Reading current time or an external exchange rate during replay can change that result. Persist required event-time facts under an explicit contract. Replaying history must not automatically resend notifications or payments. Separate state reconstruction from external effects and name the rebuild destination. Determinism is a property of the supplied information and interpreter, not a benefit obtained merely by calling records events.

PositionCommitted eventBalance after application
1Deposit 100100
2Withdraw 2080
3Corrective deposit 585

Protect append with an expected version

Two withdrawals can both read balance one hundred and each request eighty. Unconditionally appending both can violate the invariant. An append conditioned on the aggregate's expected version lets one commit and forces the other to reread and revalidate. The version check and append need one atomic boundary; a preliminary read alone can race before insertion.

Retry identity remains separate from unique event positions. The same business request can otherwise be appended twice at different positions. Per-aggregate ordering also does not atomically transfer between two accounts. Cross-resource requirements return to distributed transactions or sagas. Specify which aggregate owns each invariant and what additional coordination connects several aggregates. An append-only representation does not remove the original business consistency questions.

Preserve event meaning across schema evolution

Suppose old events contain price, while newer requirements need currency and tax. Readers must preserve what old facts meant using event type and version. Applying today's tax rate to old facts can change reconstructed totals. Verify whether conversion has enough original information; inferred missing facts are not exact historical replay. Event evolution carries a longer compatibility obligation than simply adding a column to current state.

A snapshot accelerates replay through a known position. Balance eighty at position two plus subsequent corrective deposit five reconstructs 85. Record snapshot position, schema and derivation. A snapshot alone does not justify deleting history needed for audit or new projections. Consider corrupted snapshots and remaining recovery sources. Treat a performance shortcut and authoritative retention as separate decisions. The optimized path must still correspond to the event sequence it claims to summarize.

Account for rebuilding and ongoing operations

Derived query models still need CQRS-style handling of lag, duplicates, order and rebuild generation. Possessing history does not make every query immediate. Replay CPU and I/O, additional storage, format compatibility and deletion handling are real costs. Test the actual recoverable range. A matching latest balance does not prove every historical meaning or projection correct.

Conventional current rows with appropriate audit can suffice when complete reconstruction is unnecessary. Choose event sourcing when authoritative history benefits justify evolution and recovery cost. Observe append conflicts, retries, unsupported versions, replay failure and projection lag separately. Recover through committed positions and identity rather than arbitrarily sorting printed logs. Verify side effects are disabled or redirected during reconstruction before executing it. The operational contract must make replay safe as well as possible.

Keep rejected commands distinct from accepted facts

If balance eighty rejects withdrawal one hundred, do not append a committed withdrawal effect. Rejection audit can be retained, but define how it differs from the facts used to reconstruct balance. Treating a rejected request as an ordinary withdrawal event and applying it unconditionally during replay breaks the invariant originally enforced. Event naming, schema and apply logic must agree on what was accepted. This is why merely recording every input is not the same design as retaining committed business history. Test accepted and rejected commands against replay so an audit enhancement cannot silently change authoritative reconstruction.

The same distinction must remain true during replay, not only command handling.

Solve snapshot and historical-rate exercises

A snapshot at position two holds eighty; applying position three's corrective deposit once yields 85. Reapplying earlier events double-counts them. Conversely, advancing the snapshot position while leaving its state at eighty can falsely skip the correction. State and position must correspond atomically to the history they summarize.

Reading today's external rate during historical replay can violate deterministic reconstruction. Store the relevant historical rate or define current conversion as a separate query, depending on the requirement. The learning outcome distinguishes authoritative events, command identity, aggregate version, snapshot and projection. Their roles support different guarantees even when all appear as records with IDs and numbers.

Reading and practice are recorded separately in this browser, for each language.

Learn this in order

Understand the systems behind the web · STEP 17

Choose a learning path