Problem Statement
When multiple microservices update shared data independently, immediate consistency is hard to guarantee. This causes temporary data mismatches, stale reads, or conflicting updates that confuse users and break workflows.
Jump into concepts and practice - no test required
This diagram shows two microservices updating their own databases and communicating changes asynchronously through an event bus to achieve eventual consistency.
### Before: Synchronous update causing blocking and tight coupling class OrderService: def create_order(self, order_data): # Update order database self.db.save(order_data) # Synchronously call inventory service success = self.inventory_service.reserve_stock(order_data['items']) if not success: raise Exception('Stock reservation failed') ### After: Asynchronous event-driven update for eventual consistency class OrderService: def create_order(self, order_data): # Update order database self.db.save(order_data) # Publish event to event bus event = {'type': 'OrderCreated', 'data': order_data} self.event_bus.publish(event) class InventoryService: def on_order_created(self, event): items = event['data']['items'] # Reserve stock asynchronously self.db.reserve_stock(items) # Event bus delivers events asynchronously, decoupling services
eventual consistency mean in microservices?eventQueue = []
function processEvent(event) {
if (event.type === 'update') {
database.update(event.data)
}
}
// Events arrive asynchronously
processEvent({type: 'update', data: {id: 1, value: 'A'}})
processEvent({type: 'update', data: {id: 1, value: 'B'}})
// What is the likely final value in the database for id 1?function handleEvent(event) {
if (event.type === 'update') {
if (!database.has(event.data.id)) {
database.insert(event.data)
} else {
database.update(event.data)
}
}
}