Mealy Machines, Moore Machines, and Why Event Sourcing Works
8 hours ago
- #Automata Theory
- #Event Sourcing
- #System Design
- Event sourcing involves storing events instead of state, but explanations often omit details on replay determinism and side-effect separation.
- Automata theory (Moore and Mealy machines) provides a formal framework: Moore machines output based on state, Mealy machines output during transitions.
- Replayable event sourcing requires deterministic state evolution; side effects (e.g., emails) must be separated to avoid re-execution during replay.
- Key functions: 'decide' (command → events), 'apply' (event × state → state for replay), 'transition' (event × state → state + actions for live execution).
- Implementation in Rust (e.g., obzenflow-fsm) separates state transitions and actions, with a host loop executing actions and handling replay.
- A door example illustrates Mealy transitions: actions like ringing a bell depend on the specific event (Opened) triggering the transition.
- Event logs serve as persistent input sequences; events are facts, while actions are transient and must be managed separately for reliability.
- The host loop supervises execution, journals events, and ensures replay suppresses actions, maintaining durability and observability.
- Event sourcing enables audit trails, new projections from old events, and temporal queries, but requires careful separation of concerns for correctness.