Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Saga Pattern Implementation in Go

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.

What is the Saga Pattern?

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.

Architecture

This implementation features:

  1. Choreography-based coordination: Services communicate through events, with no central coordinator.
  2. Compensation transactions: Each step has a corresponding compensation action for rollback.
  3. Event-driven workflow: Services react to events published on an event bus.
  4. In-memory implementation: For simplicity, all state is stored in memory.

Components

  • saga.SagaCoordinator: Interface for coordinating saga transactions
  • saga.StepHandler: Interface for service handlers to implement
  • saga.TransactionStore: Interface for storing transaction state
  • choreography.Coordinator: Choreography-based implementation of SagaCoordinator
  • choreography.EventBus: Interface for the event bus
  • choreography.MemoryEventBus: In-memory implementation of EventBus
  • saga.MemoryStore: In-memory implementation of TransactionStore

Example Services

Three example services are included:

  1. Order Service: Creates and cancels orders
  2. Inventory Service: Reserves and releases inventory
  3. Payment Service: Processes and refunds payments

Running the Example

The example demonstrates both success and failure scenarios:

  1. Success Scenario: All steps complete successfully
  2. Failure Scenario: The payment step fails, triggering compensation for previous steps

To run the example:

go run cmd/main.go

Real-World Considerations

In a production environment, you would need to:

  1. Replace the in-memory implementations with persistent storage (e.g., PostgreSQL, MongoDB)
  2. Use a real message broker for the event bus (e.g., RabbitMQ, Kafka)
  3. Add error handling, retries, and timeouts
  4. Implement monitoring and observability

Acknowledgements

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.

About

No description, website, or topics provided.

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages