Distributed Transactions Using the Saga Pattern

A saga is a way to keep data consistent across several microservices by splitting one business transaction into a sequence of small local transactions, one in each service.It is used because each microservice has its own database, so a normal database transaction (or a slow two-phase commit) cannot span services.If one step fails, the saga runs compensating transactions that undo the steps that already succeeded, for example refunding a payment or releasing reserved stock.In this demo, an order is placed by reserving stock in the Inventory service and then taking the payment in the Payment service, and the Order service coordinates the steps and the compensations.

Features

  • No distributed lock and no two-phase commit.
  • Every service keeps its own database and its own local transaction.
  • Compensating transactions undo completed steps, in reverse order.
  • Saga state is kept as an order status (PENDING, CONFIRMED, REJECTED, CANCELLED, COMPENSATION_PENDING) and a saga log of every step.
  • Steps and compensations are idempotent, so repeating them is safe.
  • A compensation that fails can be retried later.
  • Eventual consistency: for a short time the data is in between states.

Saga Pattern Types

Ways to coordinate a saga

Type Meaning Pros Cons
Orchestration One central service (the orchestrator) tells each service what to do and runs the compensations Easy to follow, one place for the flow The orchestrator knows all the steps (used in this demo)
Choreography No coordinator: each service reacts to events published by the others (Kafka, RabbitMQ) Loose coupling, no central point The flow is spread over many services and is harder to track

Kinds of transaction in a saga

Kind Meaning In this demo
Compensable transaction A step that can be undone Reserve stock (undo: release), take payment (undo: refund)
Pivot transaction The point of no return, after which the saga must finish Payment approved
Retriable transaction A step after the pivot that is retried until it succeeds Retry of a failed compensation

Steps and their compensations in this demo

Step Service Compensating transaction
T1 Create order (PENDING) Order Mark the order REJECTED or CANCELLED
T2 Reserve stock Inventory Release the reservation (stock goes back)
T3 Take payment Payment Refund the payment

Saga vs two-phase commit (2PC)

Point Saga Two-phase commit
Locks across services No Yes, held until the end
Scalability High Low
Consistency Eventual Immediate
Failure handling Compensating transactions Rollback by the coordinator
Fit for microservices Yes Rarely

Design rules for a saga

Rule Why
Make every step and compensation idempotent A retry must not charge or release twice
Record the saga state So a failed saga can be inspected and resumed
Compensate in reverse order Later steps may depend on earlier ones
Handle unknown outcomes If a service did not answer, do not assume the step failed

Hands-on Experiment: Create an Order, Payment, and Inventory Management System Using the Saga Pattern

Aim: To create three Spring Boot microservices (Order, Inventory, and Payment), each with its own MySQL database, where an order is processed as an orchestrated saga with compensating transactions.

The following steps are involved in developing this hands-on experiment.

  • Step 1: Generate the Project
  • Step 2: Project Structure
  • Step 3: Create Inventory Micro Service
  • Step 4: Create Payment Micro Service
  • Step 5: Create Order Micro Service (the Saga Orchestrator)
  • Step 6: Run the Application

Step-by-Step Application Development

Step 1: Generate the Project

Use Spring Initializr with:

  • Project: Maven
  • Language: Java
  • Spring Boot version: 3.3.x (latest stable)
  • Group: com.example
  • Artifact: saga-pattern-demo (parent), with modules order-service, inventory-service, and payment-service
  • Packaging: Jar
  • Java version: 17
  • Dependencies for all three services: Spring Web, Spring Data JPA, MySQL Driver

Download the generated ZIPs and place the three services as modules inside one parent folder saga-pattern-demo. The ready-made multi-module project is also in the zip.

Step 2: Project Structure

Step 3: Create Inventory Micro Service

package com.example.inventoryservice.entity;

import jakarta.persistence.*;

import java.math.BigDecimal;

@Entity
@Table(name = "inventory_items")
public class InventoryItem {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String productName;

    @Column(nullable = false, precision = 12, scale = 2)
    private BigDecimal unitPrice;

    @Column(nullable = false)
    private Integer availableQuantity;

    public InventoryItem() {
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getProductName() { return productName; }
    public void setProductName(String productName) { this.productName = productName; }

    public BigDecimal getUnitPrice() { return unitPrice; }
    public void setUnitPrice(BigDecimal unitPrice) { this.unitPrice = unitPrice; }

    public Integer getAvailableQuantity() { return availableQuantity; }
    public void setAvailableQuantity(Integer availableQuantity) { this.availableQuantity = availableQuantity; }
}
package com.example.inventoryservice.entity;

import jakarta.persistence.*;

import java.time.LocalDateTime;

// One reservation per order. RESERVED = stock is held, RELEASED = stock was given back (compensation)
@Entity
@Table(name = "reservations")
public class Reservation {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private Long orderId;

    @Column(nullable = false)
    private Long productId;

    @Column(nullable = false)
    private Integer quantity;

    private String status;

    private LocalDateTime createdAt;

    public Reservation() {
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public Long getOrderId() { return orderId; }
    public void setOrderId(Long orderId) { this.orderId = orderId; }

    public Long getProductId() { return productId; }
    public void setProductId(Long productId) { this.productId = productId; }

    public Integer getQuantity() { return quantity; }
    public void setQuantity(Integer quantity) { this.quantity = quantity; }

    public String getStatus() { return status; }
    public void setStatus(String status) { this.status = status; }

    public LocalDateTime getCreatedAt() { return createdAt; }
    public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
}
package com.example.inventoryservice.repository;

import com.example.inventoryservice.entity.InventoryItem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface InventoryItemRepository extends JpaRepository<InventoryItem, Long> {
}
package com.example.inventoryservice.repository;

import com.example.inventoryservice.entity.Reservation;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface ReservationRepository extends JpaRepository<Reservation, Long> {

    Optional<Reservation> findByOrderId(Long orderId);
}
package com.example.inventoryservice.service;

import com.example.inventoryservice.entity.InventoryItem;
import com.example.inventoryservice.entity.Reservation;
import com.example.inventoryservice.repository.InventoryItemRepository;
import com.example.inventoryservice.repository.ReservationRepository;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;

@Service
public class InventoryService {

    private final InventoryItemRepository itemRepository;
    private final ReservationRepository reservationRepository;

    // Test switch: when true, the release (compensation) call fails, so we can see COMPENSATION_PENDING
    private final AtomicBoolean releaseFails = new AtomicBoolean(false);

    public InventoryService(InventoryItemRepository itemRepository, ReservationRepository reservationRepository) {
        this.itemRepository = itemRepository;
        this.reservationRepository = reservationRepository;
    }

    // ======================= Inventory items =======================

    public InventoryItem createItem(InventoryItem item) {
        if (item.getProductName() == null || item.getProductName().isBlank()
                || item.getUnitPrice() == null || item.getUnitPrice().compareTo(BigDecimal.ZERO) <= 0
                || item.getAvailableQuantity() == null || item.getAvailableQuantity() < 0) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                    "productName, unitPrice (greater than 0) and availableQuantity (0 or more) are required");
        }
        item.setId(null);
        return itemRepository.save(item);
    }

    public List<InventoryItem> getAllItems() {
        return itemRepository.findAll();
    }

    public Optional<InventoryItem> getItemById(Long id) {
        return itemRepository.findById(id);
    }

    // ======================= Saga step: reserve stock (local transaction) =======================

    @Transactional
    public Map<String, Object> reserve(Reservation request) {
        if (request.getOrderId() == null || request.getProductId() == null
                || request.getQuantity() == null || request.getQuantity() <= 0) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                    "orderId, productId and a positive quantity are required");
        }

        // Idempotent: the same order can be reserved only once
        Optional<Reservation> existing = reservationRepository.findByOrderId(request.getOrderId());
        if (existing.isPresent()) {
            if ("RESERVED".equals(existing.get().getStatus())) {
                return toResponse(existing.get(), findItem(existing.get().getProductId()));
            }
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                    "Reservation for order " + request.getOrderId() + " was already released");
        }

        InventoryItem item = findItem(request.getProductId());
        if (item.getAvailableQuantity() < request.getQuantity()) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                    "Insufficient stock for '" + item.getProductName() + "'. Available: "
                            + item.getAvailableQuantity());
        }

        item.setAvailableQuantity(item.getAvailableQuantity() - request.getQuantity());
        itemRepository.save(item);

        Reservation reservation = new Reservation();
        reservation.setOrderId(request.getOrderId());
        reservation.setProductId(request.getProductId());
        reservation.setQuantity(request.getQuantity());
        reservation.setStatus("RESERVED");
        reservation.setCreatedAt(LocalDateTime.now());

        return toResponse(reservationRepository.save(reservation), item);
    }

    // ======================= Compensating transaction: release stock =======================

    @Transactional
    public Reservation release(Long orderId) {
        if (releaseFails.get()) {
            throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE,
                    "Inventory release is temporarily unavailable (simulated failure)");
        }

        Reservation reservation = reservationRepository.findByOrderId(orderId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND,
                        "No reservation found for order " + orderId));

        // Idempotent: releasing twice does not add the stock twice
        if (!"RELEASED".equals(reservation.getStatus())) {
            InventoryItem item = findItem(reservation.getProductId());
            item.setAvailableQuantity(item.getAvailableQuantity() + reservation.getQuantity());
            itemRepository.save(item);

            reservation.setStatus("RELEASED");
            reservationRepository.save(reservation);
        }
        return reservation;
    }

    public List<Reservation> getAllReservations() {
        return reservationRepository.findAll();
    }

    public Optional<Reservation> getReservationByOrderId(Long orderId) {
        return reservationRepository.findByOrderId(orderId);
    }

    public void setReleaseFails(boolean value) {
        releaseFails.set(value);
    }

    public boolean isReleaseFails() {
        return releaseFails.get();
    }

    // ======================= Helpers =======================

    private InventoryItem findItem(Long productId) {
        return itemRepository.findById(productId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND,
                        "Product not found with id " + productId));
    }

    private Map<String, Object> toResponse(Reservation reservation, InventoryItem item) {
        Map<String, Object> response = new LinkedHashMap<>();
        response.put("orderId", reservation.getOrderId());
        response.put("productId", reservation.getProductId());
        response.put("productName", item.getProductName());
        response.put("unitPrice", item.getUnitPrice());
        response.put("quantity", reservation.getQuantity());
        response.put("totalAmount", item.getUnitPrice().multiply(BigDecimal.valueOf(reservation.getQuantity())));
        response.put("status", reservation.getStatus());
        return response;
    }
}
package com.example.inventoryservice.controller;

import com.example.inventoryservice.entity.InventoryItem;
import com.example.inventoryservice.entity.Reservation;
import com.example.inventoryservice.service.InventoryService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/inventory")
public class InventoryController {

    private final InventoryService inventoryService;

    public InventoryController(InventoryService inventoryService) {
        this.inventoryService = inventoryService;
    }

    // ---------- items ----------

    // POST /api/inventory/items
    @PostMapping("/items")
    public ResponseEntity<InventoryItem> createItem(@RequestBody InventoryItem item) {
        return ResponseEntity.status(HttpStatus.CREATED).body(inventoryService.createItem(item));
    }

    // GET /api/inventory/items
    @GetMapping("/items")
    public List<InventoryItem> getAllItems() {
        return inventoryService.getAllItems();
    }

    // GET /api/inventory/items/{id}
    @GetMapping("/items/{id}")
    public ResponseEntity<InventoryItem> getItemById(@PathVariable Long id) {
        return inventoryService.getItemById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // ---------- saga steps ----------

    // POST /api/inventory/reservations   (saga step: reserve stock)
    @PostMapping("/reservations")
    public ResponseEntity<Map<String, Object>> reserve(@RequestBody Reservation reservation) {
        return ResponseEntity.status(HttpStatus.CREATED).body(inventoryService.reserve(reservation));
    }

    // POST /api/inventory/reservations/{orderId}/release   (compensation: give the stock back)
    @PostMapping("/reservations/{orderId}/release")
    public Reservation release(@PathVariable Long orderId) {
        return inventoryService.release(orderId);
    }

    // GET /api/inventory/reservations
    @GetMapping("/reservations")
    public List<Reservation> getAllReservations() {
        return inventoryService.getAllReservations();
    }

    // GET /api/inventory/reservations/{orderId}
    @GetMapping("/reservations/{orderId}")
    public ResponseEntity<Reservation> getReservation(@PathVariable Long orderId) {
        return inventoryService.getReservationByOrderId(orderId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // ---------- test switch ----------

    // POST /api/inventory/failure-mode?releaseFails=true
    @PostMapping("/failure-mode")
    public Map<String, Object> setFailureMode(@RequestParam boolean releaseFails) {
        inventoryService.setReleaseFails(releaseFails);
        Map<String, Object> response = new LinkedHashMap<>();
        response.put("releaseFails", inventoryService.isReleaseFails());
        return response;
    }
}
package com.example.inventoryservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class InventoryServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(InventoryServiceApplication.class, args);
    }
}
spring.application.name=inventory-service
server.port=8082

# Database owned ONLY by inventory-service
spring.datasource.url=jdbc:mysql://localhost:3306/saga_inventory_db?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=false

server.error.include-message=alwaysCode language: PHP (php)

Step 4: Create Payment Micro Service

package com.example.paymentservice.entity;

import jakarta.persistence.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;

// status: SUCCESS | DECLINED | REFUNDED
@Entity
@Table(name = "payments")
public class Payment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private Long orderId;

    private String customerName;

    @Column(nullable = false, precision = 12, scale = 2)
    private BigDecimal amount;

    private String status;

    private String transactionId;

    private String reason;

    private LocalDateTime createdAt;

    public Payment() {
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public Long getOrderId() { return orderId; }
    public void setOrderId(Long orderId) { this.orderId = orderId; }

    public String getCustomerName() { return customerName; }
    public void setCustomerName(String customerName) { this.customerName = customerName; }

    public BigDecimal getAmount() { return amount; }
    public void setAmount(BigDecimal amount) { this.amount = amount; }

    public String getStatus() { return status; }
    public void setStatus(String status) { this.status = status; }

    public String getTransactionId() { return transactionId; }
    public void setTransactionId(String transactionId) { this.transactionId = transactionId; }

    public String getReason() { return reason; }
    public void setReason(String reason) { this.reason = reason; }

    public LocalDateTime getCreatedAt() { return createdAt; }
    public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
}
package com.example.paymentservice.repository;

import com.example.paymentservice.entity.Payment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface PaymentRepository extends JpaRepository<Payment, Long> {

    Optional<Payment> findByOrderId(Long orderId);
}
package com.example.paymentservice.service;

import com.example.paymentservice.entity.Payment;
import com.example.paymentservice.repository.PaymentRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;

@Service
public class PaymentService {

    private final PaymentRepository paymentRepository;
    private final BigDecimal paymentLimit;

    // Test switch: when true, the payment call fails with 500 (the payment service is "broken")
    private final AtomicBoolean failureMode = new AtomicBoolean(false);

    public PaymentService(PaymentRepository paymentRepository,
                          @Value("${payment.limit}") BigDecimal paymentLimit) {
        this.paymentRepository = paymentRepository;
        this.paymentLimit = paymentLimit;
    }

    // ======================= Saga step: take the payment (local transaction) =======================

    public Payment processPayment(Payment request) {
        if (failureMode.get()) {
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR,
                    "Payment service failure (simulated)");
        }
        if (request.getOrderId() == null || request.getCustomerName() == null || request.getCustomerName().isBlank()
                || request.getAmount() == null || request.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                    "orderId, customerName and an amount greater than 0 are required");
        }

        // Idempotent: the same order is never charged twice
        Optional<Payment> existing = paymentRepository.findByOrderId(request.getOrderId());
        if (existing.isPresent()) {
            return existing.get();
        }

        Payment payment = new Payment();
        payment.setOrderId(request.getOrderId());
        payment.setCustomerName(request.getCustomerName());
        payment.setAmount(request.getAmount());
        payment.setCreatedAt(LocalDateTime.now());

        if (request.getAmount().compareTo(paymentLimit) > 0) {
            payment.setStatus("DECLINED");
            payment.setReason("Amount " + request.getAmount() + " exceeds the payment limit of " + paymentLimit);
        } else {
            payment.setStatus("SUCCESS");
            payment.setTransactionId("TXN-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase());
        }
        return paymentRepository.save(payment);
    }

    // ======================= Compensating transaction: refund =======================

    public Payment refund(Long orderId) {
        Payment payment = paymentRepository.findByOrderId(orderId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND,
                        "No payment found for order " + orderId));

        // Idempotent: only a SUCCESS payment is refunded, anything else is returned unchanged
        if ("SUCCESS".equals(payment.getStatus())) {
            payment.setStatus("REFUNDED");
            payment.setReason("Refunded because the order was cancelled");
            paymentRepository.save(payment);
        }
        return payment;
    }

    public List<Payment> getAllPayments() {
        return paymentRepository.findAll();
    }

    public Optional<Payment> getPaymentByOrderId(Long orderId) {
        return paymentRepository.findByOrderId(orderId);
    }

    public void setFailureMode(boolean enabled) {
        failureMode.set(enabled);
    }

    public boolean isFailureMode() {
        return failureMode.get();
    }
}
package com.example.paymentservice.controller;

import com.example.paymentservice.entity.Payment;
import com.example.paymentservice.service.PaymentService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/payments")
public class PaymentController {

    private final PaymentService paymentService;

    public PaymentController(PaymentService paymentService) {
        this.paymentService = paymentService;
    }

    // POST /api/payments   (saga step: take the payment)
    @PostMapping
    public ResponseEntity<Payment> processPayment(@RequestBody Payment payment) {
        return ResponseEntity.status(HttpStatus.CREATED).body(paymentService.processPayment(payment));
    }

    // POST /api/payments/order/{orderId}/refund   (compensation: give the money back)
    @PostMapping("/order/{orderId}/refund")
    public Payment refund(@PathVariable Long orderId) {
        return paymentService.refund(orderId);
    }

    // GET /api/payments
    @GetMapping
    public List<Payment> getAllPayments() {
        return paymentService.getAllPayments();
    }

    // GET /api/payments/order/{orderId}
    @GetMapping("/order/{orderId}")
    public ResponseEntity<Payment> getPaymentByOrderId(@PathVariable Long orderId) {
        return paymentService.getPaymentByOrderId(orderId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // POST /api/payments/failure-mode?enabled=true   (test switch)
    @PostMapping("/failure-mode")
    public Map<String, Object> setFailureMode(@RequestParam boolean enabled) {
        paymentService.setFailureMode(enabled);
        Map<String, Object> response = new LinkedHashMap<>();
        response.put("failureMode", paymentService.isFailureMode());
        return response;
    }
}
package com.example.paymentservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class PaymentServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(PaymentServiceApplication.class, args);
    }
}
spring.application.name=payment-service
server.port=8083

# Database owned ONLY by payment-service
spring.datasource.url=jdbc:mysql://localhost:3306/saga_payment_db?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=false

server.error.include-message=always

# Payments above this amount are declined (used to trigger the saga compensation)
payment.limit=50000Code language: PHP (php)

Step 5: Create Order Microservice

package com.example.orderservice.entity;

import jakarta.persistence.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;

// status: PENDING | CONFIRMED | REJECTED | CANCELLED | COMPENSATION_PENDING
@Entity
@Table(name = "orders")
public class CustomerOrder {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String customerName;

    @Column(nullable = false)
    private Long productId;

    @Column(nullable = false)
    private Integer quantity;

    private String productName;

    @Column(precision = 12, scale = 2)
    private BigDecimal unitPrice;

    @Column(precision = 12, scale = 2)
    private BigDecimal totalAmount;

    private String status;

    @Column(length = 500)
    private String failureReason;

    private LocalDateTime createdAt;

    public CustomerOrder() {
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getCustomerName() { return customerName; }
    public void setCustomerName(String customerName) { this.customerName = customerName; }

    public Long getProductId() { return productId; }
    public void setProductId(Long productId) { this.productId = productId; }

    public Integer getQuantity() { return quantity; }
    public void setQuantity(Integer quantity) { this.quantity = quantity; }

    public String getProductName() { return productName; }
    public void setProductName(String productName) { this.productName = productName; }

    public BigDecimal getUnitPrice() { return unitPrice; }
    public void setUnitPrice(BigDecimal unitPrice) { this.unitPrice = unitPrice; }

    public BigDecimal getTotalAmount() { return totalAmount; }
    public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; }

    public String getStatus() { return status; }
    public void setStatus(String status) { this.status = status; }

    public String getFailureReason() { return failureReason; }
    public void setFailureReason(String failureReason) { this.failureReason = failureReason; }

    public LocalDateTime getCreatedAt() { return createdAt; }
    public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
}
package com.example.orderservice.entity;

import jakarta.persistence.*;

import java.time.LocalDateTime;

// One row for every step (and every compensation) of the saga of an order
@Entity
@Table(name = "saga_log")
public class SagaLog {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private Long orderId;

    @Column(nullable = false)
    private String step;

    @Column(nullable = false)
    private String status;

    @Column(length = 500)
    private String message;

    private LocalDateTime createdAt;

    public SagaLog() {
    }

    public SagaLog(Long orderId, String step, String status, String message) {
        this.orderId = orderId;
        this.step = step;
        this.status = status;
        this.message = message;
        this.createdAt = LocalDateTime.now();
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public Long getOrderId() { return orderId; }
    public void setOrderId(Long orderId) { this.orderId = orderId; }

    public String getStep() { return step; }
    public void setStep(String step) { this.step = step; }

    public String getStatus() { return status; }
    public void setStatus(String status) { this.status = status; }

    public String getMessage() { return message; }
    public void setMessage(String message) { this.message = message; }

    public LocalDateTime getCreatedAt() { return createdAt; }
    public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
}
package com.example.orderservice.repository;

import com.example.orderservice.entity.CustomerOrder;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface CustomerOrderRepository extends JpaRepository<CustomerOrder, Long> {
}
package com.example.orderservice.repository;

import com.example.orderservice.entity.SagaLog;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface SagaLogRepository extends JpaRepository<SagaLog, Long> {

    List<SagaLog> findByOrderIdOrderByIdAsc(Long orderId);
}
package com.example.orderservice.service;

import com.example.orderservice.entity.CustomerOrder;
import com.example.orderservice.entity.SagaLog;
import com.example.orderservice.repository.CustomerOrderRepository;
import com.example.orderservice.repository.SagaLogRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.server.ResponseStatusException;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

// The ORCHESTRATOR of the saga. It runs the steps in order and, when a step fails,
// runs the compensating transactions of the steps that already succeeded.
//
//   T1 create order (PENDING)   -> C1 mark the order REJECTED / CANCELLED
//   T2 reserve stock            -> C2 release stock
//   T3 take payment             -> C3 refund payment
@Service
public class OrderService {

    private static final ParameterizedTypeReference<Map<String, Object>> MAP_TYPE =
            new ParameterizedTypeReference<Map<String, Object>>() {
            };

    private final CustomerOrderRepository orderRepository;
    private final SagaLogRepository sagaLogRepository;
    private final RestClient inventoryClient;
    private final RestClient paymentClient;

    public OrderService(CustomerOrderRepository orderRepository,
                        SagaLogRepository sagaLogRepository,
                        @Value("${inventory.service.url}") String inventoryUrl,
                        @Value("${payment.service.url}") String paymentUrl) {
        this.orderRepository = orderRepository;
        this.sagaLogRepository = sagaLogRepository;
        this.inventoryClient = buildClient(inventoryUrl);
        this.paymentClient = buildClient(paymentUrl);
    }

    // ======================= Read operations =======================

    public List<CustomerOrder> getAllOrders() {
        return orderRepository.findAll();
    }

    public Optional<CustomerOrder> getOrderById(Long id) {
        return orderRepository.findById(id);
    }

    public List<SagaLog> getSagaLog(Long orderId) {
        findOrder(orderId);
        return sagaLogRepository.findByOrderIdOrderByIdAsc(orderId);
    }

    // ======================= THE SAGA: place an order =======================

    public CustomerOrder placeOrder(CustomerOrder request) {
        if (request.getCustomerName() == null || request.getCustomerName().isBlank()
                || request.getProductId() == null
                || request.getQuantity() == null || request.getQuantity() <= 0) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                    "customerName, productId and a positive quantity are required");
        }

        // ---- T1: create the order in our own database (local transaction) ----
        CustomerOrder order = new CustomerOrder();
        order.setCustomerName(request.getCustomerName());
        order.setProductId(request.getProductId());
        order.setQuantity(request.getQuantity());
        order.setStatus("PENDING");
        order.setCreatedAt(LocalDateTime.now());
        order = orderRepository.save(order);
        logStep(order.getId(), "CREATE_ORDER", "SUCCESS", "Order created with status PENDING");

        // ---- T2: reserve stock in inventory-service ----
        Map<String, Object> reservation;
        try {
            reservation = reserveInventory(order);
        } catch (SagaStepException e) {
            logStep(order.getId(), "RESERVE_INVENTORY", "FAILED", e.getMessage());
            // nothing else succeeded yet, so there is nothing to compensate
            return finish(order, "REJECTED", e.getMessage());
        }

        BigDecimal unitPrice = new BigDecimal(String.valueOf(reservation.get("unitPrice")));
        order.setProductName(String.valueOf(reservation.get("productName")));
        order.setUnitPrice(unitPrice);
        order.setTotalAmount(unitPrice.multiply(BigDecimal.valueOf(order.getQuantity())));
        orderRepository.save(order);
        logStep(order.getId(), "RESERVE_INVENTORY", "SUCCESS",
                "Reserved " + order.getQuantity() + " unit(s) of " + order.getProductName());

        // ---- T3: take the payment in payment-service ----
        try {
            Map<String, Object> payment = processPayment(order);
            if (!"SUCCESS".equals(String.valueOf(payment.get("status")))) {
                throw new SagaStepException("Payment declined: " + payment.get("reason"));
            }
            logStep(order.getId(), "PROCESS_PAYMENT", "SUCCESS",
                    "Payment approved, transaction " + payment.get("transactionId"));
        } catch (SagaStepException e) {
            logStep(order.getId(), "PROCESS_PAYMENT", "FAILED", e.getMessage());
            // ---- compensate: undo the steps that already succeeded ----
            boolean compensated = compensate(order);
            return finish(order, compensated ? "CANCELLED" : "COMPENSATION_PENDING", e.getMessage());
        }

        // ---- all steps succeeded ----
        return finish(order, "CONFIRMED", null);
    }

    // ======================= Cancel a confirmed order (compensation chain) =======================

    public CustomerOrder cancelOrder(Long id) {
        CustomerOrder order = findOrder(id);
        if (!"CONFIRMED".equals(order.getStatus())) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                    "Only CONFIRMED orders can be cancelled. Current status: " + order.getStatus());
        }
        boolean compensated = compensate(order);
        return finish(order, compensated ? "CANCELLED" : "COMPENSATION_PENDING",
                compensated ? "Cancelled by the customer"
                        : "Cancelled by the customer, but the compensation is not finished");
    }

    // ======================= Retry a compensation that failed =======================

    public CustomerOrder retryCompensation(Long id) {
        CustomerOrder order = findOrder(id);
        if (!"COMPENSATION_PENDING".equals(order.getStatus())) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                    "Only COMPENSATION_PENDING orders can be retried. Current status: " + order.getStatus());
        }
        boolean compensated = compensate(order);
        return finish(order, compensated ? "CANCELLED" : "COMPENSATION_PENDING", order.getFailureReason());
    }

    // ======================= Compensating transactions =======================

    // Undo in REVERSE order of the steps: first the payment, then the stock.
    // Both calls are idempotent, so running them again is safe.
    private boolean compensate(CustomerOrder order) {
        boolean paymentOk = refundPayment(order);
        boolean inventoryOk = releaseInventory(order);
        return paymentOk && inventoryOk;
    }

    private boolean refundPayment(CustomerOrder order) {
        try {
            paymentClient.post()
                    .uri("/api/payments/order/{orderId}/refund", order.getId())
                    .retrieve()
                    .toBodilessEntity();
            logStep(order.getId(), "COMPENSATE_PAYMENT", "SUCCESS", "Payment refunded (or nothing to refund)");
            return true;
        } catch (HttpClientErrorException.NotFound e) {
            logStep(order.getId(), "COMPENSATE_PAYMENT", "SUCCESS", "No payment found, nothing to refund");
            return true;
        } catch (RestClientException e) {
            logStep(order.getId(), "COMPENSATE_PAYMENT", "FAILED", "Could not refund: " + e.getMessage());
            return false;
        }
    }

    private boolean releaseInventory(CustomerOrder order) {
        try {
            inventoryClient.post()
                    .uri("/api/inventory/reservations/{orderId}/release", order.getId())
                    .retrieve()
                    .toBodilessEntity();
            logStep(order.getId(), "COMPENSATE_INVENTORY", "SUCCESS", "Reserved stock released");
            return true;
        } catch (HttpClientErrorException.NotFound e) {
            logStep(order.getId(), "COMPENSATE_INVENTORY", "SUCCESS", "No reservation found, nothing to release");
            return true;
        } catch (RestClientException e) {
            logStep(order.getId(), "COMPENSATE_INVENTORY", "FAILED", "Could not release stock: " + e.getMessage());
            return false;
        }
    }

    // ======================= Calls to the other services =======================

    private Map<String, Object> reserveInventory(CustomerOrder order) {
        Map<String, Object> body = new LinkedHashMap<>();
        body.put("orderId", order.getId());
        body.put("productId", order.getProductId());
        body.put("quantity", order.getQuantity());

        try {
            return inventoryClient.post()
                    .uri("/api/inventory/reservations")
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(body)
                    .retrieve()
                    .body(MAP_TYPE);
        } catch (RestClientResponseException e) {
            throw new SagaStepException("Inventory service: " + errorMessage(e));
        } catch (ResourceAccessException e) {
            throw new SagaStepException("Inventory service is unavailable");
        }
    }

    private Map<String, Object> processPayment(CustomerOrder order) {
        Map<String, Object> body = new LinkedHashMap<>();
        body.put("orderId", order.getId());
        body.put("customerName", order.getCustomerName());
        body.put("amount", order.getTotalAmount());

        try {
            return paymentClient.post()
                    .uri("/api/payments")
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(body)
                    .retrieve()
                    .body(MAP_TYPE);
        } catch (RestClientResponseException e) {
            throw new SagaStepException("Payment service: " + errorMessage(e));
        } catch (ResourceAccessException e) {
            throw new SagaStepException("Payment service is unavailable");
        }
    }

    // ======================= Helpers =======================

    private CustomerOrder finish(CustomerOrder order, String status, String reason) {
        order.setStatus(status);
        order.setFailureReason(reason);
        CustomerOrder saved = orderRepository.save(order);
        logStep(saved.getId(), "SAGA_RESULT", status, reason == null ? "Order completed successfully" : reason);
        return saved;
    }

    private void logStep(Long orderId, String step, String status, String message) {
        sagaLogRepository.save(new SagaLog(orderId, step, status, message));
    }

    private CustomerOrder findOrder(Long id) {
        return orderRepository.findById(id)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND,
                        "Order not found with id " + id));
    }

    private String errorMessage(RestClientResponseException e) {
        try {
            Map<?, ?> body = e.getResponseBodyAs(Map.class);
            if (body != null && body.get("message") != null) {
                return String.valueOf(body.get("message"));
            }
        } catch (RuntimeException ignored) {
            // fall through to the generic message
        }
        return "HTTP " + e.getStatusCode().value();
    }

    private RestClient buildClient(String baseUrl) {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(2000);
        requestFactory.setReadTimeout(5000);
        return RestClient.builder().baseUrl(baseUrl).requestFactory(requestFactory).build();
    }
}
package com.example.orderservice.service;

// Thrown when one step of the saga (reserve stock or take payment) fails
public class SagaStepException extends RuntimeException {

    public SagaStepException(String message) {
        super(message);
    }
}
package com.example.orderservice.controller;

import com.example.orderservice.entity.CustomerOrder;
import com.example.orderservice.entity.SagaLog;
import com.example.orderservice.service.OrderService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    private final OrderService orderService;

    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    // POST /api/orders   (starts the saga; check "status" in the response)
    @PostMapping
    public ResponseEntity<CustomerOrder> placeOrder(@RequestBody CustomerOrder order) {
        return ResponseEntity.status(HttpStatus.CREATED).body(orderService.placeOrder(order));
    }

    // GET /api/orders
    @GetMapping
    public List<CustomerOrder> getAllOrders() {
        return orderService.getAllOrders();
    }

    // GET /api/orders/{id}
    @GetMapping("/{id}")
    public ResponseEntity<CustomerOrder> getOrderById(@PathVariable Long id) {
        return orderService.getOrderById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // GET /api/orders/{id}/saga   (every step and compensation of the saga)
    @GetMapping("/{id}/saga")
    public List<SagaLog> getSagaLog(@PathVariable Long id) {
        return orderService.getSagaLog(id);
    }

    // PUT /api/orders/{id}/cancel   (refund payment + release stock)
    @PutMapping("/{id}/cancel")
    public CustomerOrder cancelOrder(@PathVariable Long id) {
        return orderService.cancelOrder(id);
    }

    // POST /api/orders/{id}/retry-compensation   (for orders in COMPENSATION_PENDING)
    @PostMapping("/{id}/retry-compensation")
    public CustomerOrder retryCompensation(@PathVariable Long id) {
        return orderService.retryCompensation(id);
    }
}
package com.example.orderservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class OrderServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderServiceApplication.class, args);
    }
}
spring.application.name=order-service
server.port=8081

# Database owned ONLY by order-service
spring.datasource.url=jdbc:mysql://localhost:3306/saga_order_db?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=false

server.error.include-message=always

# The order service is the saga orchestrator, so it needs the address of the other two services
inventory.service.url=http://localhost:8082
payment.service.url=http://localhost:8083Code language: PHP (php)

Step 6: Run all microservices one by one

i. Inventory service

ii. Payment service

iii. Order service

Scroll to Top