The before code shows a synchronous HTTP request where Service A waits for Service B's response. The after code demonstrates an event-driven approach where Service A publishes an event to an event bus, and Service B asynchronously processes it without blocking Service A.
### Before: Request-Response (Synchronous)
import requests
def get_user_data(user_id):
response = requests.get(f"http://service-b/users/{user_id}")
if response.status_code == 200:
return response.json()
else:
return None
### After: Event-Driven (Asynchronous)
import asyncio
class EventBus:
def __init__(self):
self.subscribers = []
def subscribe(self, callback):
self.subscribers.append(callback)
async def publish(self, event):
for subscriber in self.subscribers:
await subscriber(event)
async def service_a(event_bus, user_id):
event = {"type": "UserRequested", "user_id": user_id}
await event_bus.publish(event)
async def service_b(event):
if event["type"] == "UserRequested":
print(f"Processing user {event['user_id']}")
async def main():
bus = EventBus()
bus.subscribe(service_b)
await service_a(bus, 123)
asyncio.run(main())