This project demonstrates a distributed transaction system using the Saga pattern in Go. It includes a choreography-based implementation with compensation transactions for failure scenarios.
The Saga pattern is a design pattern for managing distributed transactions in microservices architecture. Instead of using a single, atomic transaction across multiple services, the Saga pattern breaks down the transaction into a sequence of local transactions, each with its own compensation transaction for rollback in case of failure.
This implementation features:
- Choreography-based coordination: Services communicate through events, with no central coordinator.
- Compensation transactions: Each step has a corresponding compensation action for rollback.
- Event-driven workflow: Services react to events published on an event bus.
- In-memory implementation: For simplicity, all state is stored in memory.
saga.SagaCoordinator: Interface for coordinating saga transactionssaga.StepHandler: Interface for service handlers to implementsaga.TransactionStore: Interface for storing transaction statechoreography.Coordinator: Choreography-based implementation of SagaCoordinatorchoreography.EventBus: Interface for the event buschoreography.MemoryEventBus: In-memory implementation of EventBussaga.MemoryStore: In-memory implementation of TransactionStore
Three example services are included:
- Order Service: Creates and cancels orders
- Inventory Service: Reserves and releases inventory
- Payment Service: Processes and refunds payments
The example demonstrates both success and failure scenarios:
- Success Scenario: All steps complete successfully
- Failure Scenario: The payment step fails, triggering compensation for previous steps
To run the example:
go run cmd/main.goIn a production environment, you would need to:
- Replace the in-memory implementations with persistent storage (e.g., PostgreSQL, MongoDB)
- Use a real message broker for the event bus (e.g., RabbitMQ, Kafka)
- Add error handling, retries, and timeouts
- Implement monitoring and observability
This implementation is inspired by common patterns in distributed systems and microservices architecture. It's designed to be educational and to demonstrate the core concepts of the Saga pattern.