Skip to content

/spring-boot-saga-pattern

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

shell
$ npx -y skills add giuseppe-trisciuoglio/developer-kit --skill spring-boot-saga-pattern --agent claude-code

How it fires

How this skill gets triggered: by you, by Claude, or both.

  • Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.
  • You can call itInvoke it directly when you want it.
  • Slash command/spring-boot-saga-pattern
How auto-invocation works

Context preview

The summary Claude sees to decide when to auto-load this skill.

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

SKILL.md

spring-boot-saga-pattern.SKILL.md
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 Insuffici
Read more
Read it on GitHub ↗

Showing the first part of this file.

Ships withdeveloper-kit

Modular plugin marketplace for Claude Code and agentic CLIs, with validated, spec-driven skills, agents, commands, and workflows for Java, TypeScript, Python, PHP, AWS, and AI.

Get the whole plugin, auto-invoked
Stats
315
Stars
0
Views
37
Forks
Maintained
Maintenance
Python
Language
MIT
License
1mo ago
Last commit
9mo ago
Created

Repo: giuseppe-trisciuoglio/developer-kit

Other skills on developer-kit.