This example shows how replacing direct synchronous calls with asynchronous event publishing decouples services and enables eventual consistency in microservices.
### Before: Synchronous update causing tight coupling and blocking
class OrderService:
def create_order(self, order):
self.db.save(order)
inventory_service.update_stock(order.item_id, -order.quantity) # direct call
### After: Asynchronous event-driven update for eventual consistency
class OrderService:
def create_order(self, order):
self.db.save(order)
event = {'type': 'OrderCreated', 'item_id': order.item_id, 'quantity': order.quantity}
message_bus.publish(event)
class InventoryService:
def on_order_created(self, event):
self.db.update_stock(event['item_id'], -event['quantity'])
# Explanation:
# The before code tightly couples OrderService to InventoryService with synchronous calls,
# risking delays and failures propagating.
# The after code decouples them by publishing an event asynchronously,
# allowing InventoryService to update stock independently, achieving eventual consistency.