A practical guide to distributed transactions with the saga pattern in Go. Build an orchestrated saga, roll back failed steps with compensating transactions, and retry failed compensations with Kafka retry topics and a dead letter queue.

Prerequisites

What do you need to follow along?

  • Working knowledge of Golang.
  • Go & Docker installed on your PC.
  • Basic knowledge of Kafka. If you need a refresher, my guide on fault-tolerant Kafka pipelines covers everything we use here.
  • At least 8 hours of sleep (too much to ask for?)

The Monolith

Say you have a small e-commerce web app (for simplicity, and also because I want it to match my code examples). You built it as a monolith, and everything works well together.

In this system, when a user makes a purchase, everything happens in one app with one database. So we can use a database transaction to perform all the operations needed. For simplicity, say our operations are:

  1. Place the order.
  2. Reserve the stock.
  3. Process the payment.

Three simple enough steps. Since they all run in a single database transaction, if one fails, the database rolls back the previous steps. That all-or-nothing behaviour is one of the guarantees of an ACID transaction.

ACID, Defined

ACID is an acronym that refers to the set of 4 key properties that define a transaction:

  • Atomicity: Each statement in a transaction (to read, write, update or delete data) is treated as a single unit. Either the entire statement is executed, or none of it is executed.
  • Consistency: Ensures that transactions only make changes to tables in predefined, predictable ways. Transactional consistency ensures that corruption or errors in your data do not create unintended consequences for the integrity of your table.
  • Isolation: When multiple users are reading and writing from the same table all at once, isolation of their transactions ensures that the concurrent transactions don't interfere with or affect one another. Each request can occur as though they were occurring one by one, even though they're actually occurring simultaneously.
  • Durability: Ensures that changes to your data made by successfully executed transactions will be saved, even in the event of system failure.

ACID transactions ensure the highest possible data reliability and integrity. They ensure that your data never falls into an inconsistent state because of an operation that only partially completes.

Splitting Into Microservices

Now say your app grows. Traffic picks up, Black Friday is around the corner, and the monolith can't keep up. So you split it into microservices that are loosely coupled, each with its own database, and each able to scale on its own.

When a user makes a purchase now, the flow changes. The purchase touches three services instead of one:

  1. The order service.
  2. The inventory service.
  3. The payment service.

There is no single database transaction that can wrap all three anymore. So how do we ensure ACID when one purchase spans every service?

Easy. We just hope nothing ever fails halfway through a purchase. And if something does? Who cares?

There, fixed!

Okay, seriously now. How do we get an ACID-like transaction across different microservices?

Distributed Transactions, Defined

A distributed transaction is an operation within a distributed environment that spans multiple independent network nodes, databases, or microservices, ensuring that all parts either succeed or fail together as a single atomic unit.

There are two main ways to approach distributed transactions:

  1. Two-phase commit (2PC).
  2. The saga pattern.

2PC uses a coordinator to run a transaction across every participant in two phases:

  • Prepare phase: The coordinator asks each participant if it can commit. Each participant locks the data it needs and votes yes or no.
  • Commit phase: If every participant votes yes, the coordinator tells them all to commit. If any participant votes no, it tells them all to roll back.

The problem with this is that every participant holds its locks until the coordinator decides. One slow participant, or a coordinator that crashes in the middle, leaves everyone else blocked and waiting.

In this article, I'll be focusing on the saga pattern, as it is the one used in most production implementations today.

The Saga Pattern

The saga pattern takes a different approach. Instead of one big transaction that locks every service until everyone agrees, it splits the work into smaller local transactions that each commit on their own.

In the saga pattern, we implement each business transaction that spans multiple services as a saga. A saga is a reliably coordinated sequence of local transactions. The coordination mechanism, which often uses asynchronous messaging, ensures that the saga finishes: either all steps complete successfully or, if a local transaction fails because it violates a business rule, the changes made by the completed steps are undone by compensating transactions.

The compensating transactions run in reverse order, so the last step that completed is the first one we undo.

Eventual Consistency

So how does the data stay consistent? The magic word is eventual consistency.

The idea is that the data (the user's order data in our example) stays consistent, but no longer within a single transaction. In practice, there's a slight delay (usually milliseconds) during which the system is inconsistent, but then it catches up. When something fails and has to be retried, as we'll see later, that delay can stretch to a few minutes.

Our Order Saga

Here is what the saga looks like for our order example:

Saga flowchart for the order processing example

When a step fails, the saga only undoes the steps that completed before it. The failed step itself has nothing to undo. For example, if process-payment fails, no money was taken, so there is nothing to refund. The saga releases the reserved stock, then cancels the order.

Choreography vs Orchestration

There are two ways of coordinating sagas:

  • Choreography: Each local transaction publishes domain events that trigger local transactions in other services. There is no central coordinator. Each service listens for events and knows what to do next.
  • Orchestration: An orchestrator (an object) tells the participants which local transactions to execute. The whole flow, including the rollback, lives in one place.

In our Go example, we will be using orchestration.

Implementing the Saga in Golang

Since we now understand how sagas work, let's implement one in Golang, in our example e-commerce web app (which by now I have forced you to visualize 4 times, you're welcome).

Project Structure

Here is how the code is laid out:

cmd/main.go wires everything together internal/domain/saga the reusable saga internal/domain/order the order model internal/service/order the order service and the saga steps internal/adapters/kafka producer, consumers, retry topics internal/adapters/api the HTTP handler 

The Saga

First, we define our saga and its steps, along with the basic functionality like adding a step and executing the saga:

// internal/domain/saga/saga.go package saga import ( "context" "errors" "fmt" "slices" "sync" ) type Step struct { Name string Action func(ctx context.Context, data map[string]interface{}) error Compensate func(ctx context.Context, data map[string]interface{}) error } type Saga struct { name string steps []Step mu sync.Mutex } func New(name string) *Saga { return &Saga{ name: name, steps: make([]Step, 0), } } func (s *Saga) AddStep(step Step) *Saga { s.mu.Lock() defer s.mu.Unlock() s.steps = append(s.steps, step) return s } type ExecutionResult struct { Success bool FailedStep string Error error CompletedSteps []string RolledBack bool PendingCompensations []string CompensationError error } func (s *Saga) Execute(ctx context.Context, data map[string]interface{}) ExecutionResult { s.mu.Lock() defer s.mu.Unlock() completedSteps := make([]string, 0, len(s.steps)) result := ExecutionResult{Success: true} for _, step := range s.steps { select { case <-ctx.Done(): // Context cancelled, rollback return s.fail(ctx, step.Name, ctx.Err(), completedSteps, data) default: } if err := step.Action(ctx, data); err != nil { return s.fail(ctx, step.Name, err, completedSteps, data) } completedSteps = append(completedSteps, step.Name) } result.CompletedSteps = completedSteps return result } func (s *Saga) fail(ctx context.Context, stepName string, err error, completedSteps []string, data map[string]interface{}) ExecutionResult { toCompensate := slices.Clone(completedSteps) slices.Reverse(toCompensate) pending, compErr := s.compensate(context.WithoutCancel(ctx), toCompensate, data) return ExecutionResult{ Success: false, FailedStep: stepName, Error: err, CompletedSteps: completedSteps, RolledBack: compErr == nil, PendingCompensations: pending, CompensationError: compErr, } } func (s *Saga) Compensate(ctx context.Context, stepNames []string, data map[string]interface{}) ([]string, error) { s.mu.Lock() defer s.mu.Unlock() return s.compensate(ctx, stepNames, data) } func (s *Saga) compensate(ctx context.Context, stepNames []string, data map[string]interface{}) ([]string, error) { stepMap := make(map[string]Step) for _, step := range s.steps { stepMap[step.Name] = step } var failed []string var errs []error for _, stepName := range stepNames { step, ok := stepMap[stepName] if !ok { return nil, fmt.Errorf("saga %s has no step %q", s.name, stepName) } if step.Compensate != nil { if err := step.Compensate(ctx, data); err != nil { failed = append(failed, stepName) errs = append(errs, fmt.Errorf("compensate %s: %w", stepName, err)) } } } return failed, errors.Join(errs...) } 

So in the code above, we define a Step, the Saga that holds the steps, and the functions that run and undo them:

  • Step: Each step has a name, an Action (the local transaction) and a Compensate (the function that undoes it). Both receive the same data map, so a step can leave something behind for later steps or for its own compensation. For example, the payment step saves a payment_id that the refund needs.
  • AddStep: It returns the saga itself, so we can chain steps together when we build the saga.
  • Execute: It runs the steps in order. Before each step, it checks if the context was cancelled. If a step fails, it stops and hands over to fail. Every step that succeeds gets added to completedSteps, which is how the saga knows what to undo later.
  • fail: It reverses the completed steps and runs their compensations, so the last thing we did is the first thing we undo. It uses context.WithoutCancel(ctx) because a rollback has to finish even when the app is shutting down. We don't want to stop halfway through undoing an order.
  • compensate: It runs each compensation and keeps going even when one fails, so one stuck step doesn't stop the others from being undone. Any compensation that fails is collected into a list, and errors.Join combines all their errors into one.
  • Compensate: This is the public version of compensate. We will use it later to retry the compensations that failed.

The ExecutionResult tells the caller exactly how things went:

  • Success is true when every step completed.
  • RolledBack is true when a step failed but every compensation worked.
  • PendingCompensations lists the compensations that failed, so we can retry them.

The Order Model

Next, let's define our order structure:

// internal/domain/order/order.go package order import ( "errors" "fmt" ) var ErrInvalidOrder = errors.New("invalid order") type OrderStatus string type PaymentStatus string const ( StatusProcessing OrderStatus = "PROCESSING" PaymentPaid PaymentStatus = "PAID" ) type Address struct { Street string `json:"street"` City string `json:"city"` State string `json:"state"` Country string `json:"country"` PostalCode string `json:"postal_code,omitempty"` } type OrderItem struct { Quantity int64 `json:"quantity"` UnitPrice int64 `json:"unit_price"` Total int64 `json:"total"` } type Order struct { ID string `json:"id"` Status OrderStatus `json:"status"` UserID string `json:"user_id"` ProductID string `json:"product_id"` Item OrderItem `json:"item"` ShippingAddress Address `json:"shipping_address"` PaymentStatus PaymentStatus `json:"payment_status"` } func (o Order) Validate() error { switch { case o.UserID == "": return fmt.Errorf("%w: user_id is required", ErrInvalidOrder) case o.ProductID == "": return fmt.Errorf("%w: product_id is required", ErrInvalidOrder) case o.Item.Quantity <= 0: return fmt.Errorf("%w: quantity must be greater than 0", ErrInvalidOrder) case o.Item.UnitPrice < 0: return fmt.Errorf("%w: unit_price cannot be negative", ErrInvalidOrder) } return nil } 

This is a plain order with a single item and a shipping address. Validate wraps every error with ErrInvalidOrder. That way, any code further up can check errors.Is(err, order.ErrInvalidOrder) and know the order itself was bad, without parsing error messages. Our API uses this to return a 422 instead of a 500.

The Order Service

To test our saga, we need to be able to place orders. So let's define our order service and the steps a placed order goes through:

// internal/service/order/order.go package order import ( "context" "crypto/rand" "encoding/hex" "fmt" "log" "github.com/umohsamuel/distributed-transactions/internal/domain/order" "github.com/umohsamuel/distributed-transactions/internal/domain/saga" ) type Events interface { OrderCreated(ctx context.Context, o order.Order) error CompensationFailed(ctx context.Context, orderID string, steps []string, data map[string]interface{}, cause error) error } type Service struct { events Events orders *OrderService inventory *InventoryService payments *PaymentService } func NewService(events Events) *Service { return &Service{ events: events, orders: &OrderService{}, inventory: &InventoryService{releaseAttempts: make(map[string]int)}, payments: &PaymentService{}, } } func (s *Service) PlaceOrder(ctx context.Context, o order.Order) (order.Order, error) { if err := o.Validate(); err != nil { return order.Order{}, err } id, err := newOrderID() if err != nil { return order.Order{}, err } o.ID = id o.Status = order.StatusProcessing o.PaymentStatus = "" o.Item.Total = o.Item.Quantity * o.Item.UnitPrice if err := s.events.OrderCreated(ctx, o); err != nil { return order.Order{}, fmt.Errorf("publish order created: %w", err) } return o, nil } // ProcessOrder runs the order saga. It is the entry point for the Kafka consumer. func (s *Service) ProcessOrder(ctx context.Context, o order.Order) error { if err := o.Validate(); err != nil { return err } data := map[string]interface{}{ "order_id": o.ID, "product_id": o.ProductID, "quantity": int(o.Item.Quantity), "amount": float64(o.Item.Total), } result := s.newSaga().Execute(ctx, data) if !result.Success { if !result.RolledBack { if err := s.events.CompensationFailed(ctx, o.ID, result.PendingCompensations, data, result.CompensationError); err != nil { return fmt.Errorf("order %s: schedule compensation retry: %w", o.ID, err) } return fmt.Errorf("order %s failed at step %q: %w; compensation retry scheduled: %v", o.ID, result.FailedStep, result.Error, result.CompensationError) } return fmt.Errorf("order %s failed at step %q and was rolled back: %w", o.ID, result.FailedStep, result.Error) } log.Printf("Order %s completed: %v", o.ID, result.CompletedSteps) return nil } func (s *Service) RetryCompensation(ctx context.Context, steps []string, data map[string]interface{}) error { if _, err := s.newSaga().Compensate(ctx, steps, data); err != nil { return err } log.Printf("Order %v ro...
Source:https://dev.to/umohsg/distributed-transaction-processing-saga-pattern-in-golang-40pj