This code shows how to move from blocking synchronous updates to asynchronous event-driven updates. The InventoryService updates its data and publishes an event without waiting for others. The NotificationService listens and updates itself later, allowing data to converge over time.
### Before: Synchronous update causing blocking and tight coupling
class InventoryService:
def update_stock(self, product_id, quantity):
# Directly update database and block until done
database.update(product_id, quantity)
notify_other_services(product_id, quantity)
### After: Eventual consistency with asynchronous event publishing
import asyncio
class InventoryService:
async def update_stock(self, product_id, quantity):
# Update local database immediately
database.update(product_id, quantity)
# Publish event asynchronously
await event_bus.publish('stock_updated', {'product_id': product_id, 'quantity': quantity})
class NotificationService:
async def handle_stock_update(self, event):
# Consume event and update own state asynchronously
await database.update(event['product_id'], event['quantity'])
# Explanation:
# The before code blocks until all updates and notifications complete, causing delays.
# The after code updates local data immediately and publishes events asynchronously,
# allowing other services to update later, achieving eventual consistency.