How do you handle data consistency in microservices?

Data consistency in microservices refers to keeping data accurate and synchronized across services that each own their own database, without relying on a single shared transaction.

Key Points: • Eventual consistency accepts that data updated in one service will propagate to others asynchronously, typically via events, rather than instantly. • The Saga pattern breaks a business transaction into a sequence of local transactions across services, each with a compensating action if a later step fails. • Choreography-based sagas use events published to a broker that other services react to; orchestration-based sagas use a central coordinator to direct each step. • Idempotent consumers and outbox patterns help avoid duplicate or lost updates when messages are retried. • Strong consistency (distributed transactions/2PC) is generally avoided in microservices because it hurts availability and scalability.

Example: In an e-commerce checkout, the Order Service marks an order as "pending," the Inventory Service reserves stock, and the Payment Service charges the customer; if payment fails, a compensating event releases the reserved inventory and cancels the order.

Interview Tip: A concise interview answer is:

"Since each microservice owns its own database, I rely on eventual consistency achieved through events, and use the Saga pattern to coordinate multi-service transactions — each step has a compensating action so that if one step fails, previous steps can be rolled back logically rather than through a distributed transaction."