Distributed transactions in a microservices architecture are handled with the Saga pattern, which splits a transaction spanning multiple services into local transactions with compensating actions instead of relying on a two-phase commit across databases.
Key Points: • Each participating service performs its own local transaction against its own database, since a single ACID transaction can't span multiple independently-owned databases. • Services communicate the outcome of their step to the next participant through direct calls or events, continuing the saga forward on success. • If any step fails, previously completed steps run their compensating transactions in reverse order to undo their effects. • Coordination can be choreographed through events with no central controller, or orchestrated through a central saga coordinator that explicitly drives each step. • The result is eventual consistency across services rather than the immediate, all-or-nothing atomicity a traditional single-database transaction provides.
Example: For a multi-service order, the Order service creates a pending order, Payment charges the customer, and Inventory reserves stock; if Inventory fails, a compensating transaction refunds the payment and cancels the order, keeping the system consistent without ever needing a lock across all three databases at once.
Interview Tip: A concise interview answer is:
"Since each service owns its own database, I handle cross-service transactions with the Saga pattern: break the transaction into local steps per service, and define a compensating action for anything that needs to be undone if a later step fails. It gives eventual consistency instead of true atomicity, coordinated either through events or a central orchestrator."