Exercise — Saga Pattern: design a booking that reserves a flight and a hotel atomically.

Topic: microservices, Data Management. Level: Hard.

Answer

Model each reservation as a local transaction with a compensation. If the hotel step fails after the flight is booked, cancel the flight. Make every step idempotent (retry-safe) and record Saga state so it can resume after a crash. Below is an orchestrated implementation with explicit compensation and idempotency keys. ```java class TripBookingSaga { void book(TripRequest req) { String sagaId = req.id(); String flightRef = null; try { flightRef = flight.reserve(sagaId, req.flight()); // idempotent by sagaId String hotelRef = hotel.reserve(sagaId, req.hotel()); store.markCompleted(sagaId, flightRef, hotelRef); } catch (Exception ex) { if (flightRef != null) flight.cancel(sagaId, flightRef); // compensate store.markAborted(sagaId, ex.getMessage()); throw new BookingFailedException(sagaId, ex); } } } // Idempotency: flight.reserve(sagaId,...) returns the SAME ref if called twice. ```