Back
+20 XP
Concept

Event Sourcing & Append-Only State Machines

Instead of mutating rows with destructive `UPDATE` queries, Event Sourcing logs state transitions as an immutable, append-only ledger. Current and past states are reconstructed by replaying event sequences 📜.

python
class Account:
    def __init__(self):
        self.events = []

    def record(self, action, amount):
        self.events.append((action, amount))

    def balance(self):
        bal = 0
        for act, amt in self.events:
            bal += amt if act == "DEPOSIT" else -amt
        return bal

acc = Account()
acc.record("DEPOSIT", 200)
acc.record("WITHDRAW", 50)
print(f"Reconstructed Balance: ${acc.balance()} 📜")

# 90. Event Sourcing & Append-Only State Machines Instead of mutating rows with destructive `UPDATE` queries, Event Sourcing logs state transitions as an immutable, append-only ledger. Current and past states are reconstructed by replaying event sequences 📜. ```python class Account: def __init__(self): self.events = [] def record(self, action, amount): self.events.append((action, amount)) def balance(self): bal = 0 for act, amt in self.events: bal += amt if act == "DEPOSIT" else -amt return bal acc = Account() acc.record("DEPOSIT", 200) acc.record("WITHDRAW", 50) print(f"Reconstructed Balance: ${acc.balance()} 📜") ``` When event streams grow into millions of items, replaying from event zero becomes too slow. Systems solve this by generating periodic state snapshots (e.g. every 10,000 events) and replaying only from the latest snapshot forward ⚡! --- ### Question What major advantage does Event Sourcing provide over traditional CRUD database mutation? 🧠 - [ ] a. Flawless historical auditability: any past state can be reconstructed by replaying the event log up to that timestamp 📜 - [ ] b. It eliminates the need to store data on physical disks - [ ] c. It guarantees zero CPU usage during query evaluation - [ ] d. It prevents all possible network latency during distributed writes --- ### Challenge Build `EventSourcedAccount` with `record(action, amount)` and `balance()`. Record `('DEPOSIT', 500)`, `('WITHDRAW', 150)`, and `('DEPOSIT', 50)`. Print the replayed balance. 🎯 <details> <summary>Solution</summary> ```python class EventSourcedAccount: def __init__(self): self.events = [] def record(self, action, amount): self.events.append((action, amount)) def balance(self): bal = 0 for act, amt in self.events: bal += amt if act == 'DEPOSIT' else -amt return bal acc = EventSourcedAccount() acc.record('DEPOSIT', 500) acc.record('WITHDRAW', 150) acc.record('DEPOSIT', 50) print(acc.balance()) ``` </details>

Checkpoint

What major advantage does Event Sourcing provide over traditional CRUD database mutation? 🧠

Practice

Build `EventSourcedAccount` with `record(action, amount)` and `balance()`. Record `('DEPOSIT', 500)`, `('WITHDRAW', 150)`, and `('DEPOSIT', 50)`. Print the replayed balance. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks