Node.js › Architecture & Design Patterns
What is the Saga pattern, and how does it manage distributed transactions across multiple Node.js microservices?
AdvancedAnswer
Because distributed systems typically can't use a single ACID database transaction spanning multiple services, the Saga pattern manages a multi-step business process as a sequence of local transactions, each in its own service, with a corresponding compensating action defined for each step to undo it if a later step fails -- implemented either as choreography (each service listens for events and reacts, fully decentralized) or orchestration (a central coordinator explicitly calls each step and triggers compensations on failure).
// Orchestration-style saga (simplified)
async function bookTripSaga(trip) {
const flight = await bookFlight(trip);
try {
const hotel = await bookHotel(trip);
try {
return await bookCar(trip);
} catch (err) { await cancelHotel(hotel); throw err; }
} catch (err) { await cancelFlight(flight); throw err; }
}Real-world example A travel-booking platform uses an orchestrated saga to book a flight, hotel, and rental car across three separate microservices; if the car-rental booking fails after the flight and hotel already succeeded, the saga automatically triggers compensating cancelFlight and cancelHotel calls rather than leaving the customer half-booked.