Problem Statement
When services communicate only by direct requests, a slow or failing service can block the entire flow, causing delays and failures. This tight coupling makes the system fragile and hard to scale under varying loads.
The diagram shows two communication styles: event-driven where Service A emits events to an event broker that Service B consumes asynchronously, and request-driven where a client sends a request to Service A and waits synchronously for a response.
### Before: Request-driven (synchronous call) class ServiceA: def process(self, data): result = ServiceB().handle(data) return result class ServiceB: def handle(self, data): return f"Processed {data}" # Usage service_a = ServiceA() response = service_a.process('input') print(response) ### After: Event-driven (asynchronous event emission) import queue class EventBroker: def __init__(self): self.subscribers = [] self.events = queue.Queue() def subscribe(self, handler): self.subscribers.append(handler) def publish(self, event): self.events.put(event) def dispatch(self): while not self.events.empty(): event = self.events.get() for subscriber in self.subscribers: subscriber(event) class ServiceA: def __init__(self, broker): self.broker = broker def process(self, data): self.broker.publish({'type': 'process', 'data': data}) class ServiceB: def __call__(self, event): if event['type'] == 'process': print(f"Processed {event['data']}") # Setup broker = EventBroker() service_b = ServiceB() broker.subscribe(service_b) service_a = ServiceA(broker) # Usage service_a.process('input') broker.dispatch()