spring-boot-saga-pattern
giuseppe-trisciuoglio/developer-kit
Distributed transaction patterns for Spring Boot microservices using Saga Pattern with choreography or orchestration.
What is spring-boot-saga-pattern?
Implements the Saga Pattern to coordinate distributed transactions across microservices, replacing two-phase commit with sequences of local transactions and compensating actions. Use when building eventual-consistency workflows, handling transaction rollback across services, or coordinating complex business processes with Kafka, RabbitMQ, or Axon Framework.
- Design transaction flows with compensating transaction mappings
- Choose between choreography (event-driven) and orchestration (centralized coordinator) approaches
- Implement local ACID transactions in each service with idempotent event publishing
- Create compensating transactions for rollback and failure recovery
- Configure message brokers (Kafka/RabbitMQ) with exactly-once semantics and idempotent consumers
- Build saga orchestrators to manage complex workflows and state
How to install spring-boot-saga-pattern
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill spring-boot-saga-pattern- Spring Boot 2.x or 3.x project
- Message broker: Kafka or RabbitMQ configured and running
- Database for persisting saga state and local transactions
- Understanding of microservices architecture and eventual consistency concepts
How to use spring-boot-saga-pattern
- 1.Map your transaction flow and design compensating transactions for each forward step
- 2.Choose choreography (event-driven with Spring Cloud Stream) or orchestration (Axon Framework/Eventuate) based on complexity
- 3.Implement local @Transactional methods in each service that publish events after commit
- 4.Create idempotent compensating transaction methods for each service
- 5.Configure Kafka/RabbitMQ with transactional IDs and exactly-once semantics
- 6.For orchestration: build a SagaOrchestrator that listens for failures and triggers compensation
- 7.For choreography: implement @KafkaListener event handlers that chain steps and handle failures
- 8.Add metrics and monitoring to track saga status, compensation execution, and failure rates
Use cases
- Coordinating order processing across payment, inventory, and shipment services with automatic refunds on failure
- Implementing distributed refund workflows that trigger compensation across multiple services
- Building eventual-consistency workflows where strong consistency is not required
- Handling partial failures in multi-step business processes with automatic rollback
- Managing complex microservice orchestrations with centralized saga coordinators
- Microservices architects designing distributed transaction systems
- Backend engineers building Spring Boot microservices
- Teams implementing eventual-consistency patterns
- Developers replacing two-phase commit with scalable alternatives
spring-boot-saga-pattern FAQ
Choreography uses event-driven communication where each service listens for events and publishes new ones (decoupled but harder to track). Orchestration uses a centralized coordinator that explicitly commands each service (easier to monitor but creates a single point of coordination).
Use database constraints (unique keys), deduplication tables, or idempotency keys in your compensation logic. Test that running compensation multiple times produces the same result without side effects.
Implement dead-letter queues for failed compensation messages, set up alerts for stuck sagas, and use circuit breakers. Saga state must be persisted so you can manually intervene or retry.
No, sagas provide eventual consistency. The system will eventually reach a consistent state through compensation, but intermediate states may be inconsistent. Use sagas when eventual consistency is acceptable.
Use plain Kafka/RabbitMQ for simple choreography sagas. Use Axon Framework or Eventuate for complex orchestrations, especially in brownfield systems or when you need built-in saga management and recovery.
Full instructions (SKILL.md)
Source of truth, from giuseppe-trisciuoglio/developer-kit.
name: spring-boot-saga-pattern description: Provides distributed transaction patterns using the Saga Pattern for Spring Boot microservices. Use when implementing distributed transactions across services, handling compensating transactions, ensuring eventual consistency, or building choreography or orchestration-based sagas with Kafka, RabbitMQ, or Axon Framework. allowed-tools: Read, Write, Edit, Bash, Glob, Grep
Spring Boot Saga Pattern
Overview
Implements distributed transactions across microservices using the Saga Pattern. Replaces two-phase commit with a sequence of local transactions and compensating actions. Supports choreography (event-driven) and orchestration (centralized coordinator) approaches with Kafka, RabbitMQ, or Axon Framework.
When to Use
- Building distributed transactions across multiple microservices
- Replacing two-phase commit (2PC) with a more scalable solution
- Handling transaction rollback when a service fails
- Ensuring eventual consistency in microservices architecture
- Implementing compensating transactions for failed operations
- Coordinating complex business processes spanning multiple services
Trigger phrases: distributed transactions, saga pattern, compensating transactions, microservices transaction, eventual consistency, rollback across services, orchestration pattern, choreography pattern
Instructions
1. Design Transaction Flow
Map the sequence of operations and their compensating transactions:
Order → Payment → Inventory → Shipment
↓ ↓ ↓ ↓
Cancel Refund Release Cancel
Validation: Verify every forward step has a corresponding compensation.
2. Choose Implementation Approach
| Approach | Use Case | Stack |
|---|---|---|
| Choreography | Greenfield, few participants | Spring Cloud Stream + Kafka/RabbitMQ |
| Orchestration | Complex workflows, brownfield | Axon Framework, Eventuate Tram, Camunda |
Validation: Review team expertise and system complexity before choosing.
3. Implement Services with Local Transactions
Each service completes its local ACID transaction atomically:
@Service
@RequiredArgsConstructor
public class OrderService {
private final OrderRepository orderRepository;
private final KafkaTemplate<String, Object> kafka;
@Transactional
public Order createOrder(CreateOrderCommand cmd) {
Order order = orderRepository.save(new Order(cmd.orderId(), cmd.items()));
kafka.send("order.created", new OrderCreatedEvent(order.getId(), order.getItems()));
return order;
}
}
Validation: Test that local transaction commits before event is published.
4. Implement Compensating Transactions
Every forward operation requires an idempotent compensation:
@Service
@RequiredArgsConstructor
public class PaymentService {
private final PaymentRepository paymentRepository;
private final KafkaTemplate<String, Object> kafka;
public void processPayment(PaymentRequest request) {
Payment payment = paymentRepository.save(new Payment(request.orderId(), request.amount()));
kafka.send("payment.processed", new PaymentProcessedEvent(payment.getId(), request.orderId()));
}
@Transactional
public void refundPayment(String paymentId) {
paymentRepository.findById(paymentId)
.ifPresent(p -> {
p.setStatus(REFUNDED);
paymentRepository.save(p);
kafka.send("payment.refunded", new PaymentRefundedEvent(paymentId));
});
}
}
Validation: Confirm compensation can execute safely multiple times (idempotency).
5. Set Up Message Broker
Configure Kafka with idempotent consumers:
@Configuration
@EnableKafka
public class KafkaConfig {
@Bean
public ConcurrentKafkaListenerContainerFactory<String, Object> kafkaListenerContainerFactory(
ConsumerFactory<String, Object> consumerFactory) {
ConcurrentKafkaListenerContainerFactory<String, Object> factory =
new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory);
factory.setCommonErrorHandler(new DefaultErrorHandler());
return factory;
}
}
Validation: Enable transactional ID and verify exactly-once semantics.
6. Implement Saga Orchestrator (Orchestration Only)
@Service
@RequiredArgsConstructor
public class OrderSagaOrchestrator {
private final KafkaTemplate<String, Object> kafka;
private final SagaStateRepository sagaStateRepo;
public void startSaga(OrderRequest request) {
String sagaId = UUID.randomUUID().toString();
sagaStateRepo.save(new SagaState(sagaId, STARTED, LocalDateTime.now()));
kafka.send("saga.order.start", new StartOrderSagaCommand(sagaId, request));
}
@KafkaListener(topics = "payment.failed")
public void handlePaymentFailed(PaymentFailedEvent event) {
kafka.send("order.compensate", new CompensateOrderCommand(event.getSagaId()));
kafka.send("inventory.compensate", new ReleaseInventoryCommand(event.getSagaId()));
sagaStateRepo.updateStatus(event.getSagaId(), FAILED);
}
}
Validation: Verify saga state persists before sending commands. Check compensation triggers on each failure path.
7. Implement Event Handlers (Choreography Only)
@Service
public class OrderEventHandler {
private final OrderService orderService;
private final KafkaTemplate<String, Object> kafka;
@KafkaListener(topics = "payment.processed", groupId = "order-service")
public void onPaymentProcessed(PaymentProcessedEvent event) {
try {
InventoryReservedEvent result = orderService.reserveInventory(event.toInventoryRequest());
kafka.send("inventory.reserved", result);
} catch (InsufficientInventoryException e) {
kafka.send("inventory.insufficient", new InsufficientInventoryEvent(event.getOrderId(), event.getPaymentId()));
}
}
}
Validation: Test that each event handler correctly triggers the next step or compensation.
8. Add Monitoring and Observability
@Configuration
public class SagaMetricsConfig {
@Bean
public MeterRegistry meterRegistry() {
return new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
}
}
Track: saga execution duration, compensation count, failure rate, stuck sagas.
Validation: Set up alerts for sagas exceeding expected duration.
Best Practices
Design:
- Make compensating transactions idempotent using database constraints or deduplication tables
- Use immutable events (Java records) to prevent accidental mutation
- Store saga state in persistent storage for recovery
Error Handling:
- Implement circuit breakers for inter-service calls
- Use dead-letter queues for messages exceeding retry limits
- Set appropriate timeouts per saga step (30s default, configurable)
Monitoring:
- Track saga status: PENDING, COMPLETED, COMPENSATING, FAILED
- Monitor compensation execution time
- Alert when sagas exceed SLA duration
Constraints and Warnings
- Every forward transaction MUST have a corresponding compensating transaction
- Compensating transactions MUST be idempotent to handle retry scenarios
- Saga state MUST be persisted to handle failures and recovery
- Never use synchronous communication between saga participants
- Sagas provide eventual consistency, not strong consistency
- Test all failure scenarios including partial failures
- Consider Axon Framework or Eventuate for complex orchestrations
- Ensure message brokers are highly available
Examples
Choreography-Based Saga
// Application.java
@SpringBootApplication
@EnableKafka
@EnableKafkaListeners
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
// Event Classes (immutable)
public record OrderCreatedEvent(String orderId, List<OrderItem> items) {}
public record PaymentProcessedEvent(String paymentId, String orderId) {}
public record InventoryReservedEvent(String reservationId, String orderId) {}
public record PaymentFailedEvent(String orderId, String reason) {}
public record InsufficientInventoryEvent(String orderId, String paymentId) {}
// OrderService with compensation
@Service
@RequiredArgsConstructor
public class OrderService {
private final OrderRepository orderRepository;
private final KafkaTemplate<String, Object> kafka;
@KafkaListener(topics = "payment.failed", groupId = "order-service")
public void handleCompensation(PaymentFailedEvent event) {
orderRepository.findByOrderId(event.orderId())
.ifPresent(order -> {
order.setStatus(CANCELLED);
orderRepository.save(order);
});
}
}
Orchestration-Based Saga with Axon Framework
// Command
@Aggregate
public class OrderAggregate {
@AggregateIdentifier
private String orderId;
@CommandHandler
public OrderAggregate(CreateOrderCommand cmd) {
apply(new OrderCreatedEvent(cmd.orderId(), cmd.items()));
}
@EventSourcingHandler
public void on(OrderCreatedEvent event) {
this.orderId = event.orderId();
}
@CommandHandler
public void handle(CancelOrderCommand cmd) {
apply(new OrderCancelledEvent(cmd.orderId(), cmd.reason()));
}
}
References
Related skills
More from giuseppe-trisciuoglio/developer-kit and the wider catalog.

spring-boot-security-jwt
JWT authentication and authorization for Spring Boot 3.5.x with Spring Security 6.x and JJWT token management.

spring-boot-test-patterns
Comprehensive testing patterns for Spring Boot with JUnit 5, Mockito, Testcontainers, and slice testing.

spring-data-jpa
Spring Data JPA patterns for repositories, entities, queries, pagination, auditing, and transactions.

spring-data-neo4j
Spring Data Neo4j integration patterns for graph database mapping, repositories, and Cypher queries in Spring Boot.

tailwind-css-patterns
Utility-first Tailwind CSS patterns for responsive, accessible component styling.

tailwind-design-system
Build consistent UI component libraries with Tailwind CSS v4.1+ and shadcn/ui design tokens.