%

backend development

Distributed Transaction Processing: Saga Pattern in Golang*

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.

Published

October 19, 2026

Category

backend development

Reading time

29 min read

Author

Umoh Samuel

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 rolled back after retrying compensations: %v", data["order_id"], steps)
	return nil
}
 
// newSaga builds a fresh saga per order, since Execute holds the saga's lock for
// the whole run and a shared instance would process one order at a time.
func (s *Service) newSaga() *saga.Saga {
	return saga.New("order-processing").
		AddStep(saga.Step{
			Name:       "create-order",
			Action:     s.orders.CreateOrder,
			Compensate: s.orders.CancelOrder,
		}).
		AddStep(saga.Step{
			Name:       "reserve-inventory",
			Action:     s.inventory.ReserveStock,
			Compensate: s.inventory.ReleaseStock,
		}).
		AddStep(saga.Step{
			Name:       "process-payment",
			Action:     s.payments.ProcessPayment,
			Compensate: s.payments.RefundPayment,
		})
}
 
func newOrderID() (string, error) {
	b := make([]byte, 8)
	if _, err := rand.Read(b); err != nil {
		return "", fmt.Errorf("generate order id: %w", err)
	}
	return "ord_" + hex.EncodeToString(b), nil
}

The service has two jobs: accepting orders and processing them.

  • Events: This interface is how the service talks to the outside world. The service doesn't know Kafka exists. It just calls OrderCreated or CompensationFailed, and the Kafka adapter (which we will see soon) handles the rest. This also makes the service easy to test with a fake.
  • PlaceOrder: This is what the API calls. It validates the order, gives it an ID, calculates the total and publishes an OrderCreated event. It does not run the saga. It returns straight away with a PROCESSING status, and the real work happens in the background when a consumer picks up the event.
  • ProcessOrder: This is what the Kafka consumer calls. It copies what the steps need into the data map and runs the saga. There are three possible outcomes:
    • Every step worked, so we log it and we are done.
    • A step failed, but every compensation worked. The order failed cleanly, so we return an error for the logs and that's the end of it. There is nothing to retry.
    • A step failed, and some compensations failed too. The system is now half rolled back, which is the one case we can't leave alone. So we publish the failed compensations with CompensationFailed, and they get retried later.
  • RetryCompensation: This is what the retry consumers call. It only runs the compensations that failed, using the Compensate method from our saga. It never reruns the saga itself.
  • newSaga: This is where we define the actual flow. Each step is paired with its compensation, and the order we add them in is the order they run in.

The Steps and Their Compensations

Next, each step and its compensating action:

// internal/service/order/steps.go
 
package order
 
import (
	"context"
	"fmt"
	"sync"
)
 
type OrderService struct{}
 
func (o *OrderService) CreateOrder(ctx context.Context, data map[string]interface{}) error {
	orderID := data["order_id"].(string)
	fmt.Printf("Creating order %s\n", orderID)
	data["order_created"] = true
	return nil
}
 
func (o *OrderService) CancelOrder(ctx context.Context, data map[string]interface{}) error {
	orderID := data["order_id"].(string)
	fmt.Printf("Cancelling order %s\n", orderID)
	return nil
}
 
const releaseFailures = 2
 
type InventoryService struct {
	mu              sync.Mutex
	releaseAttempts map[string]int
}
 
func (i *InventoryService) ReserveStock(ctx context.Context, data map[string]interface{}) error {
	productID := data["product_id"].(string)
	quantity := number(data["quantity"])
	fmt.Printf("Reserving %d units of product %s\n", quantity, productID)
	data["stock_reserved"] = true
	return nil
}
 
func (i *InventoryService) ReleaseStock(ctx context.Context, data map[string]interface{}) error {
	orderID := data["order_id"].(string)
	productID := data["product_id"].(string)
	quantity := number(data["quantity"])
 
	i.mu.Lock()
	i.releaseAttempts[orderID]++
	attempt := i.releaseAttempts[orderID]
	i.mu.Unlock()
 
	if attempt <= releaseFailures {
		return fmt.Errorf("inventory service unavailable (release attempt %d)", attempt)
	}
 
	fmt.Printf("Releasing %d units of product %s (release attempt %d)\n", quantity, productID, attempt)
	return nil
}
 
func number(v interface{}) int {
	switch n := v.(type) {
	case int:
		return n
	case float64:
		return int(n)
	}
	return 0
}
 
const paymentLimit = 1000
 
type PaymentService struct{}
 
func (p *PaymentService) ProcessPayment(ctx context.Context, data map[string]interface{}) error {
	amount := data["amount"].(float64)
 
	if amount > paymentLimit {
		return fmt.Errorf("payment of $%.2f declined: insufficient funds", amount)
	}
 
	fmt.Printf("Processing payment of $%.2f\n", amount)
	data["payment_id"] = "pay_123456"
	return nil
}
 
func (p *PaymentService) RefundPayment(ctx context.Context, data map[string]interface{}) error {
	if paymentID, ok := data["payment_id"].(string); ok {
		fmt.Printf("Refunding payment %s\n", paymentID)
	}
	return nil
}

Of course, these are mocked for the sake of simplicity. In a real system, these would call other services over HTTP, gRPC, etc. Here, we mock everything, log each action, and simulate failures so we can follow along in the console:

  • ProcessPayment: Any payment above paymentLimit ($1000) gets declined. This is how we make the saga fail and roll back. When a payment works, it saves a payment_id in the data map, which RefundPayment would need to refund it.
  • ReleaseStock: This simulates an inventory service that is down. It keeps a count of release attempts for each order and fails the first releaseFailures attempts. With it set to 2, the first release fails, the first retry fails, and the second retry works. Set it to 4 or more if you want to see the message land in the DLQ.

One more thing. RefundPayment never actually runs in our example. Payment is the last step, so if it fails there is no completed payment to refund, and if it works there is nothing to undo.

Here is how a failed compensation moves through the retries:

Compensation retry flow through the Kafka retry topics

The Kafka Adapter

Next, the order adapter for Kafka:

// internal/adapters/kafka/orders.go
 
package kafka
 
import (
	"context"
	"encoding/json"
	"fmt"
 
	"github.com/IBM/sarama"
	"github.com/umohsamuel/distributed-transactions/internal/domain/order"
)
 
type OrderPublisher struct {
	producer *KafkaProducer
	router   *RetryRouter
}
 
func NewOrderPublisher(producer *KafkaProducer, router *RetryRouter) *OrderPublisher {
	return &OrderPublisher{producer: producer, router: router}
}
 
func (p *OrderPublisher) OrderCreated(ctx context.Context, o order.Order) error {
	value, err := json.Marshal(o)
	if err != nil {
		return fmt.Errorf("encode order: %w", err)
	}
 
	return p.producer.send(&sarama.ProducerMessage{
		Topic: CREATED.String(),
		Key:   sarama.StringEncoder(o.ID),
		Value: sarama.ByteEncoder(value),
	})
}
 
type compensationMessage struct {
	OrderID string                 `json:"order_id"`
	Steps   []string               `json:"steps"`
	Data    map[string]interface{} `json:"data"`
}
 
func (p *OrderPublisher) CompensationFailed(ctx context.Context, orderID string, steps []string, data map[string]interface{}, cause error) error {
	value, err := json.Marshal(compensationMessage{OrderID: orderID, Steps: steps, Data: data})
	if err != nil {
		return fmt.Errorf("encode compensation: %w", err)
	}
 
	return p.router.Schedule([]byte(orderID), value, CREATED.String(), cause)
}
 
type OrderProcessor interface {
	ProcessOrder(ctx context.Context, o order.Order) error
}
 
func OrderCreatedHandler(orders OrderProcessor) HandlerFunc {
	return func(ctx context.Context, msg Message) error {
		var o order.Order
		if err := json.Unmarshal(msg.Value, &o); err != nil {
			return fmt.Errorf("decode order: %w", err)
		}
 
		return orders.ProcessOrder(ctx, o)
	}
}
 
type CompensationRetrier interface {
	RetryCompensation(ctx context.Context, steps []string, data map[string]interface{}) error
}
 
func CompensationHandler(orders CompensationRetrier) HandlerFunc {
	return func(ctx context.Context, msg Message) error {
		var c compensationMessage
		if err := json.Unmarshal(msg.Value, &c); err != nil {
			return Permanent(fmt.Errorf("decode compensation: %w", err))
		}
 
		return orders.RetryCompensation(ctx, c.Steps, c.Data)
	}
}

This is the bridge between our service and Kafka. The OrderPublisher is what we pass to the service as its Events.

  • OrderCreated: It publishes the order to the created topic, using the order ID as the message key. Kafka sends messages with the same key to the same partition, so all messages for one order stay in order.
  • compensationMessage: This is what travels through the retry topics. Notice it carries the failed steps and the saga's data, not the order. This is the important part: a retry only runs the compensations that are still pending, and never reruns the saga from the top. It also carries data and not just the order, because steps add things to it as they run (like the payment_id).
  • CompensationFailed: It encodes the message and calls Schedule on the retry router, which sends it to the first retry topic.
  • OrderCreatedHandler and CompensationHandler: These decode the message and call the right method on the service. The first one handles new orders from the created topic. The second one handles compensations from the retry topics. If a compensation message can't even be decoded, retrying won't fix it, so we mark it Permanent and the router sends it straight to the DLQ.

In my implementation, I also added the retry router, the retry consumers, the DLQ and a graceful shutdown. For the sake of simplicity, and to keep this guide short and to the point, I will skip their code here. The retry tiers and DLQ work exactly like they do in my Kafka pipelines guide, and the shutdown is covered in my graceful shutdown guide. If you want to have a look, you can go through the repository linked at the end of this guide.

The API Adapter

Next, we add the order API adapter, since we will be serving orders through HTTP requests (ideally, that's how requests would come in for a traditional app):

// internal/adapters/api/order.go
 
package api
 
import (
	"context"
	"errors"
	"log"
	"net/http"
 
	"github.com/gin-gonic/gin"
	"github.com/umohsamuel/distributed-transactions/internal/domain/order"
)
 
type OrderPlacer interface {
	PlaceOrder(ctx context.Context, o order.Order) (order.Order, error)
}
 
type OrderHandler struct {
	orders OrderPlacer
}
 
func NewOrderHandler(orders OrderPlacer) *OrderHandler {
	return &OrderHandler{orders: orders}
}
 
func (h *OrderHandler) Register(r gin.IRouter) {
	r.POST("/orders", h.createOrder)
}
 
type createOrderRequest struct {
	UserID          string         `json:"user_id" binding:"required"`
	ProductID       string         `json:"product_id" binding:"required"`
	Quantity        int64          `json:"quantity" binding:"required,gt=0"`
	UnitPrice       int64          `json:"unit_price" binding:"gte=0"`
	ShippingAddress addressRequest `json:"shipping_address" binding:"required"`
}
 
type addressRequest struct {
	Street     string `json:"street" binding:"required"`
	City       string `json:"city" binding:"required"`
	State      string `json:"state"`
	Country    string `json:"country" binding:"required"`
	PostalCode string `json:"postal_code"`
}
 
type createOrderResponse struct {
	OrderID string            `json:"order_id"`
	Status  order.OrderStatus `json:"status"`
}
 
func (req createOrderRequest) toDomain() order.Order {
	return order.Order{
		UserID:    req.UserID,
		ProductID: req.ProductID,
		Item: order.OrderItem{
			Quantity:  req.Quantity,
			UnitPrice: req.UnitPrice,
		},
		ShippingAddress: order.Address{
			Street:     req.ShippingAddress.Street,
			City:       req.ShippingAddress.City,
			State:      req.ShippingAddress.State,
			Country:    req.ShippingAddress.Country,
			PostalCode: req.ShippingAddress.PostalCode,
		},
	}
}
 
func (h *OrderHandler) createOrder(c *gin.Context) {
	var req createOrderRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
 
	placed, err := h.orders.PlaceOrder(c.Request.Context(), req.toDomain())
	if err != nil {
		writeError(c, err)
		return
	}
 
	c.JSON(http.StatusAccepted, createOrderResponse{
		OrderID: placed.ID,
		Status:  placed.Status,
	})
}
 
func writeError(c *gin.Context, err error) {
	switch {
	case errors.Is(err, order.ErrInvalidOrder):
		c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
	default:
		log.Printf("%s %s: %v", c.Request.Method, c.FullPath(), err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "something went wrong, please try again"})
	}
}

The handler keeps the HTTP details away from our domain:

  • createOrderRequest: The binding tags let Gin validate the request body for us. A missing field or a quantity of 0 gets rejected with a 400 before it ever reaches the service.
  • toDomain: It converts the request into our order.Order. This keeps the JSON shape of the API separate from the order model, so either can change without breaking the other.
  • writeError: It maps our errors to status codes. An invalid order gets a 422, and anything else gets a 500 with a generic message, so we don't leak internal errors to the user.

Wiring Everything Together

Next, we wire everything together in main:

// cmd/main.go
 
package main
 
import (
	"context"
	"errors"
	"log"
	"net/http"
	"os"
	"os/signal"
	"sync"
	"syscall"
	"time"
 
	"github.com/gin-gonic/gin"
	"github.com/umohsamuel/distributed-transactions/internal/adapters/api"
	"github.com/umohsamuel/distributed-transactions/internal/adapters/kafka"
	ordersvc "github.com/umohsamuel/distributed-transactions/internal/service/order"
)
 
func main() {
	brokersUrl := []string{"localhost:9092"}
 
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
 
	producer, err := kafka.NewKafkaProducer(brokersUrl)
	if err != nil {
		log.Fatalf("Failed to initialize Kafka producer: %v", err)
	}
	defer producer.Close()
 
	router := kafka.NewRetryRouter(producer, kafka.RetryTopics, kafka.DLQ.String())
	orders := ordersvc.NewService(kafka.NewOrderPublisher(producer, router))
 
	groups := []struct {
		group  kafka.ConsumerGroup
		topic  kafka.Topics
		handle kafka.HandlerFunc
		router *kafka.RetryRouter
		delay  time.Duration
	}{
		{kafka.ORDERS_MAIN_GROUP, kafka.CREATED, kafka.OrderCreatedHandler(orders), nil, 0},
		{kafka.ORDERS_1M_RETRY_GROUP, kafka.RETRY_1M, kafka.CompensationHandler(orders), router, time.Second},
		{kafka.ORDERS_5M_RETRY_GROUP, kafka.RETRY_5M, kafka.CompensationHandler(orders), router, 5 * time.Second},
		{kafka.ORDERS_10M_RETRY_GROUP, kafka.RETRY_10M, kafka.CompensationHandler(orders), router, 10 * time.Second},
	}
 
	var wg sync.WaitGroup
	for _, g := range groups {
		consumer, err := kafka.NewKafkaConsumer(brokersUrl, g.group.String())
		if err != nil {
			log.Fatalf("Failed to start %s: %v", g.group, err)
		}
 
		handler := kafka.NewConsumerGroupHandler(g.handle, g.router, g.delay)
		wg.Go(func() {
			if err := consumer.Run(ctx, []string{g.topic.String()}, handler); err != nil {
				log.Printf("%s stopped: %v", g.group, err)
			}
		})
	}
 
	engine := gin.Default()
 
	v1 := engine.Group("/api/v1")
	api.NewOrderHandler(orders).Register(v1)
 
	srv := &http.Server{
		Addr:    ":8080",
		Handler: engine,
	}
 
	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Printf("HTTP server failed: %v", err)
			stop()
		}
	}()
 
	log.Println("Server and consumers running")
	<-ctx.Done()
	log.Println("Interruption detected, shutting down gracefully...")
 
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := srv.Shutdown(shutdownCtx); err != nil {
		log.Printf("HTTP shutdown: %v", err)
	}
 
	wg.Wait()
}

So basically:

  • We create a Kafka producer, a retry router and our order service. The router gets the list of retry topics and the DLQ, so it knows where a failed message goes next.
  • The groups table defines every consumer we run. There is one for the created topic and one for each retry topic.
  • The created consumer has no router. That's on purpose. When an order fails, the saga has already rolled it back and scheduled any failed compensations, so there is nothing left to retry. Only compensations go through the retry topics, never orders.
  • Each retry consumer has a router and a delay. If a compensation fails again, the router moves it to the next tier, and after the last tier, it goes to the DLQ.
  • The topics are named retry_1m, retry_5m and retry_10m, but the delays here are 1, 5 and 10 seconds. I shortened them for the demo, so you don't have to wait 16 minutes to see a message hit the DLQ. In production, you would use the real delays.
  • Each consumer runs in its own goroutine using wg.Go (this needs Go 1.25 or newer). Then we start the HTTP server and wait for a shutdown signal. When it comes, we stop the server and wait for the consumers to finish.

Testing

Now, how do we test this?

First, we need Kafka running. Here is the Docker Compose file for a single node Kafka in KRaft mode:

# docker-compose.yml
 
services:
  broker:
    image: apache/kafka:latest
    hostname: broker
    container_name: broker
    ports:
      - 9092:9092
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_NODE_ID: 1
      KAFKA_PROCESS_ROLES: broker,controller
      CLUSTER_ID: 8yPqetQpLSJu3qfIpWnnjQ
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT,CONTROLLER:PLAINTEXT
      KAFKA_LISTENERS: PLAINTEXT://broker:29092,CONTROLLER://broker:29093,PLAINTEXT_HOST://0.0.0.0:9092
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:29092,PLAINTEXT_HOST://localhost:9092
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@broker:29093
      KAFKA_LOG_DIRS: /tmp/kraft-combined-logs
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1

If you want to know what each of these settings does, I explained them in my Kafka pipelines guide.

Start Kafka, then run the server:

docker compose up -d
go run cmd/main.go

The order endpoint is http://localhost:8080/api/v1/orders. Every request below is a POST to that endpoint, and every valid order returns a 202:

{
  "order_id": "ord_7e840903b59d1253",
  "status": "PROCESSING"
}

The response only tells you the order was accepted. To see what actually happened, watch the console where the server is running.

The Happy Path

Send an order with a total of $400 (2 × $200), which is under our $1000 payment limit:

{
  "user_id": "u1",
  "product_id": "p1",
  "quantity": 2,
  "unit_price": 200,
  "shipping_address": {
    "street": "00, Allen Avenue",
    "city": "Ikeja",
    "country": "NG"
  }
}

Every step goes through, and you should see this in the console:

Creating order ord_7e840903b59d1253
Reserving 2 units of product p1
Processing payment of $400.00
Order ord_7e840903b59d1253 completed: [create-order reserve-inventory process-payment]

Payment Failure and Rollback

Now send an order with a total of $3000 (5 × $600), which is over the payment limit:

{
  "user_id": "u1",
  "product_id": "p1",
  "quantity": 5,
  "unit_price": 600,
  "shipping_address": {
    "street": "00, Allen Avenue",
    "city": "Ikeja",
    "country": "NG"
  }
}

The order is created and the stock is reserved, then the payment gets declined. The saga starts rolling back, but releasing the stock fails because our inventory service is "down". The rollback carries on and cancels the order, and the failed release is sent to the first retry topic:

Creating order ord_88dcc49ea1e17837
Reserving 5 units of product p1
Cancelling order ord_88dcc49ea1e17837
Routing message to topic: retry_1m (Attempt #1): compensate reserve-inventory: inventory service unavailable (release attempt 1)
Processing failed on topic created: order ord_88dcc49ea1e17837 failed at step "process-payment": payment of $3000.00 declined: insufficient funds; compensation retry scheduled: compensate reserve-inventory: inventory service unavailable (release attempt 1)

A second later, the first retry fails too, and the message moves to the next tier:

Processing failed on topic retry_1m. Routing to next stage...
Routing message to topic: retry_5m (Attempt #2): compensate reserve-inventory: inventory service unavailable (release attempt 2)

Five seconds after that, the inventory service is "back", and the release finally works:

Releasing 5 units of product p1 (release attempt 3)
Order ord_88dcc49ea1e17837 rolled back after retrying compensations: [reserve-inventory]

The order failed, but the system ended up clean. The stock was released and the order was cancelled. That's eventual consistency in action.

If you set releaseFailures to 4 in steps.go and send the same order again, the release fails on every tier and the message ends up in the DLQ. That's where a human steps in to fix it.

Bad Requests

Lastly, try sending an order with "quantity": 0, or remove the product_id field. Gin rejects it with a 400 before anything reaches Kafka.

Demo

Here is a demo of how all these concepts come together:

Conclusion

In this guide, we built an orchestrated saga in Go that keeps an order consistent across the order, inventory and payment services. The key takeaways are:

  • ACID transactions work great inside one database, but they can't span multiple microservices, each with its own database.
  • The saga pattern splits a business transaction into local transactions, each with a compensating transaction that undoes it.
  • When a step fails, the completed steps are undone in reverse order, and the failed step itself is not compensated.
  • A step that fails because of a business rule (like a declined payment) is a finished outcome, not something to retry.
  • A compensation that fails is the dangerous case, because it leaves the system half rolled back. Retry topics give it time to recover, and a DLQ catches the ones that never do.

The saga pattern maintains eventual consistency without distributed locks, and each service can use its own database and transaction model. But it does come with trade-offs:

  • Only eventual consistency: Intermediate states are visible to other processes. For a short time, someone could see a reserved stock for an order that is about to be cancelled.
  • More code to maintain: Every step needs a compensation, and that compensation has to be maintained alongside the forward logic. Some operations, like sending an email, can't really be undone at all.
  • Idempotency: Retries can run a compensation more than once, so your compensations must be idempotent. Releasing the same stock twice should not release double the stock.
  • Lack of isolation: The "I" in ACID is gone. Multiple sagas running at the same time can read and change the same data, which can cause data anomalies. A common fix is a semantic lock, like marking the order as PROCESSING while its saga runs, so other processes know not to trust it yet.

(If you want to see the full codebase, check out the repository. Play around with it and lmk what you think)

References