The before code stores only the current state and loses data on restart. The after code stores all events in an event store and replays them on recovery to rebuild the state exactly.
### Before: Service stores only current state, no event replay
class OrderService:
def __init__(self):
self.orders = {}
def create_order(self, order_id, details):
self.orders[order_id] = details
def recover(self):
# No way to recover lost state
self.orders = {}
### After: Service stores events and replays them to recover
class EventStore:
def __init__(self):
self.events = []
def append(self, event):
self.events.append(event)
def get_all(self):
return self.events
class OrderServiceWithReplay:
def __init__(self, event_store):
self.orders = {}
self.event_store = event_store
def create_order(self, order_id, details):
event = {'type': 'OrderCreated', 'order_id': order_id, 'details': details}
self.event_store.append(event)
self.apply(event)
def apply(self, event):
if event['type'] == 'OrderCreated':
self.orders[event['order_id']] = event['details']
def recover(self):
self.orders = {}
for event in self.event_store.get_all():
self.apply(event)