Reliable Event Publishing: Transactional Outbox Pattern in Golang with Debezium
A practical guide to the transactional outbox pattern in Go. Write to your database and publish events atomically in a single transaction, then stream those events to Kafka with Debezium and change data capture.
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 the basics.
- Basic knowledge of the saga pattern. My guide on the saga pattern in Golang covers everything you need.
- Patience. I tried to keep this guide short. I failed.
The Problem
We have an e-commerce platform built with microservices, and we use the saga pattern to coordinate transactions across services. When a customer places an order, our order service receives and validates it. From there, it has to:
- Save the order to its database.
- Publish an event to the other services, like the inventory, payment and notification services, so they can continue the flow.
I guess you can see the problem now, right? How do we ensure that saving the order and publishing the event either both succeed or both fail?
The database and the message broker are two separate systems, and no single transaction can cover both of them. That leaves us with two options:
- Publish the event inside the database transaction: The event goes out, but there is no guarantee the transaction will commit. If it rolls back, the other services are now processing an order that does not exist.
- Publish the event after the transaction commits: The order is saved, but the service can crash before it publishes the event. The order now exists, but no other service will ever know about it.
This is called the dual write problem.
The Question
How do we atomically update the database and publish events to a message broker?
While noting that:
- If the database transaction commits, the events must be published. If it rolls back, they must not be published.
- Events must reach the message broker in the order the service published them, even when multiple instances of the service update the same aggregate.
The solution (I'm sure you guessed it) is to hire me!
Well, let's not get ahead of ourselves. We all know no recruiter reads these articles anyway (ouch).
The actual solution is the transactional outbox pattern.
The Transactional Outbox Pattern, Defined
The Transactional Outbox Pattern is a design pattern used in distributed systems to guarantee that a service reliably updates its local database and publishes a corresponding event to a message broker as a single atomic operation.
It solves the dual write problem. Instead of writing to both the database and the message broker, the service only writes to the database. It saves the outgoing event into a dedicated outbox table, in the same local ACID transaction as the business data. A separate process, known as the message relay, then reads the committed events from the outbox and publishes them to the message broker. This guarantees at-least-once delivery.
Building the Message Relay
There are two common ways to build the message relay:
- Polling.
- Change data capture (CDC).
Polling
With polling, the relay is a background worker that queries the outbox table on a timer. The outbox table will need one extra column, like published_at, so the relay can tell which events it has already sent.
Every second or so, the relay starts a transaction, gets a batch of unpublished events, publishes them to the broker, marks them as published and commits. If the relay crashes after it publishes an event but before it commits, the event is still unpublished in the database, so the next run publishes it again. That means polling also gives at-least-once delivery.
Polling is simple. It works with any database, and it doesn't need any extra infrastructure. But it has a few downsides:
- Constant load: The relay queries the table every second, even when nothing has changed.
- Latency: An event has to wait for the next poll before it is published.
- Cleanup: Published rows stay in the table until you delete them, so you need a cleanup job, or the table keeps growing.
- Ordering: With more than one relay, keeping events in order gets harder, because each relay works on its own batch.
Change Data Capture (CDC)
With CDC, the relay does not query the outbox table at all. It reads the database's transaction log instead and publishes new outbox rows as soon as they are committed. There is no polling, no extra column and no extra load on the table.
In this guide, we will focus on CDC, as it is the most widely used method in production.
Change Data Capture, Defined
Change data capture (CDC) is a technique for detecting and capturing changes made to data in a database and transmitting those changes to downstream systems. CDC enables near real-time data synchronization, replication and event-driven processing across systems after database changes occur.
So with CDC, the transactional outbox pattern works like this:
- The application writes both its business data and an event record into the outbox table in the same local database transaction.
- A CDC tool then reads the database's transaction log and sends those new outbox rows to a message broker like Apache Kafka.
The Write-Ahead Log
Most databases have a transaction log. MySQL has the binlog and MongoDB has the oplog. In Postgres, which is what we're using, it's called the write-ahead log (WAL). The WAL is an append-only file on disk where Postgres records every data change before applying it to the actual tables.
This is what makes CDC reliable. Postgres only sends a transaction's changes to the CDC tool after the transaction commits, so the relay only ever sees events from transactions that actually committed.
Introducing Debezium
Debezium is an open source distributed platform for change data capture. It runs on top of Kafka Connect, which is a tool for moving data between Kafka and other systems. Debezium connects to Postgres, reads the WAL, and turns each change into a Kafka message.
The Complete Flow
With all these pieces in place, the complete flow looks like this:
- The order service saves the order and an event row in the outbox table, in one transaction.
- Postgres writes both changes to the WAL when the transaction commits.
- Debezium reads the new outbox row from the WAL.
- Debezium publishes the event to Kafka.
- The notification service consumes the event and continues the flow.
At no point does the order service talk to Kafka. That is the whole point.
Implementing the Outbox Pattern in Golang
Now that we understand the flow, let's implement it in Go. We will build two services:
- The order service: It saves orders and writes the events to its outbox table.
- The notification service: It consumes the events from Kafka. It is very simple, because its only job is to show that the event arrived.
Project Structure
Our project is a monorepo with two services, and the shared infrastructure lives at the root:
. ├── docker-compose.yaml # Kafka, Kafka Connect and Kafka UI ├── Makefile ├── go.work ├── debezium/ │ └── order-outbox-connector.json # Debezium connector config └── services/ ├── order/ │ ├── cmd/ │ │ └── main.go │ ├── internal/ │ │ ├── domain/order/ # order entity and event payload │ │ ├── ports/ # repository interface │ │ ├── services/ # order service logic │ │ └── adapters/ │ │ ├── db/ │ │ │ ├── migrations/ # goose migrations │ │ │ ├── sqlc/ # queries and generated code │ │ │ └── repository/ # order repository with the outbox write │ │ └── transport/http/ # HTTP server and handlers │ ├── pkg/env/ # environment variables │ ├── Dockerfile │ └── docker-compose.yaml └── notification/ ├── main.go # Kafka consumer ├── Dockerfile └── docker-compose.yaml The Outbox Table
First, we create the outbox table in the service that publishes the event, which is our order service. We use goose for our migrations:
-- services/order/internal/adapters/db/migrations/20261118093459_create_outbox_table.sql -- +goose Up CREATE TABLE outbox ( id UUID PRIMARY KEY, aggregatetype VARCHAR(255) NOT NULL, aggregateid VARCHAR(255) NOT NULL, type VARCHAR(255) NOT NULL, payload JSONB NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE PUBLICATION order_outbox FOR TABLE outbox; -- +goose Down DROP PUBLICATION IF EXISTS order_outbox; DROP TABLE IF EXISTS outbox; The column names come from domain-driven design, and they're also the default column names the Debezium outbox event router looks for:
- aggregatetype: The type of aggregate the event belongs to, which is
orderfor us. Debezium uses it to pick the Kafka topic. - aggregateid: The ID of the aggregate, which is the order's ID. Debezium uses it as the Kafka message key. Kafka sends every message with the same key to the same partition, so all the events for one order stay in order.
- type: The event type, like
OrderCreated. In our setup, Debezium sends it as a message header calledeventType. - payload: The event data, which is the order as JSON. Debezium uses it as the message value.
The last line creates a publication. A publication is a list of tables Postgres is allowed to stream changes from. Debezium reads changes through this publication, so it only sees changes made to the outbox table.
The Orders Table
Next, the orders table:
-- services/order/internal/adapters/db/migrations/20261118100000_create_orders_table.sql -- +goose Up CREATE TABLE orders ( id UUID PRIMARY KEY, customer_id UUID NOT NULL, amount BIGINT NOT NULL CHECK (amount > 0), status VARCHAR(50) NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); -- +goose Down DROP TABLE IF EXISTS orders; The Queries
I don't want to make this guide longer than it needs to be, so I will keep this part short. We're using sqlc, which generates typed Go functions from our SQL queries.
-- services/order/internal/adapters/db/sqlc/queries/outbox.sql -- name: InsertOutboxEvent :exec INSERT INTO outbox (id, aggregatetype, aggregateid, type, payload) VALUES ($1, $2, $3, $4, $5); -- name: DeleteOutboxEvent :exec DELETE FROM outbox WHERE id = $1; -- services/order/internal/adapters/db/sqlc/queries/order.sql -- name: CreateOrder :one INSERT INTO orders (id, customer_id, amount, status) VALUES ($1, $2, $3, $4) RETURNING *; -- name: GetOrder :one SELECT * FROM orders WHERE id = $1; Running sqlc generate turns these into Go functions. sqlc also generates a WithTx method, which lets us run queries in transactions.
The Order Domain
Next, we create our order domain entity:
// services/order/internal/domain/order/order.go package order import ( "errors" "time" "github.com/google/uuid" ) type Status string const ( StatusPending Status = "PENDING" ) const ( AggregateType = "order" EventOrderCreated = "OrderCreated" ) var ( ErrNotFound = errors.New("order not found") ErrInvalidAmount = errors.New("amount must be greater than zero") ErrInvalidCustID = errors.New("customer id is required") ) type Order struct { ID uuid.UUID CustomerID uuid.UUID Amount int64 Status Status CreatedAt time.Time } func New(customerID uuid.UUID, amount int64) (*Order, error) { if customerID == uuid.Nil { return nil, ErrInvalidCustID } if amount <= 0 { return nil, ErrInvalidAmount } return &Order{ ID: uuid.New(), CustomerID: customerID, Amount: amount, Status: StatusPending, }, nil } // CreatedPayload is the body of the OrderCreated event that downstream // services (inventory, payment, notification) receive. type CreatedPayload struct { OrderID uuid.UUID `json:"order_id"` CustomerID uuid.UUID `json:"customer_id"` Amount int64 `json:"amount"` Status Status `json:"status"` CreatedAt time.Time `json:"created_at"` } AggregateType and EventOrderCreated are the values we write to the aggregatetype and type columns of the outbox. We keep them in the domain so the rest of the code doesn't hardcode them.
New validates the input and returns a new order with a PENDING status.
CreatedPayload is the event the other services receive. It's separate from the Order struct, so we can change the order without breaking the event the other services depend on.
The Order Repository Port
Next, we define the repository interface in our ports:
// services/order/internal/ports/order.go package ports import ( "context" "github.com/google/uuid" "github.com/umohsamuel/transactional-outbox/services/order/internal/domain/order" ) type OrderRepository interface { Create(ctx context.Context, o *order.Order) error GetByID(ctx context.Context, id uuid.UUID) (*order.Order, error) } This follows the hexagonal architecture. The service layer uses the interface defined in this port, and our adapter layer implements it. So the service is not tied to any specific implementation, and we can swap the implementation for anything else that satisfies the interface.
The Order Repository
This is the most important part of this guide. Next, we implement the order repository interface in our database adapter:
// services/order/internal/adapters/db/repository/order.go package repository import ( "context" "database/sql" "encoding/json" "errors" "fmt" "github.com/google/uuid" "github.com/umohsamuel/transactional-outbox/services/order/internal/adapters/db/sqlc" "github.com/umohsamuel/transactional-outbox/services/order/internal/domain/order" "github.com/umohsamuel/transactional-outbox/services/order/internal/ports" ) var _ ports.OrderRepository = (*OrderRepository)(nil) type OrderRepository struct { db *sql.DB q *sqlc.Queries } func NewOrderRepository(db *sql.DB) *OrderRepository { return &OrderRepository{db: db, q: sqlc.New(db)} } func (r *OrderRepository) Create(ctx context.Context, o *order.Order) error { tx, err := r.db.BeginTx(ctx, nil) if err != nil { return fmt.Errorf("begin tx: %w", err) } defer tx.Rollback() q := r.q.WithTx(tx) row, err := q.CreateOrder(ctx, sqlc.CreateOrderParams{ ID: o.ID, CustomerID: o.CustomerID, Amount: o.Amount, Status: string(o.Status), }) if err != nil { return fmt.Errorf("insert order: %w", err) } o.CreatedAt = row.CreatedAt payload, err := json.Marshal(order.CreatedPayload{ OrderID: o.ID, CustomerID: o.CustomerID, Amount: o.Amount, Status: o.Status, CreatedAt: o.CreatedAt, }) if err != nil { return fmt.Errorf("marshal event: %w", err) } eventID := uuid.New() if err := q.InsertOutboxEvent(ctx, sqlc.InsertOutboxEventParams{ ID: eventID, Aggregatetype: order.AggregateType, Aggregateid: o.ID.String(), Type: order.EventOrderCreated, Payload: payload, }); err != nil { return fmt.Errorf("insert outbox event: %w", err) } if err := q.DeleteOutboxEvent(ctx, eventID); err != nil { return fmt.Errorf("delete outbox event: %w", err) } if err := tx.Commit(); err != nil { return fmt.Errorf("commit: %w", err) } return nil } func (r *OrderRepository) GetByID(ctx context.Context, id uuid.UUID) (*order.Order, error) { row, err := r.q.GetOrder(ctx, id) if errors.Is(err, sql.ErrNoRows) { return nil, order.ErrNotFound } if err != nil { return nil, fmt.Errorf("get order: %w", err) } return &order.Order{ ID: row.ID, CustomerID: row.CustomerID, Amount: row.Amount, Status: order.Status(row.Status), CreatedAt: row.CreatedAt, }, nil } Create does everything inside one transaction:
- It starts a transaction and uses
WithTxto run all the queries inside it. The deferredRollbackdoes nothing once the transaction commits, but it undoes everything if we return early with an error. - It inserts the order.
- It builds the event payload and inserts it into the outbox table. The aggregate type is
order, the aggregate ID is the order's ID, and the type isOrderCreated. - It deletes the outbox row immediately after.
- It commits.
Either the order and the event both exist, or neither of them does. And notice that there is no call to a broker anywhere in this code.
You might be wondering why we delete the outbox row right after we insert it. Debezium does not read the table. It reads the WAL. The insert is already in the WAL by the time we commit, so Debezium still sees it and publishes the event. Deleting the row keeps the outbox table empty forever, so it never grows and we never have to clean it up.
GetByID maps the sqlc row back into our domain order and turns sql.ErrNoRows into our own ErrNotFound.
The Order Service
Next, the order service:
// services/order/internal/services/order.go package services import ( "context" "github.com/google/uuid" "github.com/umohsamuel/transactional-outbox/services/order/internal/domain/order" "github.com/umohsamuel/transactional-outbox/services/order/internal/ports" ) type OrderService struct { repo ports.OrderRepository } func NewOrderService(repo ports.OrderRepository) *OrderService { return &OrderService{repo: repo} } func (s *OrderService) CreateOrder(ctx context.Context, customerID uuid.UUID, amount int64) (*order.Order, error) { o, err := order.New(customerID, amount) if err != nil { return nil, err } if err := s.repo.Create(ctx, o); err != nil { return nil, err } return o, nil } func (s *OrderService) GetOrder(ctx context.Context, id uuid.UUID) (*order.Order, error) { return s.repo.GetByID(ctx, id) } Notice how simple this is. The service validates the order and hands it to the repository. It knows nothing about Kafka or events. Publishing is now just a side effect of saving.
Wrapping the Repositories and Services
Our service only has one repository and one service for now. But as it grows, we don't want main.go to create every repository and every service one by one. So we wrap them:
// services/order/internal/adapters/db/repository/repository.go package repository import "database/sql" type Repositories struct { Order *OrderRepository } func New(db *sql.DB) *Repositories { return &Repositories{ Order: NewOrderRepository(db), } } // services/order/internal/services/services.go package services import "github.com/umohsamuel/transactional-outbox/services/order/internal/ports" type Services struct { Order *OrderService } func New(orderRepo ports.OrderRepository) *Services { return &Services{ Order: NewOrderService(orderRepo), } } As the service grows, adding a repository is just a new field and one line in repository.New. services.New also takes the ports.OrderRepository interface and not the Repositories struct, so the service layer stays independent of the adapter.
The HTTP Handler
Next, the handler that exposes our orders over HTTP:
// services/order/internal/adapters/transport/http/handlers/order.go package handlers import ( "errors" "net/http" "github.com/gin-gonic/gin" "github.com/google/uuid" "github.com/umohsamuel/transactional-outbox/services/order/internal/domain/order" "github.com/umohsamuel/transactional-outbox/services/order/internal/services" ) type OrderHandler struct { svc *services.OrderService } func NewOrderHandler(s *services.Services) *OrderHandler { return &OrderHandler{svc: s.Order} } func (h *OrderHandler) RegisterR...