<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Samuel Umoh  on Medium]]></title>
        <description><![CDATA[Stories by Samuel Umoh  on Medium]]></description>
        <link>https://medium.com/@umohsg?source=rss-98d0e0748007------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*p9-Nj9WmDKhmxURDMtUGDQ.jpeg</url>
            <title>Stories by Samuel Umoh  on Medium</title>
            <link>https://medium.com/@umohsg?source=rss-98d0e0748007------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:10:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@umohsg/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Reliable Event Publishing: Transactional Outbox Pattern in Golang with Debezium]]></title>
            <link>https://medium.com/@umohsg/reliable-event-publishing-transactional-outbox-pattern-in-golang-with-debezium-6af580dd586c?source=rss-98d0e0748007------2</link>
            <guid isPermaLink="false">https://medium.com/p/6af580dd586c</guid>
            <category><![CDATA[debezium]]></category>
            <category><![CDATA[transactional-outbox]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[outbox-pattern]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Samuel Umoh ]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 17:48:11 GMT</pubDate>
            <atom:updated>2026-11-19T17:48:11.152Z</atom:updated>
            <content:encoded><![CDATA[<p>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.</p><h3>Prerequisites</h3><p>What do you need to follow along?</p><ul><li>Working knowledge of Golang.</li><li>Go &amp; Docker installed on your PC.</li><li>Basic knowledge of Kafka. If you need a refresher, my guide on <a href="https://www.umohsg.com/blog/building-fault-tolerant-event-driven-kafka-pipelines-in-go-reliable-reprocessing-dead-letter-queues-1f6874d4-270c-48e1-9798-324b494c7f0e">fault-tolerant Kafka pipelines</a> covers the basics.</li><li>Basic knowledge of the saga pattern. My guide on the <a href="https://www.umohsg.com/blog/distributed-transaction-processing-saga-pattern-in-golang-60084aca-428a-413e-8388-7d1d0d6b22c3">saga pattern in Golang</a> covers everything you need.</li><li>Patience. I tried to keep this guide short. I failed.</li></ul><h3>The Problem</h3><p>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:</p><ul><li>Save the order to its database.</li><li>Publish an event to the other services, like the inventory, payment and notification services, so they can continue the flow.</li></ul><p>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?</p><p>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:</p><ul><li>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.</li><li>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.</li></ul><p>This is called the dual write problem.</p><h3>The Question</h3><p>How do we atomically update the database and publish events to a message broker?</p><p>While noting that:</p><ul><li>If the database transaction commits, the events must be published. If it rolls back, they must not be published.</li><li>Events must reach the message broker in the order the service published them, even when multiple instances of the service update the same aggregate.</li></ul><p>The solution (I’m sure you guessed it) is to hire me!</p><p>Well, let’s not get ahead of ourselves. We all know no recruiter reads these articles anyway (ouch).</p><p>The actual solution is the transactional outbox pattern.</p><h3>The Transactional Outbox Pattern, Defined</h3><p>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.</p><p>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.</p><h3>Building the Message Relay</h3><p>There are two common ways to build the message relay:</p><ul><li>Polling.</li><li>Change data capture (CDC).</li></ul><h3>Polling</h3><p>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.</p><p>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.</p><p>Polling is simple. It works with any database, and it doesn’t need any extra infrastructure. But it has a few downsides:</p><ul><li>Constant load: The relay queries the table every second, even when nothing has changed.</li><li>Latency: An event has to wait for the next poll before it is published.</li><li>Cleanup: Published rows stay in the table until you delete them, so you need a cleanup job, or the table keeps growing.</li><li>Ordering: With more than one relay, keeping events in order gets harder, because each relay works on its own batch.</li></ul><h3>Change Data Capture (CDC)</h3><p>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.</p><p>In this guide, we will focus on CDC, as it is the most widely used method in production.</p><h3>Change Data Capture, Defined</h3><p>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.</p><p>So with CDC, the transactional outbox pattern works like this:</p><ul><li>The application writes both its business data and an event record into the outbox table in the same local database transaction.</li><li>A CDC tool then reads the database’s transaction log and sends those new outbox rows to a message broker like Apache Kafka.</li></ul><h3>The Write-Ahead Log</h3><p>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.</p><p>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.</p><h3>Introducing Debezium</h3><p>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.</p><h3>The Complete Flow</h3><p>With all these pieces in place, the complete flow looks like this:</p><ul><li>The order service saves the order and an event row in the outbox table, in one transaction.</li><li>Postgres writes both changes to the WAL when the transaction commits.</li><li>Debezium reads the new outbox row from the WAL.</li><li>Debezium publishes the event to Kafka.</li><li>The notification service consumes the event and continues the flow.</li></ul><p>At no point does the order service talk to Kafka. That is the whole point.</p><h3>Implementing the Outbox Pattern in Golang</h3><p>Now that we understand the flow, let’s implement it in Go. We will build two services:</p><ul><li>The order service: It saves orders and writes the events to its outbox table.</li><li>The notification service: It consumes the events from Kafka. It is very simple, because its only job is to show that the event arrived.</li></ul><h3>Project Structure</h3><p>Our project is a monorepo with two services, and the shared infrastructure lives at the root:</p><pre>.<br>├── docker-compose.yaml              # Kafka, Kafka Connect and Kafka UI<br>├── Makefile<br>├── go.work<br>├── debezium/<br>│   └── order-outbox-connector.json  # Debezium connector config<br>└── services/<br>    ├── order/<br>    │   ├── cmd/<br>    │   │   └── main.go<br>    │   ├── internal/<br>    │   │   ├── domain/order/        # order entity and event payload<br>    │   │   ├── ports/               # repository interface<br>    │   │   ├── services/            # order service logic<br>    │   │   └── adapters/<br>    │   │       ├── db/<br>    │   │       │   ├── migrations/  # goose migrations<br>    │   │       │   ├── sqlc/        # queries and generated code<br>    │   │       │   └── repository/  # order repository with the outbox write<br>    │   │       └── transport/http/  # HTTP server and handlers<br>    │   ├── pkg/env/                 # environment variables<br>    │   ├── Dockerfile<br>    │   └── docker-compose.yaml<br>    └── notification/<br>        ├── main.go                  # Kafka consumer<br>        ├── Dockerfile<br>        └── docker-compose.yaml</pre><h3>The Outbox Table</h3><p>First, we create the outbox table in the service that publishes the event, which is our order service. We use goose for our migrations:</p><pre>-- services/order/internal/adapters/db/migrations/20261118093459_create_outbox_table.sql</pre><pre>-- +goose Up<br>CREATE TABLE outbox (<br>  id            UUID PRIMARY KEY,<br>  aggregatetype VARCHAR(255) NOT NULL,<br>  aggregateid   VARCHAR(255) NOT NULL,<br>  type          VARCHAR(255) NOT NULL,<br>  payload       JSONB NOT NULL,<br>  created_at    TIMESTAMPTZ NOT NULL DEFAULT now()<br>);</pre><pre>CREATE PUBLICATION order_outbox FOR TABLE outbox;</pre><pre>-- +goose Down<br>DROP PUBLICATION IF EXISTS order_outbox;<br>DROP TABLE IF EXISTS outbox;</pre><p>The column names come from domain-driven design, and they’re also the default column names the Debezium outbox event router looks for:</p><ul><li>aggregatetype: The type of aggregate the event belongs to, which is order for us. Debezium uses it to pick the Kafka topic.</li><li>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.</li><li>type: The event type, like OrderCreated. In our setup, Debezium sends it as a message header called eventType.</li><li>payload: The event data, which is the order as JSON. Debezium uses it as the message value.</li></ul><p>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.</p><h3>The Orders Table</h3><p>Next, the orders table:</p><pre>-- services/order/internal/adapters/db/migrations/20261118100000_create_orders_table.sql</pre><pre>-- +goose Up<br>CREATE TABLE orders (<br>  id           UUID PRIMARY KEY,<br>  customer_id  UUID NOT NULL,<br>  amount       BIGINT NOT NULL CHECK (amount &gt; 0),<br>  status       VARCHAR(50) NOT NULL,<br>  created_at   TIMESTAMPTZ NOT NULL DEFAULT now()<br>);</pre><pre>-- +goose Down<br>DROP TABLE IF EXISTS orders;</pre><h3>The Queries</h3><p>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.</p><pre>-- services/order/internal/adapters/db/sqlc/queries/outbox.sql</pre><pre>-- name: InsertOutboxEvent :exec<br>INSERT INTO outbox (id, aggregatetype, aggregateid, type, payload)<br>VALUES ($1, $2, $3, $4, $5);</pre><pre>-- name: DeleteOutboxEvent :exec<br>DELETE FROM outbox WHERE id = $1;</pre><pre>-- services/order/internal/adapters/db/sqlc/queries/order.sql</pre><pre>-- name: CreateOrder :one<br>INSERT INTO orders (id, customer_id, amount, status)<br>VALUES ($1, $2, $3, $4)<br>RETURNING *;</pre><pre>-- name: GetOrder :one<br>SELECT * FROM orders WHERE id = $1;</pre><p>Running sqlc generate turns these into Go functions. sqlc also generates a WithTx method, which lets us run queries in transactions.</p><h3>The Order Domain</h3><p>Next, we create our order domain entity:</p><pre>// services/order/internal/domain/order/order.go</pre><pre>package order</pre><pre>import (<br>	&quot;errors&quot;<br>	&quot;time&quot;</pre><pre>	&quot;github.com/google/uuid&quot;<br>)</pre><pre>type Status string</pre><pre>const (<br>	StatusPending Status = &quot;PENDING&quot;<br>)</pre><pre>const (<br>	AggregateType     = &quot;order&quot;<br>	EventOrderCreated = &quot;OrderCreated&quot;<br>)</pre><pre>var (<br>	ErrNotFound      = errors.New(&quot;order not found&quot;)<br>	ErrInvalidAmount = errors.New(&quot;amount must be greater than zero&quot;)<br>	ErrInvalidCustID = errors.New(&quot;customer id is required&quot;)<br>)</pre><pre>type Order struct {<br>	ID         uuid.UUID<br>	CustomerID uuid.UUID<br>	Amount     int64<br>	Status     Status<br>	CreatedAt  time.Time<br>}</pre><pre>func New(customerID uuid.UUID, amount int64) (*Order, error) {<br>	if customerID == uuid.Nil {<br>		return nil, ErrInvalidCustID<br>	}<br>	if amount &lt;= 0 {<br>		return nil, ErrInvalidAmount<br>	}</pre><pre>	return &amp;Order{<br>		ID:         uuid.New(),<br>		CustomerID: customerID,<br>		Amount:     amount,<br>		Status:     StatusPending,<br>	}, nil<br>}</pre><pre>// CreatedPayload is the body of the OrderCreated event that downstream<br>// services (inventory, payment, notification) receive.<br>type CreatedPayload struct {<br>	OrderID    uuid.UUID `json:&quot;order_id&quot;`<br>	CustomerID uuid.UUID `json:&quot;customer_id&quot;`<br>	Amount     int64     `json:&quot;amount&quot;`<br>	Status     Status    `json:&quot;status&quot;`<br>	CreatedAt  time.Time `json:&quot;created_at&quot;`<br>}</pre><p>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&#39;t hardcode them.</p><p>New validates the input and returns a new order with a PENDING status.</p><p>CreatedPayload is the event the other services receive. It&#39;s separate from the Order struct, so we can change the order without breaking the event the other services depend on.</p><h3>The Order Repository Port</h3><p>Next, we define the repository interface in our ports:</p><pre>// services/order/internal/ports/order.go</pre><pre>package ports</pre><pre>import (<br>	&quot;context&quot;</pre><pre>	&quot;github.com/google/uuid&quot;<br>	&quot;github.com/umohsamuel/transactional-outbox/services/order/internal/domain/order&quot;<br>)</pre><pre>type OrderRepository interface {<br>	Create(ctx context.Context, o *order.Order) error<br>	GetByID(ctx context.Context, id uuid.UUID) (*order.Order, error)<br>}</pre><p>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.</p><h3>The Order Repository</h3><p>This is the most important part of this guide. Next, we implement the order repository interface in our database adapter:</p><pre>// services/order/internal/adapters/db/repository/order.go</pre><pre>package repository</pre><pre>import (<br>	&quot;context&quot;<br>	&quot;database/sql&quot;<br>	&quot;encoding/json&quot;<br>	&quot;errors&quot;<br>	&quot;fmt&quot;</pre><pre>	&quot;github.com/google/uuid&quot;<br>	&quot;github.com/umohsamuel/transactional-outbox/services/order/internal/adapters/db/sqlc&quot;<br>	&quot;github.com/umohsamuel/transactional-outbox/services/order/internal/domain/order&quot;<br>	&quot;github.com/umohsamuel/transactional-outbox/services/order/internal/ports&quot;<br>)</pre><pre>var _ ports.OrderRepository = (*OrderRepository)(nil)</pre><pre>type OrderRepository struct {<br>	db *sql.DB<br>	q  *sqlc.Queries<br>}</pre><pre>func NewOrderRepository(db *sql.DB) *OrderRepository {<br>	return &amp;OrderRepository{db: db, q: sqlc.New(db)}<br>}</pre><pre>func (r *OrderRepository) Create(ctx context.Context, o *order.Order) error {<br>	tx, err := r.db.BeginTx(ctx, nil)<br>	if err != nil {<br>		return fmt.Errorf(&quot;begin tx: %w&quot;, err)<br>	}<br>	defer tx.Rollback()</pre><pre>	q := r.q.WithTx(tx)</pre><pre>	row, err := q.CreateOrder(ctx, sqlc.CreateOrderParams{<br>		ID:         o.ID,<br>		CustomerID: o.CustomerID,<br>		Amount:     o.Amount,<br>		Status:     string(o.Status),<br>	})<br>	if err != nil {<br>		return fmt.Errorf(&quot;insert order: %w&quot;, err)<br>	}<br>	o.CreatedAt = row.CreatedAt</pre><pre>	payload, err := json.Marshal(order.CreatedPayload{<br>		OrderID:    o.ID,<br>		CustomerID: o.CustomerID,<br>		Amount:     o.Amount,<br>		Status:     o.Status,<br>		CreatedAt:  o.CreatedAt,<br>	})<br>	if err != nil {<br>		return fmt.Errorf(&quot;marshal event: %w&quot;, err)<br>	}</pre><pre>	eventID := uuid.New()<br>	if err := q.InsertOutboxEvent(ctx, sqlc.InsertOutboxEventParams{<br>		ID:            eventID,<br>		Aggregatetype: order.AggregateType,<br>		Aggregateid:   o.ID.String(),<br>		Type:          order.EventOrderCreated,<br>		Payload:       payload,<br>	}); err != nil {<br>		return fmt.Errorf(&quot;insert outbox event: %w&quot;, err)<br>	}</pre><pre>	if err := q.DeleteOutboxEvent(ctx, eventID); err != nil {<br>		return fmt.Errorf(&quot;delete outbox event: %w&quot;, err)<br>	}</pre><pre>	if err := tx.Commit(); err != nil {<br>		return fmt.Errorf(&quot;commit: %w&quot;, err)<br>	}<br>	return nil<br>}</pre><pre>func (r *OrderRepository) GetByID(ctx context.Context, id uuid.UUID) (*order.Order, error) {<br>	row, err := r.q.GetOrder(ctx, id)<br>	if errors.Is(err, sql.ErrNoRows) {<br>		return nil, order.ErrNotFound<br>	}<br>	if err != nil {<br>		return nil, fmt.Errorf(&quot;get order: %w&quot;, err)<br>	}</pre><pre>	return &amp;order.Order{<br>		ID:         row.ID,<br>		CustomerID: row.CustomerID,<br>		Amount:     row.Amount,<br>		Status:     order.Status(row.Status),<br>		CreatedAt:  row.CreatedAt,<br>	}, nil<br>}</pre><p>Create does everything inside one transaction:</p><ul><li>It starts a transaction and uses WithTx to run all the queries inside it. The deferred Rollback does nothing once the transaction commits, but it undoes everything if we return early with an error.</li><li>It inserts the order.</li><li>It builds the event payload and inserts it into the outbox table. The aggregate type is order, the aggregate ID is the order&#39;s ID, and the type is OrderCreated.</li><li>It deletes the outbox row immediately after.</li><li>It commits.</li></ul><p>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.</p><p>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.</p><p>GetByID maps the sqlc row back into our domain order and turns sql.ErrNoRows into our own ErrNotFound.</p><h3>The Order Service</h3><p>Next, the order service:</p><pre>// services/order/internal/services/order.go</pre><pre>package services</pre><pre>import (<br>	&quot;context&quot;</pre><pre>	&quot;github.com/google/uuid&quot;<br>	&quot;github.com/umohsamuel/transactional-outbox/services/order/internal/domain/order&quot;<br>	&quot;github.com/umohsamuel/transactional-outbox/services/order/internal/ports&quot;<br>)</pre><pre>type OrderService struct {<br>	repo ports.OrderRepository<br>}</pre><pre>func NewOrderService(repo ports.OrderRepository) *OrderService {<br>	return &amp;OrderService{repo: repo}<br>}</pre><pre>func (s *OrderService) CreateOrder(ctx context.Context, customerID uuid.UUID, amount int64) (*order.Order, error) {<br>	o, err := order.New(customerID, amount)<br>	if err != nil {<br>		return nil, err<br>	}</pre><pre>	if err := s.repo.Create(ctx, o); err != nil {<br>		return nil, err<br>	}<br>	return o, nil<br>}</pre><pre>func (s *OrderService) GetOrder(ctx context.Context, id uuid.UUID) (*order.Order, error) {<br>	return s.repo.GetByID(ctx, id)<br>}</pre><p>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.</p><h3>Wrapping the Repositories and Services</h3><p>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:</p><pre>// services/order/internal/adapters/db/repository/repository.go</pre><pre>package repository</pre><pre>import &quot;database/sql&quot;</pre><pre>type Repositories struct {<br>	Order *OrderRepository<br>}</pre><pre>func New(db *sql.DB) *Repositories {<br>	return &amp;Repositories{<br>		Order: NewOrderRepository(db),<br>	}<br>}</pre><pre>// services/order/internal/services/services.go</pre><pre>package services</pre><pre>import &quot;github.com/umohsamuel/transactional-outbox/services/order/internal/ports&quot;</pre><pre>type Services struct {<br>	Order *OrderService<br>}</pre><pre>func New(orderRepo ports.OrderRepository) *Services {<br>	return &amp;Services{<br>		Order: NewOrderService(orderRepo),<br>	}<br>}</pre><p>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.</p><h3>The HTTP Handler</h3><p>Next, the handler that exposes our orders over HTTP:</p><pre>// services/order/internal/adapters/transport/http/handlers/order.go</pre><pre>package handlers</pre><pre>import (<br>	&quot;errors&quot;<br>	&quot;net/http&quot;</pre><pre>	&quot;github.com/gin-gonic/gin&quot;<br>	&quot;github.com/google/uuid&quot;<br>	&quot;github.com/umohsamuel/transactional-outbox/services/order/internal/domain/order&quot;<br>	&quot;github.com/umohsamuel/transactional-outbox/services/order/internal/services&quot;<br>)</pre><pre>type OrderHandler struct {<br>	svc *services.OrderService<br>}</pre><pre>func NewOrderHandler(s *services.Services) *OrderHandler {<br>	return &amp;OrderHandler{svc: s.Order}<br>}</pre><pre>func (h *OrderHandler) RegisterRoutes(r gin.IRouter) {<br>	g := r.Group(&quot;/orders&quot;)<br>	g.POST(&quot;&quot;, h.Create)<br>	g.GET(&quot;/:id&quot;, h.Get)<br>}</pre><pre>type createOrderRequest struct {<br>	CustomerID uuid.UUID `json:&quot;customer_id&quot; binding:&quot;required&quot;`<br>	Amount     int64     `json:&quot;amount&quot; binding:&quot;required,gt=0&quot;`<br>}</pre><pre>func (h *OrderHandler) Create(c *gin.Context) {<br>	var req createOrderRequest<br>	if err := c.ShouldBindJSON(&amp;req); err != nil {<br>		c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()})<br>		return<br>	}</pre><pre>	o, err := h.svc.CreateOrder(c, req.CustomerID, req.Amount)<br>	switch {<br>	case errors.Is(err, order.ErrInvalidAmount), errors.Is(err, order.ErrInvalidCustID):<br>		c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()})<br>		return<br>	case err != nil:<br>		c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: &quot;could not create order&quot;})<br>		return<br>	}</pre><pre>	c.JSON(http.StatusCreated, o)<br>}</pre><pre>func (h *OrderHandler) Get(c *gin.Context) {<br>	id, err := uuid.Parse(c.Param(&quot;id&quot;))<br>	if err != nil {<br>		c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: &quot;invalid order id&quot;})<br>		return<br>	}</pre><pre>	o, err := h.svc.GetOrder(c, id)<br>	switch {<br>	case errors.Is(err, order.ErrNotFound):<br>		c.JSON(http.StatusNotFound, gin.H{&quot;error&quot;: err.Error()})<br>		return<br>	case err != nil:<br>		c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: &quot;could not get order&quot;})<br>		return<br>	}</pre><pre>	c.JSON(http.StatusOK, o)<br>}</pre><p>The handler adds POST /orders and GET /orders/:id. The binding tags let Gin validate the request body, so a missing customer ID or an amount of 0 gets a 400 before it reaches the service. Validation errors from our domain also get a 400, anything else gets a 500 with a generic message, and an order that doesn&#39;t exist gets a 404.</p><h3>The HTTP Server</h3><p>Next, the server that holds the router and registers our handlers:</p><pre>// services/order/internal/adapters/transport/http/http.go</pre><pre>package http</pre><pre>import (<br>	&quot;net/http&quot;</pre><pre>	&quot;github.com/gin-gonic/gin&quot;<br>	&quot;github.com/umohsamuel/transactional-outbox/services/order/internal/adapters/transport/http/handlers&quot;<br>	&quot;github.com/umohsamuel/transactional-outbox/services/order/internal/services&quot;<br>)</pre><pre>type HttpServer struct {<br>	router   *gin.Engine<br>	services *services.Services<br>}</pre><pre>func NewHttpServer(svc *services.Services) *HttpServer {<br>	r := gin.Default()<br>	r.ContextWithFallback = true<br>	s := &amp;HttpServer{router: r, services: svc}</pre><pre>	s.setupRoutes()<br>	return s<br>}</pre><pre>func (s *HttpServer) setupRoutes() {<br>	v1 := s.router.Group(&quot;/api/v1&quot;)</pre><pre>	handlers.NewOrderHandler(s.services).RegisterRoutes(v1)<br>}</pre><pre>func (s *HttpServer) Handler() http.Handler {<br>	return s.router<br>}</pre><p>All our routes are under /api/v1, so the full path to create an order is /api/v1/orders. We also set ContextWithFallback to true, so the Gin context uses the request&#39;s context. That way, if the client disconnects, the database transaction in our repository gets cancelled too.</p><h3>The Environment Variables</h3><p>Next, the config. We read it from environment variables into a struct:</p><pre>// services/order/pkg/env/env.go</pre><pre>package env</pre><pre>import (<br>	&quot;fmt&quot;</pre><pre>	&quot;github.com/caarlos0/env/v11&quot;<br>	_ &quot;github.com/joho/godotenv/autoload&quot;<br>)</pre><pre>type Env struct {<br>	Port          int    `env:&quot;PORT&quot; envDefault:&quot;8080&quot;`<br>	CLIENT_ORIGIN string `env:&quot;CLIENT_ORIGIN&quot;`<br>	AppEnv        string `env:&quot;APP_ENV&quot; envDefault:&quot;development&quot;`</pre><pre>	DB PostgresEnv<br>}</pre><pre>type PostgresEnv struct {<br>	DB_USER     string `env:&quot;DB_USER&quot;`<br>	DB_PASSWORD string `env:&quot;DB_PASSWORD&quot;`<br>	DB_DATABASE string `env:&quot;DB_DATABASE&quot;`<br>	DB_HOST     string `env:&quot;DB_HOST&quot;`<br>	DB_SCHEMA   string `env:&quot;DB_SCHEMA&quot;`<br>	DB_PORT     int    `env:&quot;DB_PORT&quot; envDefault:&quot;5432&quot;`<br>	DB_SSLMODE  string `env:&quot;DB_SSLMODE&quot;`<br>}</pre><pre>func LoadEnv() (*Env, error) {<br>	var cfg Env</pre><pre>	if err := env.Parse(&amp;cfg); err != nil {<br>		return nil, fmt.Errorf(&quot;failed to parse env config: %w&quot;, err)<br>	}</pre><pre>	return &amp;cfg, nil<br>}</pre><h3>Wiring Everything Together</h3><p>Finally, we wire everything together in main:</p><pre>// services/order/cmd/main.go</pre><pre>package main</pre><pre>import (<br>	&quot;context&quot;<br>	&quot;database/sql&quot;<br>	&quot;errors&quot;<br>	&quot;fmt&quot;<br>	&quot;log&quot;<br>	&quot;net/http&quot;<br>	&quot;net/url&quot;<br>	&quot;os/signal&quot;<br>	&quot;strconv&quot;<br>	&quot;syscall&quot;<br>	&quot;time&quot;</pre><pre>	_ &quot;github.com/jackc/pgx/v5/stdlib&quot;</pre><pre>	&quot;github.com/umohsamuel/transactional-outbox/services/order/internal/adapters/db/repository&quot;<br>	httpserver &quot;github.com/umohsamuel/transactional-outbox/services/order/internal/adapters/transport/http&quot;<br>	&quot;github.com/umohsamuel/transactional-outbox/services/order/internal/services&quot;<br>	&quot;github.com/umohsamuel/transactional-outbox/services/order/pkg/env&quot;<br>)</pre><pre>func main() {<br>	if err := run(); err != nil {<br>		log.Fatal(err)<br>	}<br>}</pre><pre>func run() error {<br>	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)<br>	defer stop()</pre><pre>	cfg, err := env.LoadEnv()<br>	if err != nil {<br>		return err<br>	}</pre><pre>	db, err := openDB(ctx, cfg.DB)<br>	if err != nil {<br>		return err<br>	}<br>	defer db.Close()</pre><pre>	repos := repository.New(db)<br>	svcs := services.New(repos.Order)<br>	server := httpserver.NewHttpServer(svcs)</pre><pre>	srv := &amp;http.Server{<br>		Addr:              &quot;:&quot; + strconv.Itoa(cfg.Port),<br>		Handler:           server.Handler(),<br>		ReadHeaderTimeout: 5 * time.Second,<br>	}</pre><pre>	errCh := make(chan error, 1)<br>	go func() {<br>		log.Printf(&quot;listening on %s&quot;, srv.Addr)<br>		if err := srv.ListenAndServe(); err != nil &amp;&amp; !errors.Is(err, http.ErrServerClosed) {<br>			errCh &lt;- err<br>		}<br>		close(errCh)<br>	}()</pre><pre>	select {<br>	case err := &lt;-errCh:<br>		return err<br>	case &lt;-ctx.Done():<br>	}</pre><pre>	log.Println(&quot;shutting down&quot;)<br>	shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)<br>	defer cancel()<br>	return srv.Shutdown(shutdownCtx)<br>}</pre><pre>func openDB(ctx context.Context, e env.PostgresEnv) (*sql.DB, error) {<br>	q := url.Values{}<br>	if e.DB_SSLMODE != &quot;&quot; {<br>		q.Set(&quot;sslmode&quot;, e.DB_SSLMODE)<br>	}<br>	if e.DB_SCHEMA != &quot;&quot; {<br>		q.Set(&quot;search_path&quot;, e.DB_SCHEMA)<br>	}</pre><pre>	dsn := url.URL{<br>		Scheme:   &quot;postgres&quot;,<br>		User:     url.UserPassword(e.DB_USER, e.DB_PASSWORD),<br>		Host:     fmt.Sprintf(&quot;%s:%d&quot;, e.DB_HOST, e.DB_PORT),<br>		Path:     e.DB_DATABASE,<br>		RawQuery: q.Encode(),<br>	}</pre><pre>	db, err := sql.Open(&quot;pgx&quot;, dsn.String())<br>	if err != nil {<br>		return nil, fmt.Errorf(&quot;open db: %w&quot;, err)<br>	}</pre><pre>	pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)<br>	defer cancel()<br>	if err := db.PingContext(pingCtx); err != nil {<br>		db.Close()<br>		return nil, fmt.Errorf(&quot;ping db: %w&quot;, err)<br>	}</pre><pre>	return db, nil<br>}</pre><p>In main.go, we load the env, open the database with the pgx driver, pass the repositories to the services, and pass the services to the HTTP server. We also <a href="https://www.umohsg.com/blog/graceful-shutdown-in-golang-2fbbf043-1b2e-45ab-bfc9-b7eafd89926c">gracefully shut down</a> the server when we get a Ctrl+C or a SIGTERM.</p><h3>The Notification Service</h3><p>Now the other side. The notification service is a single main.go file that consumes the order events from Kafka:</p><pre>// services/notification/main.go</pre><pre>package main</pre><pre>import (<br>	&quot;context&quot;<br>	&quot;encoding/json&quot;<br>	&quot;log&quot;<br>	&quot;os&quot;<br>	&quot;os/signal&quot;<br>	&quot;strings&quot;<br>	&quot;syscall&quot;<br>	&quot;time&quot;</pre><pre>	&quot;github.com/segmentio/kafka-go&quot;<br>)</pre><pre>type orderCreated struct {<br>	OrderID    string    `json:&quot;order_id&quot;`<br>	CustomerID string    `json:&quot;customer_id&quot;`<br>	Amount     int64     `json:&quot;amount&quot;`<br>	Status     string    `json:&quot;status&quot;`<br>	CreatedAt  time.Time `json:&quot;created_at&quot;`<br>}</pre><pre>func main() {<br>	brokers := getenv(&quot;KAFKA_BROKERS&quot;, &quot;localhost:9092&quot;)<br>	topic := getenv(&quot;KAFKA_TOPIC&quot;, &quot;outbox.event.order&quot;)<br>	groupID := getenv(&quot;KAFKA_GROUP_ID&quot;, &quot;notification-service&quot;)</pre><pre>	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)<br>	defer stop()</pre><pre>	brokerList := strings.Split(brokers, &quot;,&quot;)</pre><pre>	log.Printf(&quot;waiting for topic %q&quot;, topic)<br>	if err := waitForTopic(ctx, brokerList[0], topic); err != nil {<br>		log.Println(&quot;shutting down&quot;)<br>		return<br>	}</pre><pre>	r := kafka.NewReader(kafka.ReaderConfig{<br>		Brokers: brokerList,<br>		Topic:   topic,<br>		GroupID: groupID,<br>	})<br>	defer r.Close()</pre><pre>	log.Printf(&quot;notification service listening on topic %q&quot;, topic)</pre><pre>	for {<br>		m, err := r.ReadMessage(ctx)<br>		if err != nil {<br>			if ctx.Err() != nil {<br>				log.Println(&quot;shutting down&quot;)<br>				return<br>			}<br>			log.Printf(&quot;read message: %v&quot;, err)<br>			time.Sleep(time.Second)<br>			continue<br>		}</pre><pre>		log.Printf(&quot;received: topic=%s partition=%d offset=%d key=%s headers=%s&quot;,<br>			m.Topic, m.Partition, m.Offset, m.Key, headers(m.Headers))</pre><pre>		evt, err := decode(m.Value)<br>		if err != nil {<br>			log.Printf(&quot;could not decode payload %s: %v&quot;, m.Value, err)<br>			continue<br>		}</pre><pre>		log.Printf(&quot;sending confirmation to customer %s: order %s for %d is %s&quot;,<br>			evt.CustomerID, evt.OrderID, evt.Amount, evt.Status)<br>	}<br>}</pre><pre>func waitForTopic(ctx context.Context, broker, topic string) error {<br>	for {<br>		conn, err := kafka.DialContext(ctx, &quot;tcp&quot;, broker)<br>		if err == nil {<br>			partitions, err := conn.ReadPartitions(topic)<br>			conn.Close()<br>			if err == nil &amp;&amp; len(partitions) &gt; 0 {<br>				return nil<br>			}<br>		}</pre><pre>		select {<br>		case &lt;-ctx.Done():<br>			return ctx.Err()<br>		case &lt;-time.After(2 * time.Second):<br>		}<br>	}<br>}</pre><pre>func decode(raw []byte) (orderCreated, error) {<br>	var s string<br>	if err := json.Unmarshal(raw, &amp;s); err == nil {<br>		raw = []byte(s)<br>	}</pre><pre>	var evt orderCreated<br>	err := json.Unmarshal(raw, &amp;evt)<br>	return evt, err<br>}</pre><pre>func headers(hs []kafka.Header) string {<br>	parts := make([]string, 0, len(hs))<br>	for _, h := range hs {<br>		parts = append(parts, h.Key+&quot;=&quot;+string(h.Value))<br>	}<br>	return &quot;[&quot; + strings.Join(parts, &quot; &quot;) + &quot;]&quot;<br>}</pre><pre>func getenv(key, fallback string) string {<br>	if v := os.Getenv(key); v != &quot;&quot; {<br>		return v<br>	}<br>	return fallback<br>}</pre><p>Debezium names the topic outbox.event. plus the aggregate type, so our topic is outbox.event.order.</p><p>The consumer reads each message and logs the key, the headers and the payload. In a real system, this is where you would send the email.</p><p>decode handles the payload whether it comes in as a JSON object or as a JSON string, since that depends on how the connector is set up.</p><p>Before creating the reader, we call waitForTopic so the consumer only joins the group once the topic exists. Otherwise, kafka-go gives it no partitions and it never receives anything.</p><h3>Setting Up the Containers</h3><p>Next, we have to set up our containers.</p><h3>The Order Service Dockerfile</h3><pre># services/order/Dockerfile</pre><pre>FROM golang:1.27-alpine AS build</pre><pre>WORKDIR /src</pre><pre>COPY go.mod go.sum ./<br>RUN go mod download</pre><pre>COPY ./ ./</pre><pre>RUN CGO_ENABLED=0 go build -trimpath -ldflags=&quot;-s -w&quot; -o /out/main ./cmd</pre><pre>FROM alpine:3.20.1 AS prod<br>WORKDIR /app<br>COPY --from=build /out/main /app/main<br>USER nobody<br>CMD [&quot;./main&quot;]</pre><p>This is a multi-stage build. We compile the binary in the Go image, then copy only the binary into a small Alpine image and run it as a non-root user.</p><h3>The Order Service Docker Compose</h3><pre># services/order/docker-compose.yaml</pre><pre>services:<br>  app:<br>    profiles: [&quot;app&quot;]<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>      target: prod<br>    restart: unless-stopped<br>    container_name: order_app<br>    ports:<br>      - &quot;${PORT:-8080}:${PORT:-8080}&quot;<br>    env_file: .env<br>    environment:<br>      DB_HOST: postgres<br>    depends_on:<br>      postgres:<br>        condition: service_healthy<br>    networks:<br>      - order_network<br>  postgres:<br>    image: postgres:17.4<br>    container_name: order_pg<br>    command: [&quot;postgres&quot;, &quot;-c&quot;, &quot;wal_level=logical&quot;]<br>    volumes:<br>      - postgresql_data:/var/lib/postgresql/data<br>    environment:<br>      POSTGRES_USER: ${DB_USER:-postgres}<br>      POSTGRES_PASSWORD: ${DB_PASSWORD}<br>      POSTGRES_DB: ${DB_DATABASE:-postgres}<br>      PGPORT: ${DB_PORT:-5432}<br>    ports:<br>      - &quot;${DB_PORT:-5432}:${DB_PORT:-5432}&quot;<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}&quot;]<br>      interval: 5s<br>      timeout: 5s<br>      retries: 3<br>      start_period: 15s<br>    networks:<br>      - order_network<br>      - outbox_infra<br>    restart: unless-stopped</pre><pre>volumes:<br>  postgresql_data:<br>    driver: local<br>networks:<br>  order_network:<br>    driver: bridge<br>  outbox_infra:<br>    name: outbox_infra<br>    external: true</pre><p>We set wal_level=logical so Postgres writes enough detail to the WAL for Debezium to decode each change.</p><p>Postgres also joins two networks: order_network for the order app, and the shared outbox_infra network so Kafka Connect can reach it. The order app only needs order_network, since it never talks to Kafka.</p><p>The order service also needs a .env file:</p><pre># services/order/.env</pre><pre>PORT=8080</pre><pre>DB_USER=postgres<br>DB_PASSWORD=postgres<br>DB_DATABASE=order_db<br>DB_HOST=localhost<br>DB_PORT=5432<br>DB_SCHEMA=public<br>DB_SSLMODE=disable</pre><pre>GOOSE_DRIVER=postgres<br>GOOSE_DBSTRING=&quot;host=localhost port=5432 user=postgres password=postgres dbname=order_db sslmode=disable&quot;<br>GOOSE_MIGRATION_DIR=./internal/adapters/db/migrations</pre><p>Make sure the dbname in GOOSE_DBSTRING matches DB_DATABASE, so goose runs the migrations against the right database.</p><h3>The Notification Service Dockerfile</h3><pre># services/notification/Dockerfile</pre><pre>FROM golang:1.27-alpine AS build</pre><pre>WORKDIR /src</pre><pre>COPY go.mod go.sum ./<br>RUN go mod download</pre><pre>COPY ./ ./</pre><pre>RUN CGO_ENABLED=0 go build -trimpath -ldflags=&quot;-s -w&quot; -o /out/main .</pre><pre>FROM alpine:3.20.1 AS prod<br>WORKDIR /app<br>COPY --from=build /out/main /app/main<br>USER nobody<br>CMD [&quot;./main&quot;]</pre><p>This is the same as the order service. The only difference is that we build from . instead of ./cmd, since the whole service is one main.go file.</p><h3>The Notification Service Docker Compose</h3><pre># services/notification/docker-compose.yaml</pre><pre>services:<br>  app:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>      target: prod<br>    container_name: notification_app<br>    restart: unless-stopped<br>    environment:<br>      KAFKA_BROKERS: ${KAFKA_BROKERS:-kafka:9092}<br>      KAFKA_TOPIC: ${KAFKA_TOPIC:-outbox.event.order}<br>      KAFKA_GROUP_ID: ${KAFKA_GROUP_ID:-notification-service}<br>    networks:<br>      - outbox_infra</pre><pre>networks:<br>  outbox_infra:<br>    name: outbox_infra<br>    external: true</pre><p>The notification service only joins the shared network, because the only thing it talks to is Kafka.</p><h3>Setting Up the Infrastructure</h3><p>Next, we set up Kafka, Kafka Connect with Debezium, and Kafka UI.</p><h3>The Shared Network</h3><p>Each service has its own compose file, so each one can be started and stopped on its own. But they still need to reach each other. So first, let’s create a shared network that every compose file joins:</p><pre>docker network create outbox_infra</pre><p>Every compose file declares this network as external. That means none of them own it, and none of them will delete it when they shut down.</p><h3>The Infrastructure Docker Compose</h3><p>Next, the compose file at the root of the project:</p><pre># docker-compose.yaml</pre><pre>name: outbox-infra</pre><pre>services:<br>  kafka:<br>    image: apache/kafka:3.9.0<br>    container_name: kafka<br>    ports:<br>      - &quot;9094:9094&quot;<br>    environment:<br>      CLUSTER_ID: MkU3OEVBNTcwNTJENDM2Qk<br>      KAFKA_NODE_ID: 1<br>      KAFKA_PROCESS_ROLES: broker,controller<br>      KAFKA_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093,EXTERNAL://:9094<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,EXTERNAL://localhost:9094<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,CONTROLLER:PLAINTEXT,EXTERNAL:PLAINTEXT<br>      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER<br>      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:9093<br>      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1<br>      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1<br>      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0<br>    healthcheck:<br>      test:<br>        [<br>          &quot;CMD-SHELL&quot;,<br>          &quot;/opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server localhost:9092 &gt; /dev/null 2&gt;&amp;1&quot;,<br>        ]<br>      interval: 10s<br>      timeout: 10s<br>      retries: 10<br>      start_period: 20s<br>    networks:<br>      - outbox_infra</pre><pre>  connect:<br>    image: quay.io/debezium/connect:3.2.0.Final<br>    container_name: connect<br>    ports:<br>      - &quot;8083:8083&quot;<br>    environment:<br>      BOOTSTRAP_SERVERS: kafka:9092<br>      GROUP_ID: connect-cluster<br>      CONFIG_STORAGE_TOPIC: connect_configs<br>      OFFSET_STORAGE_TOPIC: connect_offsets<br>      STATUS_STORAGE_TOPIC: connect_statuses<br>      CONNECT_CONFIG_PROVIDERS: env<br>      CONNECT_CONFIG_PROVIDERS_ENV_CLASS: org.apache.kafka.common.config.provider.EnvVarConfigProvider<br>      DEBEZIUM_USER_PASSWORD: ${DEBEZIUM_USER_PASSWORD:?set DEBEZIUM_USER_PASSWORD in .env}<br>    depends_on:<br>      kafka:<br>        condition: service_healthy<br>    networks:<br>      - outbox_infra</pre><pre>  kafka-ui:<br>    image: ghcr.io/kafbat/kafka-ui:latest<br>    container_name: kafka-ui<br>    ports:<br>      - &quot;8081:8080&quot;<br>    environment:<br>      KAFKA_CLUSTERS_0_NAME: local<br>      KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka:9092<br>      KAFKA_CLUSTERS_0_KAFKACONNECT_0_NAME: debezium<br>      KAFKA_CLUSTERS_0_KAFKACONNECT_0_ADDRESS: <a href="http://connect:8083/">http://connect:8083</a><br>    depends_on:<br>      - kafka<br>      - connect<br>    networks:<br>      - outbox_infra</pre><pre>networks:<br>  outbox_infra:<br>    name: outbox_infra<br>    external: true</pre><p>Kafka runs as a single broker in KRaft mode. Other containers connect to it on kafka:9092, and your PC connects to it on localhost:9094. You can find the rest of these settings in my <a href="https://www.umohsg.com/blog/building-fault-tolerant-event-driven-kafka-pipelines-in-go-reliable-reprocessing-dead-letter-queues-1f6874d4-270c-48e1-9798-324b494c7f0e">Kafka pipelines guide</a>.</p><p>The connect service uses the Debezium image, which is Kafka Connect with the Debezium connectors already installed. The CONNECT_CONFIG_PROVIDERS settings let our connector read the database password from an environment variable instead of the JSON file.</p><p>Kafka UI runs on port 8081.</p><p>Kafka Connect reads the Debezium password from a .env file at the root of the project:</p><pre># .env</pre><pre>DEBEZIUM_USER_PASSWORD=debezium</pre><h3>Starting Everything</h3><p>Now we can start the infrastructure:</p><pre>docker compose up -d</pre><p>Docker marks the connect container as started before Kafka Connect is actually ready. Run this to wait until its API responds:</p><pre>until curl -s http://localhost:8083/ &gt; /dev/null; do sleep 2; done</pre><p>Once it returns, confirm that Kafka Connect has the Postgres connector:</p><pre>curl http://localhost:8083/connector-plugins</pre><p>You should see io.debezium.connector.postgresql.PostgresConnector in the list.</p><p>Next, start the order service and run the migrations:</p><pre>docker compose -f services/order/docker-compose.yaml --profile app up -d --build<br>cd services/order<br>goose up<br>cd ../..</pre><p>This creates the orders and outbox tables and the order_outbox publication. We run goose from services/order because that&#39;s where its .env file is.</p><p>If you don’t feel like typing all of this, the repository also has a Makefile with these steps: make network, make infra, make order and make notification.</p><h3>The Debezium Database User</h3><p>Debezium needs its own database user. We could give it our main user, but that user can read and change everything, and Debezium only needs to read the outbox.</p><p>Connect to Postgres inside the order database container:</p><pre>docker exec -it order_pg psql -U postgres -d order_db</pre><p>Then create the user. Use the same password you put in the root .env file:</p><pre>CREATE ROLE debezium WITH LOGIN REPLICATION PASSWORD &#39;debezium&#39;;<br>GRANT CONNECT ON DATABASE order_db TO debezium;<br>GRANT USAGE ON SCHEMA public TO debezium;<br>GRANT SELECT ON public.outbox TO debezium;</pre><p>LOGIN lets the user connect, and REPLICATION lets it create a replication slot and stream the WAL. CONNECT and USAGE give it access to the order_db database and the public schema. SELECT on the outbox is for the snapshot Debezium takes the first time the connector starts.</p><p>The Debezium user can only read the outbox. It has no access to the orders table.</p><p>You only need to do this once per database volume. If you delete the volume, you have to do it again.</p><h3>The Debezium Connector</h3><p>Next, we tell Debezium what to watch and where to send it. Create debezium/order-outbox-connector.json at the root of the project:</p><pre>{<br>  &quot;name&quot;: &quot;order-outbox-connector&quot;,<br>  &quot;config&quot;: {<br>    &quot;connector.class&quot;: &quot;io.debezium.connector.postgresql.PostgresConnector&quot;,<br>    &quot;tasks.max&quot;: &quot;1&quot;,<br>    &quot;database.hostname&quot;: &quot;order_pg&quot;,<br>    &quot;database.port&quot;: &quot;5432&quot;,<br>    &quot;database.user&quot;: &quot;debezium&quot;,<br>    &quot;database.password&quot;: &quot;${env:DEBEZIUM_USER_PASSWORD}&quot;,<br>    &quot;database.dbname&quot;: &quot;order_db&quot;,<br>    &quot;topic.prefix&quot;: &quot;order&quot;,<br>    &quot;plugin.name&quot;: &quot;pgoutput&quot;,<br>    &quot;publication.name&quot;: &quot;order_outbox&quot;,<br>    &quot;publication.autocreate.mode&quot;: &quot;disabled&quot;,<br>    &quot;slot.name&quot;: &quot;order_outbox_slot&quot;,<br>    &quot;table.include.list&quot;: &quot;public.outbox&quot;,<br>    &quot;tombstones.on.delete&quot;: &quot;false&quot;,<br>    &quot;key.converter&quot;: &quot;org.apache.kafka.connect.storage.StringConverter&quot;,<br>    &quot;value.converter&quot;: &quot;org.apache.kafka.connect.storage.StringConverter&quot;,<br>    &quot;transforms&quot;: &quot;outbox&quot;,<br>    &quot;transforms.outbox.type&quot;: &quot;io.debezium.transforms.outbox.EventRouter&quot;,<br>    &quot;transforms.outbox.table.fields.additional.placement&quot;: &quot;type:header:eventType&quot;<br>  }<br>}</pre><p>Let’s go through the important ones:</p><ul><li>database.hostname: Kafka Connect reaches Postgres by its container name, order_pg, over the shared network.</li><li>database.password: This reads the password from the environment variable we set on the Kafka Connect container.</li><li>plugin.name: pgoutput is the logical decoding plugin built into Postgres, so we don&#39;t have to install anything.</li><li>publication.name and publication.autocreate.mode: They tell Debezium to use the order_outbox publication from our migration, instead of creating its own.</li><li>slot.name: This is the name of the replication slot. Postgres keeps the WAL for this slot until Debezium confirms it has read it. So if Kafka Connect goes down, no events are lost, and Debezium picks up where it stopped.</li><li>table.include.list: It tells Debezium to only watch public.outbox.</li><li>tombstones.on.delete: Our repository deletes every outbox row right after it inserts it. Setting this to false stops Debezium from sending an empty message to Kafka for every delete. The outbox event router also ignores the delete events themselves.</li><li>The converters: StringConverter sends the key and the payload as plain text, without Debezium&#39;s schema wrapper.</li></ul><p>The last setting is the outbox transform. By default, Debezium sends every row change with extra data, like the old row, the new row and some metadata. EventRouter removes that and sends only the event.</p><p>It uses the outbox columns to build the event. The topic name comes from aggregatetype, so our order events go to outbox.event.order. The message key comes from aggregateid, and the message value comes from payload. The table.fields.additional.placement setting also adds the type column to each message as a header called eventType.</p><p>Now register the connector with Kafka Connect:</p><pre>curl -X POST -H &quot;Content-Type: application/json&quot; \<br>  --data @debezium/order-outbox-connector.json \<br>  http://localhost:8083/connectors</pre><p>Then check its status:</p><pre>curl http://localhost:8083/connectors/order-outbox-connector/status</pre><p>Both the connector and its task should say RUNNING:</p><pre>{<br>  &quot;name&quot;: &quot;order-outbox-connector&quot;,<br>  &quot;connector&quot;: {<br>    &quot;state&quot;: &quot;RUNNING&quot;,<br>    &quot;worker_id&quot;: &quot;172.26.0.3:8083&quot;<br>  },<br>  &quot;tasks&quot;: [<br>    {<br>      &quot;id&quot;: 0,<br>      &quot;state&quot;: &quot;RUNNING&quot;,<br>      &quot;worker_id&quot;: &quot;172.26.0.3:8083&quot;<br>    }<br>  ],<br>  &quot;type&quot;: &quot;source&quot;<br>}</pre><p>You can also see the connector in Kafka UI under Kafka Connect.</p><h3>Starting the Notification Service</h3><p>Lastly, start the notification service and follow its logs:</p><pre>docker compose -f services/notification/docker-compose.yaml up -d --build<br>docker logs -f notification_app</pre><p>You should see:</p><pre>waiting for topic &quot;outbox.event.order&quot;<br>notification service listening on topic &quot;outbox.event.order&quot;</pre><h3>Testing</h3><p>Now, how do we test this?</p><h3>The Happy Path</h3><p>In another terminal, place an order:</p><pre>curl -X POST http://localhost:8080/api/v1/orders \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;customer_id&quot;: &quot;3f1c2a4e-8b7d-4c6e-9a1f-2b3c4d5e6f70&quot;, &quot;amount&quot;: 5000}&#39;</pre><p>The order service saves the order and returns it:</p><pre>{<br>  &quot;ID&quot;: &quot;e2027503-b264-40c5-8e9f-e1b0d425b76f&quot;,<br>  &quot;CustomerID&quot;: &quot;3f1c2a4e-8b7d-4c6e-9a1f-2b3c4d5e6f70&quot;,<br>  &quot;Amount&quot;: 5000,<br>  &quot;Status&quot;: &quot;PENDING&quot;,<br>  &quot;CreatedAt&quot;: &quot;2026-11-18T13:59:54.581932Z&quot;<br>}</pre><p>A moment later, the notification service logs the event:</p><pre>received: topic=outbox.event.order partition=0 offset=0 key=e2027503-b264-40c5-8e9f-e1b0d425b76f headers=[__debezium.context.connectorLogicalName=order __debezium.context.taskId=0 __debezium.context.connectorName=postgresql id=02580ef7-2fa4-4df1-9703-9abfb22dd8c9 eventType=OrderCreated]<br>sending confirmation to customer 3f1c2a4e-8b7d-4c6e-9a1f-2b3c4d5e6f70: order e2027503-b264-40c5-8e9f-e1b0d425b76f for 5000 is PENDING</pre><p>The message key is the order ID, and the eventType header is OrderCreated. The id header is the outbox row&#39;s ID, and you can ignore the __debezium headers.</p><p>You can also see the message in Kafka UI at http://localhost:8081, under Topics &gt; outbox.event.order &gt; Messages.</p><p>Now, check the database:</p><pre>docker exec order_pg psql -U postgres -d order_db -c &quot;SELECT count(*) FROM orders;&quot; -c &quot;SELECT count(*) FROM outbox;&quot;</pre><p>The orders table has 1 row, and the outbox table has 0. The event was published even though the outbox is empty. That&#39;s because Debezium read the insert from the WAL, not from the table.</p><h3>When Kafka Connect Is Down</h3><p>First, stop Kafka Connect:</p><pre>docker stop connect</pre><p>Then place a few orders. They still succeed, since the order service doesn’t depend on Kafka or Kafka Connect, but nothing reaches the notification service yet.</p><p>Now start Kafka Connect again:</p><pre>docker start connect</pre><p>After a few seconds, the missed events show up in the notification logs, in the order you placed them. The replication slot kept the WAL while Kafka Connect was down, so Debezium continues from where it stopped.</p><p>The same works for the notification service. Stop it, place a few orders, and start it again. The events wait in Kafka until it comes back.</p><h3>Notes</h3><p>Before taking this to production, there are a few things to prepare for:</p><h3>At-Least-Once Delivery</h3><p>The outbox pattern guarantees at-least-once delivery, not exactly-once. If Kafka Connect crashes after publishing an event but before saving its position, it publishes that event again when it restarts.</p><p>So your consumers must be idempotent. An easy way to do this is to store the id header of every event you process and skip any event you have already seen.</p><h3>Replication Slots</h3><p>Deleting a connector does not delete its replication slot. Postgres keeps every WAL file the slot hasn’t read, so an unused slot keeps growing the WAL until your disk is full.</p><p>So when you delete a connector, also drop its replication slot:</p><pre>SELECT pg_drop_replication_slot(&#39;order_outbox_slot&#39;);</pre><h3>Conclusion</h3><p>In this guide, we built the transactional outbox pattern in Go with Debezium and Kafka. The key takeaways are:</p><ul><li>Writing to a database and publishing to a broker are two separate writes, and a crash or rollback can leave them out of sync.</li><li>The outbox pattern saves the event in the same transaction as the business data, so both are saved or neither is.</li><li>Debezium reads the outbox rows from the Postgres WAL and publishes them to Kafka, so the service never talks to Kafka.</li><li>Deleting the outbox row in the same transaction keeps the table empty, and the event still reaches Kafka through the WAL.</li><li>The replication slot holds the WAL until Debezium reads it, so no events are lost if Kafka Connect goes down.</li></ul><p>The outbox pattern solves the dual write problem, but it comes with trade-offs:</p><ul><li>More infrastructure: You have to run and monitor Kafka Connect and Debezium on top of Kafka.</li><li>At-least-once delivery: Events can arrive more than once, so consumers must be idempotent.</li><li>Replication slots: An unused slot will fill your disk with WAL files.</li></ul><p>(If you want to see the full codebase, check out the <a href="https://github.com/umohsamuel/transactional-outbox">repository</a>. Play around with it and lmk what you think.)</p><h3>References</h3><ul><li><a href="https://www.ibm.com/think/topics/change-data-capture">IBM: What is Change Data Capture?</a></li><li><a href="https://microservices.io/patterns/data/transactional-outbox.html">Microservices.io: Pattern: Transactional Outbox</a></li><li><a href="https://debezium.io/documentation/reference/stable/transformations/outbox-event-router.html">Debezium: Outbox Event Router</a></li><li><a href="https://debezium.io/documentation/reference/stable/connectors/postgresql.html">Debezium: PostgreSQL Connector</a></li><li><a href="https://debezium.io/documentation/reference/stable/kc-tutorial.html">Debezium: Tutorial</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6af580dd586c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Transaction Processing: Saga Pattern in Golang]]></title>
            <link>https://medium.com/@umohsg/distributed-transaction-processing-saga-pattern-in-golang-28077b0ea0b6?source=rss-98d0e0748007------2</link>
            <guid isPermaLink="false">https://medium.com/p/28077b0ea0b6</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[saga-pattern]]></category>
            <category><![CDATA[distributed-transaction]]></category>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[saga]]></category>
            <dc:creator><![CDATA[Samuel Umoh ]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 16:55:19 GMT</pubDate>
            <atom:updated>2026-11-19T16:55:19.206Z</atom:updated>
            <content:encoded><![CDATA[<p>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.</p><h3>Prerequisites</h3><p>What do you need to follow along?</p><ul><li>Working knowledge of Golang.</li><li>Go &amp; Docker installed on your PC.</li><li>Basic knowledge of Kafka. If you need a refresher, my <a href="https://medium.com/blog/1f6874d4-270c-48e1-9798-324b494c7f0e">guide on fault-tolerant Kafka pipelines</a> covers everything we use here.</li><li>At least 8 hours of sleep (too much to ask for?)</li></ul><h3>The Monolith</h3><p>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.</p><p>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:</p><ol><li>Place the order.</li><li>Reserve the stock.</li><li>Process the payment.</li></ol><p>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.</p><h3>ACID, Defined</h3><p>ACID is an acronym that refers to the set of 4 key properties that define a transaction:</p><ul><li><strong>Atomicity</strong>: 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.</li><li><strong>Consistency</strong>: 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.</li><li><strong>Isolation</strong>: 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.</li><li><strong>Durability</strong>: Ensures that changes to your data made by successfully executed transactions will be saved, even in the event of system failure.</li></ul><p>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.</p><h3>Splitting Into Microservices</h3><p>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.</p><p>When a user makes a purchase now, the flow changes. The purchase touches three services instead of one:</p><ol><li>The order service.</li><li>The inventory service.</li><li>The payment service.</li></ol><p>There is no single database transaction that can wrap all three anymore. So how do we ensure ACID when one purchase spans every service?</p><p>Easy. We just hope nothing ever fails halfway through a purchase. And if something does? Who cares?</p><p>There, fixed!</p><p>Okay, seriously now. How do we get an ACID-like transaction across different microservices?</p><h3>Distributed Transactions, Defined</h3><p>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.</p><p>There are two main ways to approach distributed transactions:</p><ol><li>Two-phase commit (2PC).</li><li>The saga pattern.</li></ol><p>2PC uses a coordinator to run a transaction across every participant in two phases:</p><ul><li><strong>Prepare phase</strong>: The coordinator asks each participant if it can commit. Each participant locks the data it needs and votes yes or no.</li><li><strong>Commit phase</strong>: If every participant votes yes, the coordinator tells them all to commit. If any participant votes no, it tells them all to roll back.</li></ul><p>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.</p><p>In this article, I’ll be focusing on the saga pattern, as it is the one used in most production implementations today.</p><h3>The Saga Pattern</h3><p>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.</p><p>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.</p><p>The compensating transactions run in reverse order, so the last step that completed is the first one we undo.</p><h3>Eventual Consistency</h3><p>So how does the data stay consistent? The magic word is <strong>eventual consistency</strong>.</p><p>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.</p><h3>Our Order Saga</h3><p>Here is what the saga looks like for our order example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LLZ3Ze3kkUbCJ-v1.png" /></figure><p>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.</p><h3>Choreography vs Orchestration</h3><p>There are two ways of coordinating sagas:</p><ul><li><strong>Choreography</strong>: 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.</li><li><strong>Orchestration</strong>: An orchestrator (an object) tells the participants which local transactions to execute. The whole flow, including the rollback, lives in one place.</li></ul><p>In our Go example, we will be using orchestration.</p><h3>Implementing the Saga in Golang</h3><p>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).</p><h3>Project Structure</h3><p>Here is how the code is laid out:</p><pre>cmd/main.go                    wires everything together<br>internal/domain/saga           the reusable saga<br>internal/domain/order          the order model<br>internal/service/order         the order service and the saga steps<br>internal/adapters/kafka        producer, consumers, retry topics<br>internal/adapters/api          the HTTP handler</pre><h3>The Saga</h3><p>First, we define our saga and its steps, along with the basic functionality like adding a step and executing the saga:</p><pre>package saga</pre><pre>import (<br>	&quot;context&quot;<br>	&quot;errors&quot;<br>	&quot;fmt&quot;<br>	&quot;slices&quot;<br>	&quot;sync&quot;<br>)</pre><pre>type Step struct {<br>	Name       string<br>	Action     func(ctx context.Context, data map[string]interface{}) error<br>	Compensate func(ctx context.Context, data map[string]interface{}) error<br>}</pre><pre>type Saga struct {<br>	name  string<br>	steps []Step<br>	mu    sync.Mutex<br>}</pre><pre>func New(name string) *Saga {<br>	return &amp;Saga{<br>		name:  name,<br>		steps: make([]Step, 0),<br>	}<br>}</pre><pre>func (s *Saga) AddStep(step Step) *Saga {<br>	s.mu.Lock()<br>	defer s.mu.Unlock()</pre><pre>	s.steps = append(s.steps, step)</pre><pre>	return s<br>}</pre><pre>type ExecutionResult struct {<br>	Success              bool<br>	FailedStep           string<br>	Error                error<br>	CompletedSteps       []string<br>	RolledBack           bool<br>	PendingCompensations []string<br>	CompensationError    error<br>}</pre><pre>func (s *Saga) Execute(ctx context.Context, data map[string]interface{}) ExecutionResult {</pre><pre>	s.mu.Lock()<br>	defer s.mu.Unlock()</pre><pre>	completedSteps := make([]string, 0, len(s.steps))<br>	result := ExecutionResult{Success: true}</pre><pre>	for _, step := range s.steps {<br>		select {<br>		case &lt;-ctx.Done():<br>			// Context cancelled, rollback<br>			return s.fail(ctx, step.Name, ctx.Err(), completedSteps, data)</pre><pre>		default:<br>		}</pre><pre>		if err := step.Action(ctx, data); err != nil {<br>			return s.fail(ctx, step.Name, err, completedSteps, data)<br>		}</pre><pre>		completedSteps = append(completedSteps, step.Name)<br>	}</pre><pre>	result.CompletedSteps = completedSteps<br>	return result<br>}</pre><pre>func (s *Saga) fail(ctx context.Context, stepName string, err error, completedSteps []string, data map[string]interface{}) ExecutionResult {<br>	toCompensate := slices.Clone(completedSteps)<br>	slices.Reverse(toCompensate)</pre><pre>	pending, compErr := s.compensate(context.WithoutCancel(ctx), toCompensate, data)</pre><pre>	return ExecutionResult{<br>		Success:              false,<br>		FailedStep:           stepName,<br>		Error:                err,<br>		CompletedSteps:       completedSteps,<br>		RolledBack:           compErr == nil,<br>		PendingCompensations: pending,<br>		CompensationError:    compErr,<br>	}<br>}</pre><pre>func (s *Saga) Compensate(ctx context.Context, stepNames []string, data map[string]interface{}) ([]string, error) {<br>	s.mu.Lock()<br>	defer s.mu.Unlock()</pre><pre>	return s.compensate(ctx, stepNames, data)<br>}</pre><pre>func (s *Saga) compensate(ctx context.Context, stepNames []string, data map[string]interface{}) ([]string, error) {<br>	stepMap := make(map[string]Step)</pre><pre>	for _, step := range s.steps {<br>		stepMap[step.Name] = step<br>	}</pre><pre>	var failed []string<br>	var errs []error<br>	for _, stepName := range stepNames {<br>		step, ok := stepMap[stepName]<br>		if !ok {<br>			return nil, fmt.Errorf(&quot;saga %s has no step %q&quot;, s.name, stepName)<br>		}</pre><pre>		if step.Compensate != nil {<br>			if err := step.Compensate(ctx, data); err != nil {<br>				failed = append(failed, stepName)<br>				errs = append(errs, fmt.Errorf(&quot;compensate %s: %w&quot;, stepName, err))<br>			}<br>		}<br>	}<br>	return failed, errors.Join(errs...)<br>}</pre><p>So in the code above, we define a Step, the Saga that holds the steps, and the functions that run and undo them:</p><ul><li><strong>Step</strong>: 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.</li><li><strong>AddStep</strong>: It returns the saga itself, so we can chain steps together when we build the saga.</li><li><strong>Execute</strong>: 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.</li><li><strong>fail</strong>: 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&#39;t want to stop halfway through undoing an order.</li><li><strong>compensate</strong>: 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.</li><li><strong>Compensate</strong>: This is the public version of compensate. We will use it later to retry the compensations that failed.</li></ul><p>The ExecutionResult tells the caller exactly how things went:</p><ul><li>Success is true when every step completed.</li><li>RolledBack is true when a step failed but every compensation worked.</li><li>PendingCompensations lists the compensations that failed, so we can retry them.</li></ul><h3>The Order Model</h3><p>Next, let’s define our order structure:</p><pre>package order</pre><pre>import (<br>	&quot;errors&quot;<br>	&quot;fmt&quot;<br>)</pre><pre>var ErrInvalidOrder = errors.New(&quot;invalid order&quot;)</pre><pre>type OrderStatus string<br>type PaymentStatus string</pre><pre>const (<br>	StatusProcessing OrderStatus   = &quot;PROCESSING&quot;<br>	PaymentPaid      PaymentStatus = &quot;PAID&quot;<br>)</pre><pre>type Address struct {<br>	Street     string `json:&quot;street&quot;`<br>	City       string `json:&quot;city&quot;`<br>	State      string `json:&quot;state&quot;`<br>	Country    string `json:&quot;country&quot;`<br>	PostalCode string `json:&quot;postal_code,omitempty&quot;`<br>}</pre><pre>type OrderItem struct {<br>	Quantity  int64 `json:&quot;quantity&quot;`<br>	UnitPrice int64 `json:&quot;unit_price&quot;`<br>	Total     int64 `json:&quot;total&quot;`<br>}</pre><pre>type Order struct {<br>	ID              string        `json:&quot;id&quot;`<br>	Status          OrderStatus   `json:&quot;status&quot;`<br>	UserID          string        `json:&quot;user_id&quot;`<br>	ProductID       string        `json:&quot;product_id&quot;`<br>	Item            OrderItem     `json:&quot;item&quot;`<br>	ShippingAddress Address       `json:&quot;shipping_address&quot;`<br>	PaymentStatus   PaymentStatus `json:&quot;payment_status&quot;`<br>}</pre><pre>func (o Order) Validate() error {<br>	switch {<br>	case o.UserID == &quot;&quot;:<br>		return fmt.Errorf(&quot;%w: user_id is required&quot;, ErrInvalidOrder)<br>	case o.ProductID == &quot;&quot;:<br>		return fmt.Errorf(&quot;%w: product_id is required&quot;, ErrInvalidOrder)<br>	case o.Item.Quantity &lt;= 0:<br>		return fmt.Errorf(&quot;%w: quantity must be greater than 0&quot;, ErrInvalidOrder)<br>	case o.Item.UnitPrice &lt; 0:<br>		return fmt.Errorf(&quot;%w: unit_price cannot be negative&quot;, ErrInvalidOrder)<br>	}<br>	return nil<br>}</pre><p>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.</p><h3>The Order Service</h3><p>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:</p><pre>package order</pre><pre>import (<br>	&quot;context&quot;<br>	&quot;crypto/rand&quot;<br>	&quot;encoding/hex&quot;<br>	&quot;fmt&quot;<br>	&quot;log&quot;</pre><pre>	&quot;github.com/umohsamuel/distributed-transactions/internal/domain/order&quot;<br>	&quot;github.com/umohsamuel/distributed-transactions/internal/domain/saga&quot;<br>)</pre><pre>type Events interface {<br>	OrderCreated(ctx context.Context, o order.Order) error<br>	CompensationFailed(ctx context.Context, orderID string, steps []string, data map[string]interface{}, cause error) error<br>}</pre><pre>type Service struct {<br>	events    Events<br>	orders    *OrderService<br>	inventory *InventoryService<br>	payments  *PaymentService<br>}</pre><pre>func NewService(events Events) *Service {<br>	return &amp;Service{<br>		events:    events,<br>		orders:    &amp;OrderService{},<br>		inventory: &amp;InventoryService{releaseAttempts: make(map[string]int)},<br>		payments:  &amp;PaymentService{},<br>	}<br>}</pre><pre>func (s *Service) PlaceOrder(ctx context.Context, o order.Order) (order.Order, error) {<br>	if err := o.Validate(); err != nil {<br>		return order.Order{}, err<br>	}</pre><pre>	id, err := newOrderID()<br>	if err != nil {<br>		return order.Order{}, err<br>	}</pre><pre>	o.ID = id<br>	o.Status = order.StatusProcessing<br>	o.PaymentStatus = &quot;&quot;<br>	o.Item.Total = o.Item.Quantity * o.Item.UnitPrice</pre><pre>	if err := s.events.OrderCreated(ctx, o); err != nil {<br>		return order.Order{}, fmt.Errorf(&quot;publish order created: %w&quot;, err)<br>	}<br>	return o, nil<br>}</pre><pre>// ProcessOrder runs the order saga. It is the entry point for the Kafka consumer.<br>func (s *Service) ProcessOrder(ctx context.Context, o order.Order) error {<br>	if err := o.Validate(); err != nil {<br>		return err<br>	}</pre><pre>	data := map[string]interface{}{<br>		&quot;order_id&quot;:   o.ID,<br>		&quot;product_id&quot;: o.ProductID,<br>		&quot;quantity&quot;:   int(o.Item.Quantity),<br>		&quot;amount&quot;:     float64(o.Item.Total),<br>	}</pre><pre>	result := s.newSaga().Execute(ctx, data)<br>	if !result.Success {<br>		if !result.RolledBack {<br>			if err := s.events.CompensationFailed(ctx, o.ID, result.PendingCompensations, data, result.CompensationError); err != nil {<br>				return fmt.Errorf(&quot;order %s: schedule compensation retry: %w&quot;, o.ID, err)<br>			}<br>			return fmt.Errorf(&quot;order %s failed at step %q: %w; compensation retry scheduled: %v&quot;, o.ID, result.FailedStep, result.Error, result.CompensationError)<br>		}<br>		return fmt.Errorf(&quot;order %s failed at step %q and was rolled back: %w&quot;, o.ID, result.FailedStep, result.Error)<br>	}</pre><pre>	log.Printf(&quot;Order %s completed: %v&quot;, o.ID, result.CompletedSteps)<br>	return nil<br>}</pre><pre>func (s *Service) RetryCompensation(ctx context.Context, steps []string, data map[string]interface{}) error {<br>	if _, err := s.newSaga().Compensate(ctx, steps, data); err != nil {<br>		return err<br>	}</pre><pre>	log.Printf(&quot;Order %v rolled back after retrying compensations: %v&quot;, data[&quot;order_id&quot;], steps)<br>	return nil<br>}</pre><pre>// newSaga builds a fresh saga per order, since Execute holds the saga&#39;s lock for<br>// the whole run and a shared instance would process one order at a time.<br>func (s *Service) newSaga() *saga.Saga {<br>	return saga.New(&quot;order-processing&quot;).<br>		AddStep(saga.Step{<br>			Name:       &quot;create-order&quot;,<br>			Action:     s.orders.CreateOrder,<br>			Compensate: s.orders.CancelOrder,<br>		}).<br>		AddStep(saga.Step{<br>			Name:       &quot;reserve-inventory&quot;,<br>			Action:     s.inventory.ReserveStock,<br>			Compensate: s.inventory.ReleaseStock,<br>		}).<br>		AddStep(saga.Step{<br>			Name:       &quot;process-payment&quot;,<br>			Action:     s.payments.ProcessPayment,<br>			Compensate: s.payments.RefundPayment,<br>		})<br>}</pre><pre>func newOrderID() (string, error) {<br>	b := make([]byte, 8)<br>	if _, err := rand.Read(b); err != nil {<br>		return &quot;&quot;, fmt.Errorf(&quot;generate order id: %w&quot;, err)<br>	}<br>	return &quot;ord_&quot; + hex.EncodeToString(b), nil<br>}</pre><p>The service has two jobs: accepting orders and processing them.</p><ul><li><strong>Events</strong>: 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.</li><li><strong>PlaceOrder</strong>: 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.</li><li><strong>ProcessOrder</strong>: 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:</li><li>Every step worked, so we log it and we are done.</li><li>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.</li><li>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.</li><li><strong>RetryCompensation</strong>: 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.</li><li><strong>newSaga</strong>: 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.</li></ul><h3>The Steps and Their Compensations</h3><p>Next, each step and its compensating action:</p><pre>package order</pre><pre>import (<br>	&quot;context&quot;<br>	&quot;fmt&quot;<br>	&quot;sync&quot;<br>)</pre><pre>type OrderService struct{}</pre><pre>func (o *OrderService) CreateOrder(ctx context.Context, data map[string]interface{}) error {<br>	orderID := data[&quot;order_id&quot;].(string)<br>	fmt.Printf(&quot;Creating order %s\n&quot;, orderID)<br>	data[&quot;order_created&quot;] = true<br>	return nil<br>}</pre><pre>func (o *OrderService) CancelOrder(ctx context.Context, data map[string]interface{}) error {<br>	orderID := data[&quot;order_id&quot;].(string)<br>	fmt.Printf(&quot;Cancelling order %s\n&quot;, orderID)<br>	return nil<br>}</pre><pre>const releaseFailures = 2</pre><pre>type InventoryService struct {<br>	mu              sync.Mutex<br>	releaseAttempts map[string]int<br>}</pre><pre>func (i *InventoryService) ReserveStock(ctx context.Context, data map[string]interface{}) error {<br>	productID := data[&quot;product_id&quot;].(string)<br>	quantity := number(data[&quot;quantity&quot;])<br>	fmt.Printf(&quot;Reserving %d units of product %s\n&quot;, quantity, productID)<br>	data[&quot;stock_reserved&quot;] = true<br>	return nil<br>}</pre><pre>func (i *InventoryService) ReleaseStock(ctx context.Context, data map[string]interface{}) error {<br>	orderID := data[&quot;order_id&quot;].(string)<br>	productID := data[&quot;product_id&quot;].(string)<br>	quantity := number(data[&quot;quantity&quot;])</pre><pre>	i.mu.Lock()<br>	i.releaseAttempts[orderID]++<br>	attempt := i.releaseAttempts[orderID]<br>	i.mu.Unlock()</pre><pre>	if attempt &lt;= releaseFailures {<br>		return fmt.Errorf(&quot;inventory service unavailable (release attempt %d)&quot;, attempt)<br>	}</pre><pre>	fmt.Printf(&quot;Releasing %d units of product %s (release attempt %d)\n&quot;, quantity, productID, attempt)<br>	return nil<br>}</pre><pre>func number(v interface{}) int {<br>	switch n := v.(type) {<br>	case int:<br>		return n<br>	case float64:<br>		return int(n)<br>	}<br>	return 0<br>}</pre><pre>const paymentLimit = 1000</pre><pre>type PaymentService struct{}</pre><pre>func (p *PaymentService) ProcessPayment(ctx context.Context, data map[string]interface{}) error {<br>	amount := data[&quot;amount&quot;].(float64)</pre><pre>	if amount &gt; paymentLimit {<br>		return fmt.Errorf(&quot;payment of $%.2f declined: insufficient funds&quot;, amount)<br>	}</pre><pre>	fmt.Printf(&quot;Processing payment of $%.2f\n&quot;, amount)<br>	data[&quot;payment_id&quot;] = &quot;pay_123456&quot;<br>	return nil<br>}</pre><pre>func (p *PaymentService) RefundPayment(ctx context.Context, data map[string]interface{}) error {<br>	if paymentID, ok := data[&quot;payment_id&quot;].(string); ok {<br>		fmt.Printf(&quot;Refunding payment %s\n&quot;, paymentID)<br>	}<br>	return nil<br>}</pre><p>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:</p><ul><li><strong>ProcessPayment</strong>: 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.</li><li><strong>ReleaseStock</strong>: 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.</li></ul><p>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.</p><p>Here is how a failed compensation moves through the retries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rv4cyXsXkYL5ol82.png" /></figure><h3>The Kafka Adapter</h3><p>Next, the order adapter for Kafka:</p><pre>package kafka</pre><pre>import (<br>	&quot;context&quot;<br>	&quot;encoding/json&quot;<br>	&quot;fmt&quot;</pre><pre>	&quot;github.com/IBM/sarama&quot;<br>	&quot;github.com/umohsamuel/distributed-transactions/internal/domain/order&quot;<br>)</pre><pre>type OrderPublisher struct {<br>	producer *KafkaProducer<br>	router   *RetryRouter<br>}</pre><pre>func NewOrderPublisher(producer *KafkaProducer, router *RetryRouter) *OrderPublisher {<br>	return &amp;OrderPublisher{producer: producer, router: router}<br>}</pre><pre>func (p *OrderPublisher) OrderCreated(ctx context.Context, o order.Order) error {<br>	value, err := json.Marshal(o)<br>	if err != nil {<br>		return fmt.Errorf(&quot;encode order: %w&quot;, err)<br>	}</pre><pre>	return p.producer.send(&amp;sarama.ProducerMessage{<br>		Topic: CREATED.String(),<br>		Key:   sarama.StringEncoder(o.ID),<br>		Value: sarama.ByteEncoder(value),<br>	})<br>}</pre><pre>type compensationMessage struct {<br>	OrderID string                 `json:&quot;order_id&quot;`<br>	Steps   []string               `json:&quot;steps&quot;`<br>	Data    map[string]interface{} `json:&quot;data&quot;`<br>}</pre><pre>func (p *OrderPublisher) CompensationFailed(ctx context.Context, orderID string, steps []string, data map[string]interface{}, cause error) error {<br>	value, err := json.Marshal(compensationMessage{OrderID: orderID, Steps: steps, Data: data})<br>	if err != nil {<br>		return fmt.Errorf(&quot;encode compensation: %w&quot;, err)<br>	}</pre><pre>	return p.router.Schedule([]byte(orderID), value, CREATED.String(), cause)<br>}</pre><pre>type OrderProcessor interface {<br>	ProcessOrder(ctx context.Context, o order.Order) error<br>}</pre><pre>func OrderCreatedHandler(orders OrderProcessor) HandlerFunc {<br>	return func(ctx context.Context, msg Message) error {<br>		var o order.Order<br>		if err := json.Unmarshal(msg.Value, &amp;o); err != nil {<br>			return fmt.Errorf(&quot;decode order: %w&quot;, err)<br>		}</pre><pre>		return orders.ProcessOrder(ctx, o)<br>	}<br>}</pre><pre>type CompensationRetrier interface {<br>	RetryCompensation(ctx context.Context, steps []string, data map[string]interface{}) error<br>}</pre><pre>func CompensationHandler(orders CompensationRetrier) HandlerFunc {<br>	return func(ctx context.Context, msg Message) error {<br>		var c compensationMessage<br>		if err := json.Unmarshal(msg.Value, &amp;c); err != nil {<br>			return Permanent(fmt.Errorf(&quot;decode compensation: %w&quot;, err))<br>		}</pre><pre>		return orders.RetryCompensation(ctx, c.Steps, c.Data)<br>	}<br>}</pre><p>This is the bridge between our service and Kafka. The OrderPublisher is what we pass to the service as its Events.</p><ul><li><strong>OrderCreated</strong>: 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.</li><li><strong>compensationMessage</strong>: 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).</li><li><strong>CompensationFailed</strong>: It encodes the message and calls Schedule on the retry router, which sends it to the first retry topic.</li><li><strong>OrderCreatedHandler</strong> and <strong>CompensationHandler</strong>: 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&#39;t even be decoded, retrying won&#39;t fix it, so we mark it Permanent and the router sends it straight to the DLQ.</li></ul><p>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 <a href="https://medium.com/blog/1f6874d4-270c-48e1-9798-324b494c7f0e">Kafka pipelines guide</a>, and the shutdown is covered in my <a href="https://medium.com/blog/2fbbf043-1b2e-45ab-bfc9-b7eafd89926c">graceful shutdown guide</a>. If you want to have a look, you can go through the repository linked at the end of this guide.</p><h3>The API Adapter</h3><p>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):</p><pre>package api</pre><pre>import (<br>	&quot;context&quot;<br>	&quot;errors&quot;<br>	&quot;log&quot;<br>	&quot;net/http&quot;</pre><pre>	&quot;github.com/gin-gonic/gin&quot;<br>	&quot;github.com/umohsamuel/distributed-transactions/internal/domain/order&quot;<br>)</pre><pre>type OrderPlacer interface {<br>	PlaceOrder(ctx context.Context, o order.Order) (order.Order, error)<br>}</pre><pre>type OrderHandler struct {<br>	orders OrderPlacer<br>}</pre><pre>func NewOrderHandler(orders OrderPlacer) *OrderHandler {<br>	return &amp;OrderHandler{orders: orders}<br>}</pre><pre>func (h *OrderHandler) Register(r gin.IRouter) {<br>	r.POST(&quot;/orders&quot;, h.createOrder)<br>}</pre><pre>type createOrderRequest struct {<br>	UserID          string         `json:&quot;user_id&quot; binding:&quot;required&quot;`<br>	ProductID       string         `json:&quot;product_id&quot; binding:&quot;required&quot;`<br>	Quantity        int64          `json:&quot;quantity&quot; binding:&quot;required,gt=0&quot;`<br>	UnitPrice       int64          `json:&quot;unit_price&quot; binding:&quot;gte=0&quot;`<br>	ShippingAddress addressRequest `json:&quot;shipping_address&quot; binding:&quot;required&quot;`<br>}</pre><pre>type addressRequest struct {<br>	Street     string `json:&quot;street&quot; binding:&quot;required&quot;`<br>	City       string `json:&quot;city&quot; binding:&quot;required&quot;`<br>	State      string `json:&quot;state&quot;`<br>	Country    string `json:&quot;country&quot; binding:&quot;required&quot;`<br>	PostalCode string `json:&quot;postal_code&quot;`<br>}</pre><pre>type createOrderResponse struct {<br>	OrderID string            `json:&quot;order_id&quot;`<br>	Status  order.OrderStatus `json:&quot;status&quot;`<br>}</pre><pre>func (req createOrderRequest) toDomain() order.Order {<br>	return order.Order{<br>		UserID:    req.UserID,<br>		ProductID: req.ProductID,<br>		Item: order.OrderItem{<br>			Quantity:  req.Quantity,<br>			UnitPrice: req.UnitPrice,<br>		},<br>		ShippingAddress: order.Address{<br>			Street:     req.ShippingAddress.Street,<br>			City:       req.ShippingAddress.City,<br>			State:      req.ShippingAddress.State,<br>			Country:    req.ShippingAddress.Country,<br>			PostalCode: req.ShippingAddress.PostalCode,<br>		},<br>	}<br>}</pre><pre>func (h *OrderHandler) createOrder(c *gin.Context) {<br>	var req createOrderRequest<br>	if err := c.ShouldBindJSON(&amp;req); err != nil {<br>		c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()})<br>		return<br>	}</pre><pre>	placed, err := h.orders.PlaceOrder(c.Request.Context(), req.toDomain())<br>	if err != nil {<br>		writeError(c, err)<br>		return<br>	}</pre><pre>	c.JSON(http.StatusAccepted, createOrderResponse{<br>		OrderID: placed.ID,<br>		Status:  placed.Status,<br>	})<br>}</pre><pre>func writeError(c *gin.Context, err error) {<br>	switch {<br>	case errors.Is(err, order.ErrInvalidOrder):<br>		c.JSON(http.StatusUnprocessableEntity, gin.H{&quot;error&quot;: err.Error()})<br>	default:<br>		log.Printf(&quot;%s %s: %v&quot;, c.Request.Method, c.FullPath(), err)<br>		c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: &quot;something went wrong, please try again&quot;})<br>	}<br>}</pre><p>The handler keeps the HTTP details away from our domain:</p><ul><li><strong>createOrderRequest</strong>: 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.</li><li><strong>toDomain</strong>: 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.</li><li><strong>writeError</strong>: 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&#39;t leak internal errors to the user.</li></ul><h3>Wiring Everything Together</h3><p>Next, we wire everything together in main:</p><pre>package main</pre><pre>import (<br>	&quot;context&quot;<br>	&quot;errors&quot;<br>	&quot;log&quot;<br>	&quot;net/http&quot;<br>	&quot;os&quot;<br>	&quot;os/signal&quot;<br>	&quot;sync&quot;<br>	&quot;syscall&quot;<br>	&quot;time&quot;</pre><pre>	&quot;github.com/gin-gonic/gin&quot;<br>	&quot;github.com/umohsamuel/distributed-transactions/internal/adapters/api&quot;<br>	&quot;github.com/umohsamuel/distributed-transactions/internal/adapters/kafka&quot;<br>	ordersvc &quot;github.com/umohsamuel/distributed-transactions/internal/service/order&quot;<br>)</pre><pre>func main() {<br>	brokersUrl := []string{&quot;localhost:9092&quot;}</pre><pre>	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)<br>	defer stop()</pre><pre>	producer, err := kafka.NewKafkaProducer(brokersUrl)<br>	if err != nil {<br>		log.Fatalf(&quot;Failed to initialize Kafka producer: %v&quot;, err)<br>	}<br>	defer producer.Close()</pre><pre>	router := kafka.NewRetryRouter(producer, kafka.RetryTopics, kafka.DLQ.String())<br>	orders := ordersvc.NewService(kafka.NewOrderPublisher(producer, router))</pre><pre>	groups := []struct {<br>		group  kafka.ConsumerGroup<br>		topic  kafka.Topics<br>		handle kafka.HandlerFunc<br>		router *kafka.RetryRouter<br>		delay  time.Duration<br>	}{<br>		{kafka.ORDERS_MAIN_GROUP, kafka.CREATED, kafka.OrderCreatedHandler(orders), nil, 0},<br>		{kafka.ORDERS_1M_RETRY_GROUP, kafka.RETRY_1M, kafka.CompensationHandler(orders), router, time.Second},<br>		{kafka.ORDERS_5M_RETRY_GROUP, kafka.RETRY_5M, kafka.CompensationHandler(orders), router, 5 * time.Second},<br>		{kafka.ORDERS_10M_RETRY_GROUP, kafka.RETRY_10M, kafka.CompensationHandler(orders), router, 10 * time.Second},<br>	}</pre><pre>	var wg sync.WaitGroup<br>	for _, g := range groups {<br>		consumer, err := kafka.NewKafkaConsumer(brokersUrl, g.group.String())<br>		if err != nil {<br>			log.Fatalf(&quot;Failed to start %s: %v&quot;, g.group, err)<br>		}</pre><pre>		handler := kafka.NewConsumerGroupHandler(g.handle, g.router, g.delay)<br>		wg.Go(func() {<br>			if err := consumer.Run(ctx, []string{g.topic.String()}, handler); err != nil {<br>				log.Printf(&quot;%s stopped: %v&quot;, g.group, err)<br>			}<br>		})<br>	}</pre><pre>	engine := gin.Default()</pre><pre>	v1 := engine.Group(&quot;/api/v1&quot;)<br>	api.NewOrderHandler(orders).Register(v1)</pre><pre>	srv := &amp;http.Server{<br>		Addr:    &quot;:8080&quot;,<br>		Handler: engine,<br>	}</pre><pre>	go func() {<br>		if err := srv.ListenAndServe(); err != nil &amp;&amp; !errors.Is(err, http.ErrServerClosed) {<br>			log.Printf(&quot;HTTP server failed: %v&quot;, err)<br>			stop()<br>		}<br>	}()</pre><pre>	log.Println(&quot;Server and consumers running&quot;)<br>	&lt;-ctx.Done()<br>	log.Println(&quot;Interruption detected, shutting down gracefully...&quot;)</pre><pre>	shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)<br>	defer cancel()<br>	if err := srv.Shutdown(shutdownCtx); err != nil {<br>		log.Printf(&quot;HTTP shutdown: %v&quot;, err)<br>	}</pre><pre>	wg.Wait()<br>}</pre><p>So basically:</p><ul><li>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.</li><li>The groups table defines every consumer we run. There is one for the created topic and one for each retry topic.</li><li>The created consumer has no router. That&#39;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.</li><li>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.</li><li>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&#39;t have to wait 16 minutes to see a message hit the DLQ. In production, you would use the real delays.</li><li>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.</li></ul><h3>Testing</h3><p>Now, how do we test this?</p><p>First, we need Kafka running. Here is the Docker Compose file for a single node Kafka in KRaft mode:</p><pre>services:<br>  broker:<br>    image: apache/kafka:latest<br>    hostname: broker<br>    container_name: broker<br>    ports:<br>      - 9092:9092<br>    environment:<br>      KAFKA_BROKER_ID: 1<br>      KAFKA_NODE_ID: 1<br>      KAFKA_PROCESS_ROLES: broker,controller<br>      CLUSTER_ID: 8yPqetQpLSJu3qfIpWnnjQ<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT,CONTROLLER:PLAINTEXT<br>      KAFKA_LISTENERS: PLAINTEXT://broker:29092,CONTROLLER://broker:29093,PLAINTEXT_HOST://0.0.0.0:9092<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:29092,PLAINTEXT_HOST://localhost:9092<br>      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT<br>      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER<br>      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@broker:29093<br>      KAFKA_LOG_DIRS: /tmp/kraft-combined-logs<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0<br>      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1<br>      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1</pre><p>If you want to know what each of these settings does, I explained them in my <a href="https://medium.com/blog/1f6874d4-270c-48e1-9798-324b494c7f0e">Kafka pipelines guide</a>.</p><p>Start Kafka, then run the server:</p><pre>docker compose up -d<br>go run cmd/main.go</pre><p>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:</p><pre>{<br>  &quot;order_id&quot;: &quot;ord_7e840903b59d1253&quot;,<br>  &quot;status&quot;: &quot;PROCESSING&quot;<br>}</pre><p>The response only tells you the order was accepted. To see what actually happened, watch the console where the server is running.</p><h3>The Happy Path</h3><p>Send an order with a total of $400 (2 × $200), which is under our $1000 payment limit:</p><pre>{<br>  &quot;user_id&quot;: &quot;u1&quot;,<br>  &quot;product_id&quot;: &quot;p1&quot;,<br>  &quot;quantity&quot;: 2,<br>  &quot;unit_price&quot;: 200,<br>  &quot;shipping_address&quot;: {<br>    &quot;street&quot;: &quot;00, Allen Avenue&quot;,<br>    &quot;city&quot;: &quot;Ikeja&quot;,<br>    &quot;country&quot;: &quot;NG&quot;<br>  }<br>}</pre><p>Every step goes through, and you should see this in the console:</p><pre>Creating order ord_7e840903b59d1253<br>Reserving 2 units of product p1<br>Processing payment of $400.00<br>Order ord_7e840903b59d1253 completed: [create-order reserve-inventory process-payment]</pre><h3>Payment Failure and Rollback</h3><p>Now send an order with a total of $3000 (5 × $600), which is over the payment limit:</p><pre>{<br>  &quot;user_id&quot;: &quot;u1&quot;,<br>  &quot;product_id&quot;: &quot;p1&quot;,<br>  &quot;quantity&quot;: 5,<br>  &quot;unit_price&quot;: 600,<br>  &quot;shipping_address&quot;: {<br>    &quot;street&quot;: &quot;00, Allen Avenue&quot;,<br>    &quot;city&quot;: &quot;Ikeja&quot;,<br>    &quot;country&quot;: &quot;NG&quot;<br>  }<br>}</pre><p>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:</p><pre>Creating order ord_88dcc49ea1e17837<br>Reserving 5 units of product p1<br>Cancelling order ord_88dcc49ea1e17837<br>Routing message to topic: retry_1m (Attempt #1): compensate reserve-inventory: inventory service unavailable (release attempt 1)<br>Processing failed on topic created: order ord_88dcc49ea1e17837 failed at step &quot;process-payment&quot;: payment of $3000.00 declined: insufficient funds; compensation retry scheduled: compensate reserve-inventory: inventory service unavailable (release attempt 1)</pre><p>A second later, the first retry fails too, and the message moves to the next tier:</p><pre>Processing failed on topic retry_1m. Routing to next stage...<br>Routing message to topic: retry_5m (Attempt #2): compensate reserve-inventory: inventory service unavailable (release attempt 2)</pre><p>Five seconds after that, the inventory service is “back”, and the release finally works:</p><pre>Releasing 5 units of product p1 (release attempt 3)<br>Order ord_88dcc49ea1e17837 rolled back after retrying compensations: [reserve-inventory]</pre><p>The order failed, but the system ended up clean. The stock was released and the order was cancelled. That’s eventual consistency in action.</p><p>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&#39;s where a human steps in to fix it.</p><h3>Bad Requests</h3><p>Lastly, try sending an order with &quot;quantity&quot;: 0, or remove the product_id field. Gin rejects it with a 400 before anything reaches Kafka.</p><h3>Conclusion</h3><p>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:</p><ul><li>ACID transactions work great inside one database, but they can’t span multiple microservices, each with its own database.</li><li>The saga pattern splits a business transaction into local transactions, each with a compensating transaction that undoes it.</li><li>When a step fails, the completed steps are undone in reverse order, and the failed step itself is not compensated.</li><li>A step that fails because of a business rule (like a declined payment) is a finished outcome, not something to retry.</li><li>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.</li></ul><p>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:</p><ul><li><strong>Only eventual consistency</strong>: 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.</li><li><strong>More code to maintain</strong>: 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.</li><li><strong>Idempotency</strong>: 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.</li><li><strong>Lack of isolation</strong>: 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.</li></ul><p>(If you want to see the full codebase, check out the <a href="https://github.com/umohsamuel/distributed-transactions">repository</a>. Play around with it and lmk what you think)</p><h3>References</h3><ul><li><a href="https://www.databricks.com/blog/what-are-acid-transactions">Databricks: What are ACID Transactions?</a></li><li><a href="https://en.wikipedia.org/wiki/Distributed_transaction">Wikipedia: Distributed Transaction</a></li><li><a href="https://microservices.io/patterns/data/saga.html">Microservices.io: Pattern: Saga</a></li><li><a href="https://oneuptime.com/blog/post/2026-01-25-saga-pattern-distributed-transactions-go/view">OneUptime: How to Implement the Saga Pattern for Distributed Transactions in Go</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28077b0ea0b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Fault-Tolerant, Event-Driven Kafka Pipelines in Go: Reliable Reprocessing & Dead Letter…]]></title>
            <link>https://medium.com/@umohsg/building-fault-tolerant-event-driven-kafka-pipelines-in-go-reliable-reprocessing-dead-letter-ea84634222d7?source=rss-98d0e0748007------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea84634222d7</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Samuel Umoh ]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 00:44:50 GMT</pubDate>
            <atom:updated>2026-08-18T00:44:50.255Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Fault-Tolerant, Event-Driven Kafka Pipelines in Go: Reliable Reprocessing &amp; Dead Letter Queues</h3><blockquote><em>A practical guide to building reliable event-driven systems in Go using Apache Kafka. Learn how to implement tiered retry strategies with delayed reprocessing, route permanently failed messages to dead letter queues in Golang with Sarama.</em></blockquote><h3>Prerequisites</h3><p>What do you need to follow along?</p><ol><li>Working knowledge of Golang.</li><li>Go &amp; Docker installed on your PC.</li></ol><h3>What is an Event-Driven Architecture?</h3><p>An Event-Driven Architecture (EDA) is a design approach where services communicate by producing and responding to events. Each service operates independently, producing or reacting to events as they happen.</p><h3>What are Events?</h3><p>An event is a record of something that has happened in a system, typically representing a state change or a significant action. An event contains data (payload) describing what happened. An example of an event could be:</p><ol><li>A user signing up for a service.</li><li>A user placing an order in your system.</li></ol><h3>Components of an Event-Driven Architecture</h3><p>To understand how events flow through a system, we need to know three key players:</p><p><strong>Event Producers</strong>: They are the sources of events. They generate and publish events like signup events, order placed events, etc. Producers generate events and transmit them to the rest of the system. They do not know who is listening for or handling the events.</p><p><strong>Event Brokers</strong>: They sit between producers and consumers, decoupling them so neither needs a direct connection to the other. Brokers receive event messages, maintain their chronological order, make them available for consumption, and route them to the right consumers. <a href="https://kafka.apache.org/">Apache Kafka</a> is an example of an event broker, and it’s the one we’ll use throughout this guide.</p><p><strong>Event Consumers</strong>: They handle the processing tasks. They listen on event channels and react when an event they are subscribed to is published, then they process the event, which can include making API calls, updating a database, triggering other events, or logging information.</p><h3>The Complete Flow</h3><p>With those three pieces in place, the flow of an EDA looks like this:</p><ul><li>When an app or service performs an action that another part of the system needs to know about, it publishes a new event to the broker.</li><li>The broker receives the event, maintains the event’s order relative to others in the stream, and then routes it to the appropriate consumer.</li><li>An event consumer then ingests the message in real time or at a later relevant instance and processes it to trigger another action.</li></ul><h3>Apache Kafka, Defined</h3><p>Apache Kafka is an open-source, distributed, event-streaming platform used to publish, store, process, and consume real-time data streams. It is based on a publish-subscribe messaging model and is designed to support fault-tolerant, scalable, high-throughput, and low-latency data pipelines, event-driven applications, and stream-processing systems.</p><h3>Key Apache Kafka Components</h3><ol><li><strong>Messages</strong>: A unit of data comprised of two parts: a key and a value. The value is the actual content being sent, while the key identifies what the message relates to.</li><li><strong>Producers</strong>: Applications that publish events or messages to Kafka topics. A producer can publish to one or more topics and can optionally choose the partition that stores the data.</li><li><strong>Topics</strong>: A topic is a named channel or routing mechanism through which events are published and delivered to consumers. Applications write to and read from topics.</li><li><strong>Partitions</strong>: Subdivisions of a topic that distribute records across multiple brokers. Partitions let Kafka scale horizontally while preserving record order within each partition.</li><li><strong>Brokers</strong>: Kafka servers that store topic partitions, handle client requests, and replicate data across the cluster for fault tolerance.</li><li><strong>Consumers</strong>: Applications that subscribe to topics and read records from partitions.</li><li><strong>Consumer Groups</strong>: Allow multiple consumers to work together to process records from a topic.</li><li><strong>Offsets</strong>: Unique sequential identifiers assigned to records within a partition. Consumers use offsets to track their reading position and replay data when needed.</li></ol><p>Together, these components allow organizations to reliably stream, process, and distribute high-volume data in real time across complex, distributed environments.</p><h3>Setting Up Kafka Locally with Docker</h3><p>Before we write any Go code, we need a running Kafka cluster. We will use Docker Compose to spin up Kafka locally:</p><pre>services:<br>  broker:<br>    image: apache/kafka:latest<br>    hostname: broker<br>    container_name: broker<br>    ports:<br>      - 9092:9092<br>    environment:<br>      KAFKA_BROKER_ID: 1<br>      KAFKA_NODE_ID: 1<br>      KAFKA_PROCESS_ROLES: broker,controller<br>      CLUSTER_ID: 59Uj60pTdxFKv5bUMDYZFA<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT,CONTROLLER:PLAINTEXT<br>      KAFKA_LISTENERS: PLAINTEXT://broker:29092,CONTROLLER://broker:29093,PLAINTEXT_HOST://0.0.0.0:9092<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:29092,PLAINTEXT_HOST://localhost:9092<br>      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT<br>      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER<br>      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@broker:29093<br>      KAFKA_LOG_DIRS: /tmp/kraft-combined-logs<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0<br>      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1<br>      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1</pre><p>Since the introduction of <a href="https://docs.confluent.io/platform/current/kafka-metadata/kraft.html">KRaft</a>, Kafka no longer requires <a href="https://zookeeper.apache.org/">Apache ZooKeeper®</a> for managing cluster metadata. It uses Kafka itself instead. One advantage of the new KRaft mode is that you can have a single Kafka broker to handle both metadata and client requests in a small, local development environment. The docker-compose.yml file for this tutorial uses this approach, leading to faster startup times and simpler configuration. Note that, in a production setting, you’ll have distinct Kafka brokers for handling requests and operating as a cluster controller.</p><p>Start the cluster with:</p><pre>docker compose up -d</pre><h3>Defining Topics and Consumer Groups</h3><p>Before we build the producer and consumer, let’s define the topics and consumer groups that both sides of our pipeline will share. We will keep these in a separate pkg/topics package so both the producer and consumer can import them:</p><pre>// pkg/topics/topics.go<br><br>package topics<br><br>type Topics string<br><br>const (<br> ORDERS_CREATED Topics = &quot;orders_created&quot;<br> RETRY_5M       Topics = &quot;retry_5m&quot;<br> RETRY_20M      Topics = &quot;retry_20m&quot;<br> RETRY_40M      Topics = &quot;retry_40m&quot;<br> ORDERS_DLQ     Topics = &quot;orders_dlq&quot;<br>)<br><br>func (t Topics) String() string {<br> return string(t)<br>}<br><br>type ConsumerGroup string<br><br>const (<br> ORDERS_MAIN_GROUP      ConsumerGroup = &quot;orders_main_group&quot;<br> ORDERS_5M_RETRY_GROUP  ConsumerGroup = &quot;orders_retry_5m_group&quot;<br> ORDERS_20M_RETRY_GROUP ConsumerGroup = &quot;orders_retry_20m_group&quot;<br> ORDERS_40M_RETRY_GROUP ConsumerGroup = &quot;orders_retry_40m_group&quot;<br>)<br><br>func (t ConsumerGroup) String() string {<br> return string(t)<br>}</pre><p>We have a main topic for fresh orders, three retry topics with increasing delays (5 minutes, 20 minutes, 40 minutes), and a dead letter queue (DLQ) for messages that have exhausted all retry attempts. The consumer groups map one-to-one with these topics so each tier has its own independent group.</p><h3>Creating the Producer</h3><p>Now that Kafka is running and our shared definitions are in place, let’s build the producer side of our pipeline. The producer is responsible for receiving an order request via a REST API and publishing that event to our Kafka broker.</p><blockquote><em>We’ll be using Sarama throughout this guide, Sarama is an MIT-licensed Go client library for Apache Kafka.</em></blockquote><h3>Connecting to Kafka</h3><p>First, we need a function that establishes a connection to our Kafka broker and returns a synchronous producer:</p><pre>func ConnectProducer(brokersUrl []string) (sarama.SyncProducer, error) {<br>	config := sarama.NewConfig()<br><br>        sarama.MaxRequestSize = 100 * 1024 * 1024<br>         sarama.MaxResponseSize = 100 * 1024 * 1024<br>         config.Producer.MaxMessageBytes = 100 * 1024 * 1024<br>         config.Producer.Return.Successes = true<br>         config.Producer.RequiredAcks = sarama.WaitForAll<br>         config.Producer.Idempotent = true<br>         config.Producer.Retry.Max = 3<br>         config.Net.MaxOpenRequests = 1<br><br>         conn, err := sarama.NewSyncProducer(brokersUrl, config)<br>         if err != nil {<br>          return nil, err<br>         }<br><br>         return conn, nil<br>}</pre><p>A few things worth noting here. RequiredAcks = sarama.WaitForAll means the producer will wait for all in-sync replicas to acknowledge the message before considering it successfully sent. We also set Idempotent = true to prevent duplicate messages in case of retries, and MaxOpenRequests = 1 is required for idempotent producers to guarantee ordering.</p><h3>Publishing Messages</h3><p>Next, our publisher function which produces a message to our broker:</p><pre>func PushOrderToQueue(producer sarama.SyncProducer, topic string, message []byte) error {<br>  msg := &amp;sarama.ProducerMessage{<br>    Topic: topic,<br>    Value: sarama.StringEncoder(message),<br>   }<br><br>   partition, offset, err := producer.SendMessage(msg)<br>   if err != nil {<br>    return err<br>   }<br><br>   fmt.Printf(&quot;Message is stored in topic(%s)/partition(%d)/offset(%d)&quot;, topic, partition, offset)<br>   return nil<br>}</pre><h3>The REST API Entry Point</h3><p>We will use a basic REST API POST request to handle incoming user requests that will then trigger our producer to publish an event to the broker:</p><pre>func main() {<br>  brokersUrl := []string{&quot;localhost:9092&quot;}<br><br> producer, err := ConnectProducer(brokersUrl)<br> if err != nil {<br>  log.Fatalf(&quot;Failed to initialize Kafka producer: %v&quot;, err)<br> }<br><br> defer producer.Close()<br><br> router := gin.Default()<br> api := router.Group(&quot;/api/v1&quot;)<br> api.POST(&quot;/order&quot;, createOrderHandler(producer))<br><br> router.Run()<br>}</pre><h3>The Order Handler</h3><p>Now our createOrderHandler, which will produce the event on success:</p><pre>type Order struct {<br>	Text string `form:&quot;text&quot; json:&quot;text&quot;`<br>}<br><br>func createOrderHandler(producer sarama.SyncProducer) gin.HandlerFunc {<br> return func(c *gin.Context) {<br>  topic := topics.ORDERS_CREATED.String()<br>  order := new(Order)<br>  if err := c.ShouldBindJSON(&amp;order); err != nil {<br>   c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()})<br>   return<br>  }<br>  orderInBytes, err := json.Marshal(order)<br>  if err != nil {<br>   c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()})<br>   return<br>  }<br>  err = PushOrderToQueue(producer, topic, orderInBytes)<br>  if err != nil {<br>   c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()})<br>   return<br>  }<br>  c.JSON(http.StatusOK, gin.H{<br>   &quot;success&quot;: true,<br>   &quot;message&quot;: &quot;Order pushed successfully&quot;,<br>   &quot;order&quot;:   order,<br>  })<br> }<br>}</pre><h3>Complete Producer Code</h3><p>Here is the full producer code with everything wired together:</p><pre>// producer/producer.go<br><br>package main<br>import (<br> &quot;encoding/json&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;github.com/IBM/sarama&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br> &quot;github.com/umohsamuel/edd-kafka-golang/pkg/topics&quot;<br>)<br>type Order struct {<br> Text string `form:&quot;text&quot; json:&quot;text&quot;`<br>}<br>func main() {<br> brokersUrl := []string{&quot;localhost:9092&quot;}<br> producer, err := ConnectProducer(brokersUrl)<br> if err != nil {<br>  log.Fatalf(&quot;Failed to initialize Kafka producer: %v&quot;, err)<br> }<br> defer producer.Close()<br> router := gin.Default()<br> api := router.Group(&quot;/api/v1&quot;)<br> api.POST(&quot;/order&quot;, createOrderHandler(producer))<br> router.Run()<br>}<br>func ConnectProducer(brokersUrl []string) (sarama.SyncProducer, error) {<br> config := sarama.NewConfig()<br> sarama.MaxRequestSize = 100 * 1024 * 1024<br> sarama.MaxResponseSize = 100 * 1024 * 1024<br> config.Producer.MaxMessageBytes = 100 * 1024 * 1024<br> config.Producer.Return.Successes = true<br> config.Producer.RequiredAcks = sarama.WaitForAll<br> config.Producer.Idempotent = true<br> config.Producer.Retry.Max = 3<br> config.Net.MaxOpenRequests = 1<br> conn, err := sarama.NewSyncProducer(brokersUrl, config)<br> if err != nil {<br>  return nil, err<br> }<br> return conn, nil<br>}<br>func PushOrderToQueue(producer sarama.SyncProducer, topic string, message []byte) error {<br> msg := &amp;sarama.ProducerMessage{<br>  Topic: topic,<br>  Value: sarama.StringEncoder(message),<br> }<br> partition, offset, err := producer.SendMessage(msg)<br> if err != nil {<br>  return err<br> }<br> fmt.Printf(&quot;Message is stored in topic(%s)/partition(%d)/offset(%d)&quot;, topic, partition, offset)<br> return nil<br>}<br>func createOrderHandler(producer sarama.SyncProducer) gin.HandlerFunc {<br> return func(c *gin.Context) {<br>  topic := topics.ORDERS_CREATED.String()<br>  order := new(Order)<br>  if err := c.ShouldBindJSON(&amp;order); err != nil {<br>   c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()})<br>   return<br>  }<br>  orderInBytes, err := json.Marshal(order)<br>  if err != nil {<br>   c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()})<br>   return<br>  }<br>  err = PushOrderToQueue(producer, topic, orderInBytes)<br>  if err != nil {<br>   c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()})<br>   return<br>  }<br>  c.JSON(http.StatusOK, gin.H{<br>   &quot;success&quot;: true,<br>   &quot;message&quot;: &quot;Order pushed successfully&quot;,<br>   &quot;order&quot;:   order,<br>  })<br> }<br>}</pre><h3>Creating the Consumer</h3><p>Now for the other side of the pipeline. The consumer listens for events on topics, processes them, and handles failures by routing messages through a tiered reprocessing system.</p><h3>Connecting Consumer Groups</h3><p>Next, let’s create our consumer group and producer connections. The consumer side also needs a producer because when a message fails processing, it needs to publish the message to the next retry topic:</p><pre>func ConnectConsumerGroup(brokersUrl []string, groupID string) (sarama.ConsumerGroup, error) {<br>	config := sarama.NewConfig()<br>  config.Consumer.Return.Errors = true<br>   config.Consumer.Offsets.AutoCommit.Enable = false<br>   config.Consumer.Offsets.Initial = sarama.OffsetOldest<br>   return sarama.NewConsumerGroup(brokersUrl, groupID, config)<br>  }<br>  func ConnectProducer(brokersUrl []string) (sarama.SyncProducer, error) {<br>   config := sarama.NewConfig()<br>   config.Producer.RequiredAcks = sarama.WaitForAll<br>   config.Producer.Return.Successes = true<br>   config.Producer.Idempotent = true<br>   config.Net.MaxOpenRequests = 1<br>   return sarama.NewSyncProducer(brokersUrl, config)<br>}</pre><p>Pay attention to config.Consumer.Offsets.AutoCommit.Enable = false. By default, Sarama will automatically commit offsets in the background on a timer, which means it could mark a message as &quot;done&quot; before your code has actually finished processing it. If your app crashes between the auto-commit and the actual processing, that message is lost. By disabling auto-commit, we take full control of when offsets get committed. This means we have to manually call session.MarkMessage and session.Commit in our handler to commit an offset.</p><h3>The Main Consumer Group Handler</h3><p>This is where the processing logic lives. When a message is consumed, we will attempt to process it. If processing fails, we route the message to the next retry tier:</p><pre>type ConsumerGroupHandler struct {<br>	producer sarama.SyncProducer<br>}<br><br>func (h *ConsumerGroupHandler) Setup(sarama.ConsumerGroupSession) error {<br> return nil<br>}<br>func (h *ConsumerGroupHandler) Cleanup(sarama.ConsumerGroupSession) error {<br> return nil<br>}<br>func (h *ConsumerGroupHandler) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {<br> for msg := range claim.Messages() {<br>  fmt.Printf(&quot;Received message: key=%s, value=%s, partition=%d, offset=%d\n&quot;, string(msg.Key), string(msg.Value), msg.Partition, msg.Offset)<br>  err := processBusinessLogic(msg.Value)<br>  if err != nil {<br>   log.Printf(&quot;Processing failed on topic %s. Routing to next stage...&quot;, msg.Topic)<br>   errRoute := h.routeToNextStage(msg)<br>   if errRoute != nil {<br>    log.Printf(&quot;CRITICAL: Failed to route message: %v&quot;, errRoute)<br>    return errRoute<br>   }<br>  }<br>  session.MarkMessage(msg, &quot;&quot;)<br>  session.Commit()<br> }<br> return nil<br>}</pre><p>Notice how after we are done with a message, whether it was processed successfully or routed to the next retry stage, we call session.MarkMessage(msg, &quot;&quot;) followed by session.Commit(). This is the manual offset commit we set up earlier when we disabled auto-commit. MarkMessage tells Sarama &quot;I am done with this message&quot; and Commit actually persists that offset to Kafka. This way, if the consumer crashes mid-processing, Kafka knows to redeliver the message because the offset was never committed.</p><h3>Routing Failed Messages</h3><p>The routeToNextStage method is the heart of our retry strategy. It reads the x-retry-count header from the message to determine how many times this message has already been retried, then routes it to the next topic accordingly. After three failed attempts, the message lands in the DLQ:</p><pre>func (h *ConsumerGroupHandler) routeToNextStage(msg *sarama.ConsumerMessage) error {<br>	retryCount := 0<br>	for _, header := range msg.Headers {<br>		if string(header.Key) == &quot;x-retry-count&quot; {<br>			retryCount, _ = strconv.Atoi(string(header.Value))<br>		}<br>	}<br><br>  var nextTopic string<br> switch retryCount {<br> case 0:<br>  nextTopic = topics.RETRY_5M.String()<br> case 1:<br>  nextTopic = topics.RETRY_20M.String()<br> case 2:<br>  nextTopic = topics.RETRY_40M.String()<br> default:<br>  nextTopic = topics.ORDERS_DLQ.String()<br> }<br> now := time.Now()<br> headers := []sarama.RecordHeader{<br>  {Key: []byte(&quot;x-retry-count&quot;), Value: []byte(strconv.Itoa(retryCount + 1))},<br>  {Key: []byte(&quot;x-failed-at&quot;), Value: []byte(now.Format(time.RFC3339))},<br>  {Key: []byte(&quot;x-original-topic&quot;), Value: []byte(msg.Topic)},<br> }<br> retryMsg := &amp;sarama.ProducerMessage{<br>  Topic:   nextTopic,<br>  Key:     sarama.ByteEncoder(msg.Key),<br>  Value:   sarama.ByteEncoder(msg.Value),<br>  Headers: headers,<br> }<br> log.Printf(&quot;Routing message to topic: %s (Attempt #%d)&quot;, nextTopic, retryCount+1)<br> _, _, err := h.producer.SendMessage(retryMsg)<br> return err<br>}</pre><p>We attach three headers to every retried message: x-retry-count so the next handler knows which attempt this is, x-failed-at so the retry handler can calculate the correct delay, and x-original-topic for traceability. The switch statement maps the retry count to the appropriate next topic, escalating through 5 minute, 20 minute, and 40 minute delays before finally landing in the DLQ.</p><h3>The Retry Consumer Group Handler</h3><p>The retry handler works similarly to the main handler, but with one key difference: it enforces a delay before reprocessing the message. It reads the x-failed-at header to determine when the message originally failed, then calculates how much time has already passed. If the message arrived before the required delay has elapsed, it sleeps for the remaining duration. If processing fails again, it escalates to the next retry tier:</p><pre>type RetryConsumerGroupHandler struct {<br>	producer      sarama.SyncProducer<br>	delayDuration time.Duration<br>}<br><br>func (h *RetryConsumerGroupHandler) Setup(sarama.ConsumerGroupSession) error   { return nil }<br>func (h *RetryConsumerGroupHandler) Cleanup(sarama.ConsumerGroupSession) error { return nil }<br>func (h *RetryConsumerGroupHandler) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {<br> for msg := range claim.Messages() {<br>  var failedAt time.Time<br>  for _, header := range msg.Headers {<br>   if string(header.Key) == &quot;x-failed-at&quot; {<br>    failedAt, _ = time.Parse(time.RFC3339, string(header.Value))<br>   }<br>  }<br>  timeElapsed := time.Since(failedAt)<br>  if timeElapsed &lt; h.delayDuration {<br>   remainingDelay := h.delayDuration - timeElapsed<br>   log.Printf(&quot;[%s] Message arrived early. Sleeping for %v...&quot;, msg.Topic, remainingDelay)<br>   time.Sleep(remainingDelay)<br>  }<br>  err := processBusinessLogic(msg.Value)<br>  if err != nil {<br>   log.Printf(&quot;[%s] Retry failed. Escalating to next tier.&quot;, msg.Topic)<br>   mainHandler := &amp;ConsumerGroupHandler{producer: h.producer}<br>   errRoute := mainHandler.routeToNextStage(msg)<br>   if errRoute != nil {<br>    return errRoute<br>   }<br>  }<br>  session.MarkMessage(msg, &quot;&quot;)<br>  session.Commit()<br> }<br> return nil<br>}</pre><h3>Simulating Business Logic</h3><p>For testing purposes, here is a dummy function that simulates our business logic. You can toggle between returning nil (success) and returning an error (failure) to test both paths:</p><pre>func processBusinessLogic(data []byte) error {<br>	// return nil<br>	return fmt.Errorf(&quot;forced simulation error&quot;)<br>}</pre><h3>Complete Consumer Code</h3><p>Here is the full consumer code with everything connected together. We create a shared producer (for routing failed messages), spin up consumer groups for the main topic and each retry tier, and run them all concurrently in separate goroutines:</p><pre>// consumer/consumer.go<br><br>package main<br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;os&quot;<br> &quot;os/signal&quot;<br> &quot;strconv&quot;<br> &quot;syscall&quot;<br> &quot;time&quot;<br> &quot;github.com/IBM/sarama&quot;<br> &quot;github.com/umohsamuel/edd-kafka-golang/pkg/topics&quot;<br>)<br>func main() {<br> brokersUrl := []string{&quot;localhost:9092&quot;}<br> sharedProducer, err := ConnectProducer(brokersUrl)<br> if err != nil {<br>  log.Fatalf(&quot;Failed to start DLQ Producer: %v&quot;, err)<br> }<br> defer sharedProducer.Close()<br> mainGroup, err := ConnectConsumerGroup(brokersUrl, topics.ORDERS_MAIN_GROUP.String())<br> if err != nil {<br>  log.Fatalf(&quot;Failed to start Main Consumer Group: %v&quot;, err)<br> }<br> defer mainGroup.Close()<br> retryGroup5m, err := ConnectConsumerGroup(brokersUrl, topics.ORDERS_5M_RETRY_GROUP.String())<br> if err != nil {<br>  log.Fatalf(&quot;Failed to start 5m Retry Group: %v&quot;, err)<br> }<br> defer retryGroup5m.Close()<br> retryGroup20m, err := ConnectConsumerGroup(brokersUrl, topics.ORDERS_20M_RETRY_GROUP.String())<br> if err != nil {<br>  log.Fatalf(&quot;Failed to start 20m Retry Group: %v&quot;, err)<br> }<br> defer retryGroup20m.Close()<br> retryGroup40m, err := ConnectConsumerGroup(brokersUrl, topics.ORDERS_40M_RETRY_GROUP.String())<br> if err != nil {<br>  log.Fatalf(&quot;Failed to start 40m Retry Group: %v&quot;, err)<br> }<br> defer retryGroup40m.Close()<br> ctx, cancel := context.WithCancel(context.Background())<br> sigchan := make(chan os.Signal, 1)<br> signal.Notify(sigchan, syscall.SIGINT, syscall.SIGTERM)<br> fmt.Println(&quot;Consumers have entered the fray...&quot;)<br> go func() {<br>  handler := &amp;ConsumerGroupHandler{<br>   producer: sharedProducer,<br>  }<br>  for {<br>   if err := mainGroup.Consume(ctx, []string{topics.ORDERS_CREATED.String()}, handler); err != nil {<br>    log.Printf(&quot;Error from main consumer group: %v&quot;, err)<br>   }<br>   if ctx.Err() != nil {<br>    return<br>   }<br>  }<br> }()<br> go func() {<br>  handler := &amp;RetryConsumerGroupHandler{<br>   producer:      sharedProducer,<br>   delayDuration: 5 * time.Minute,<br>  }<br>  for {<br>   if err := retryGroup5m.Consume(ctx, []string{topics.RETRY_5M.String()}, handler); err != nil {<br>    log.Printf(&quot;Error from %s group: %v&quot;, topics.RETRY_5M.String(), err)<br>   }<br>   if ctx.Err() != nil {<br>    return<br>   }<br>  }<br> }()<br> go func() {<br>  handler := &amp;RetryConsumerGroupHandler{<br>   producer:      sharedProducer,<br>   delayDuration: 20 * time.Minute,<br>  }<br>  for {<br>   if err := retryGroup20m.Consume(ctx, []string{topics.RETRY_20M.String()}, handler); err != nil {<br>    log.Printf(&quot;Error from %s group: %v&quot;, topics.RETRY_20M.String(), err)<br>   }<br>   if ctx.Err() != nil {<br>    return<br>   }<br>  }<br> }()<br> go func() {<br>  handler := &amp;RetryConsumerGroupHandler{<br>   producer:      sharedProducer,<br>   delayDuration: 40 * time.Minute,<br>  }<br>  for {<br>   if err := retryGroup40m.Consume(ctx, []string{topics.RETRY_40M.String()}, handler); err != nil {<br>    log.Printf(&quot;Error from %s group: %v&quot;, topics.RETRY_40M.String(), err)<br>   }<br>   if ctx.Err() != nil {<br>    return<br>   }<br>  }<br> }()<br> &lt;-sigchan<br> fmt.Println(&quot;Interruption detected, shutting down all groups gracefully...&quot;)<br> cancel()<br>}<br>func ConnectConsumerGroup(brokersUrl []string, groupID string) (sarama.ConsumerGroup, error) {<br> config := sarama.NewConfig()<br> config.Consumer.Return.Errors = true<br> config.Consumer.Offsets.AutoCommit.Enable = false<br> config.Consumer.Offsets.Initial = sarama.OffsetOldest<br> return sarama.NewConsumerGroup(brokersUrl, groupID, config)<br>}<br>func ConnectProducer(brokersUrl []string) (sarama.SyncProducer, error) {<br> config := sarama.NewConfig()<br> config.Producer.RequiredAcks = sarama.WaitForAll<br> config.Producer.Return.Successes = true<br> config.Producer.Idempotent = true<br> config.Net.MaxOpenRequests = 1<br> return sarama.NewSyncProducer(brokersUrl, config)<br>}<br>func processBusinessLogic(data []byte) error {<br> // return nil<br> return fmt.Errorf(&quot;forced simulation error&quot;)<br>}<br>type ConsumerGroupHandler struct {<br> producer sarama.SyncProducer<br>}<br>func (h *ConsumerGroupHandler) Setup(sarama.ConsumerGroupSession) error {<br> return nil<br>}<br>func (h *ConsumerGroupHandler) Cleanup(sarama.ConsumerGroupSession) error {<br> return nil<br>}<br>func (h *ConsumerGroupHandler) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {<br> for msg := range claim.Messages() {<br>  fmt.Printf(&quot;Received message: key=%s, value=%s, partition=%d, offset=%d\n&quot;, string(msg.Key), string(msg.Value), msg.Partition, msg.Offset)<br>  err := processBusinessLogic(msg.Value)<br>  if err != nil {<br>   log.Printf(&quot;Processing failed on topic %s. Routing to next stage...&quot;, msg.Topic)<br>   errRoute := h.routeToNextStage(msg)<br>   if errRoute != nil {<br>    log.Printf(&quot;CRITICAL: Failed to route message: %v&quot;, errRoute)<br>    return errRoute<br>   }<br>  }<br>  session.MarkMessage(msg, &quot;&quot;)<br>  session.Commit()<br> }<br> return nil<br>}<br>func (h *ConsumerGroupHandler) routeToNextStage(msg *sarama.ConsumerMessage) error {<br> retryCount := 0<br> for _, header := range msg.Headers {<br>  if string(header.Key) == &quot;x-retry-count&quot; {<br>   retryCount, _ = strconv.Atoi(string(header.Value))<br>  }<br> }<br> var nextTopic string<br> switch retryCount {<br> case 0:<br>  nextTopic = topics.RETRY_5M.String()<br> case 1:<br>  nextTopic = topics.RETRY_20M.String()<br> case 2:<br>  nextTopic = topics.RETRY_40M.String()<br> default:<br>  nextTopic = topics.ORDERS_DLQ.String()<br> }<br> now := time.Now()<br> headers := []sarama.RecordHeader{<br>  {Key: []byte(&quot;x-retry-count&quot;), Value: []byte(strconv.Itoa(retryCount + 1))},<br>  {Key: []byte(&quot;x-failed-at&quot;), Value: []byte(now.Format(time.RFC3339))},<br>  {Key: []byte(&quot;x-original-topic&quot;), Value: []byte(msg.Topic)},<br> }<br> retryMsg := &amp;sarama.ProducerMessage{<br>  Topic:   nextTopic,<br>  Key:     sarama.ByteEncoder(msg.Key),<br>  Value:   sarama.ByteEncoder(msg.Value),<br>  Headers: headers,<br> }<br> log.Printf(&quot;Routing message to topic: %s (Attempt #%d)&quot;, nextTopic, retryCount+1)<br> _, _, err := h.producer.SendMessage(retryMsg)<br> return err<br>}<br>type RetryConsumerGroupHandler struct {<br> producer      sarama.SyncProducer<br> delayDuration time.Duration<br>}<br>func (h *RetryConsumerGroupHandler) Setup(sarama.ConsumerGroupSession) error   { return nil }<br>func (h *RetryConsumerGroupHandler) Cleanup(sarama.ConsumerGroupSession) error { return nil }<br>func (h *RetryConsumerGroupHandler) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {<br> for msg := range claim.Messages() {<br>  var failedAt time.Time<br>  for _, header := range msg.Headers {<br>   if string(header.Key) == &quot;x-failed-at&quot; {<br>    failedAt, _ = time.Parse(time.RFC3339, string(header.Value))<br>   }<br>  }<br>  timeElapsed := time.Since(failedAt)<br>  if timeElapsed &lt; h.delayDuration {<br>   remainingDelay := h.delayDuration - timeElapsed<br>   log.Printf(&quot;[%s] Message arrived early. Sleeping for %v...&quot;, msg.Topic, remainingDelay)<br>   time.Sleep(remainingDelay)<br>  }<br>  err := processBusinessLogic(msg.Value)<br>  if err != nil {<br>   log.Printf(&quot;[%s] Retry failed. Escalating to next tier.&quot;, msg.Topic)<br>   mainHandler := &amp;ConsumerGroupHandler{producer: h.producer}<br>   errRoute := mainHandler.routeToNextStage(msg)<br>   if errRoute != nil {<br>    return errRoute<br>   }<br>  }<br>  session.MarkMessage(msg, &quot;&quot;)<br>  session.Commit()<br> }<br> return nil<br>}</pre><h3>Running the Application</h3><p>To run the application, first start the Docker Compose cluster (if you already did this earlier, you can skip it), then run the producer and consumer in separate terminals:</p><pre>docker compose up -d</pre><pre>cd producer &amp;&amp; go run .</pre><pre>cd consumer &amp;&amp; go run .</pre><h3>Testing with cURL</h3><p>You can test the pipeline by sending a POST request to the producer’s API:</p><pre>curl -X POST http://localhost:8080/api/v1/order \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;text&quot;: &quot;New order from Lagos&quot;}&#39;</pre><p>To see the full retry flow in action, keep the processBusinessLogic function returning the dummy error. Send a request and watch the consumer logs as the message fails, gets routed to the 5 minute retry topic, fails again, moves to the 20 minute retry, then the 40 minute retry, and finally lands in the DLQ.</p><p>Once you have confirmed that flow, change processBusinessLogic to return nil, restart the consumer service, and send another request to confirm the success path works cleanly, with the message being marked and committed on the first pass.</p><p>Lastly, while the consumer service is running, try hitting Ctrl+C as well. You should see each consumer group shut down gracefully in turn, without dropping any in-flight messages.</p><h3>Demo</h3><p>Here is a demo of how all these concepts come together:</p><p><a href="https://res.cloudinary.com/db6nohcui/video/upload/v1786899332/c79e8f83-1540-4b9b-8262-d7b6798bea5a_edd-golang-kafka_tnlpk0.mp4">https://res.cloudinary.com/db6nohcui/video/upload/v1786899332/c79e8f83-1540-4b9b-8262-d7b6798bea5a_edd-golang-kafka_tnlpk0.mp4</a></p><h3>Conclusion</h3><p>In this guide, we built a fault-tolerant event-driven pipeline using Apache Kafka and Go. The key takeaways are:</p><ol><li><strong>Event-Driven Architecture</strong> decouples your services, letting producers and consumers operate independently through a message broker.</li><li><strong>Tiered retry topics &amp; reprocessing</strong> with increasing delays (5m, 20m, 40m) give transient failures time to resolve before reprocessing, instead of hammering the same operation repeatedly.</li><li><strong>Dead letter queues</strong> catch messages that have exhausted all retry attempts, so they can be inspected and handled manually without blocking the pipeline.</li><li><strong>Consumer groups</strong> let you scale consumption horizontally while Kafka handles partition assignment and offset tracking.</li></ol><p>These patterns apply to any Go service that needs reliable, asynchronous message processing, whether you are processing orders, sending notifications, or syncing data between services.</p><p>(If you want to see the full codebase, checkout the <a href="https://github.com/umohsamuel/edd-kafka-golang">repository</a>. Play around with it and lmk what you think)</p><h3>References</h3><ul><li><a href="https://www.uber.com/us/en/blog/reliable-reprocessing/">Uber Engineering: Reliable Reprocessing</a></li><li><a href="https://developer.confluent.io/confluent-tutorials/kafka-on-docker/">Confluent: Kafka on Docker</a></li><li><a href="https://www.tencentcloud.com/document/product/597/60360">Tencent Cloud: Kafka Dead Letter Queue</a></li><li><a href="https://www.confluent.io/learn/kafka-dead-letter-queue/#overview">Confluent: Kafka Dead Letter Queue Overview</a></li><li><a href="https://www.ibm.com/think/topics/apache-kafka">IBM: Apache Kafka</a></li><li><a href="https://www.ibm.com/think/topics/event-driven-architecture">IBM: Event-Driven Architecture</a></li><li><a href="https://kafka.apache.org/43/getting-started/introduction/">Apache Kafka: Getting Started</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea84634222d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Horizontally Scaling PostgreSQL: Database Sharding with Citus]]></title>
            <link>https://medium.com/@umohsg/horizontally-scaling-postgresql-database-sharding-with-citus-6059da19ea81?source=rss-98d0e0748007------2</link>
            <guid isPermaLink="false">https://medium.com/p/6059da19ea81</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[database-sharding]]></category>
            <dc:creator><![CDATA[Samuel Umoh ]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 12:36:53 GMT</pubDate>
            <atom:updated>2026-07-21T12:36:53.467Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>A practical guide to scaling your database infrastructure horizontally. Learn how to shard your data, optimize query routing, and build a distributed multi-tenant architecture using Postgres, Citus and Docker.</em></blockquote><h3>Prerequisites</h3><p>What do you need to follow along?</p><ol><li>A working Laptop/PC?</li><li>Working knowledge of SQL or PostgreSQL.</li></ol><p>Database sharding is a strategy used to solve scalability issues in applications that have a massive amount of data. It involves splitting data into smaller chunks called shards. Each shard is stored on a separate database server instance, effectively spreading the data and the workload across multiple machines.</p><h3>Why Shard Data?</h3><p>As an application grows, the number of users and the amount of data it stores increase over time. At a certain limit, a single database server will become a bottleneck. The application slows down and affects the user experience.</p><p>Instead of upgrading a single server with more CPU or RAM, which will eventually hit a hardware ceiling, sharding lets you add more servers to your cluster. This allows applications to handle nearly infinite growth in data volume and user traffic.</p><h3>Understanding Shards and Shard Keys</h3><p>Before we start sharding data, let’s first understand what shards and shard keys are.</p><h3>Shards</h3><p>The partitioned data chunks are called logical shards. The machine that stores the logical shard is called a physical shard or database node. A physical shard can contain multiple logical shards.</p><h3>Shard Key</h3><p>A shard key is used to determine how to partition the dataset. A shard key is a specific column in your dataset that determines which rows of data group together to form a shard.</p><h3>Sharding Methods</h3><p>There are a few ways to shard data depending on the application requirements.</p><ol><li><strong>Key-based sharding (hash sharding)</strong>: Hash sharding uses a mathematical formula called a hash function. The hash function takes your shard key and generates a hash value, this hash value determines the exact physical shard where the row will be stored.</li><li><strong>Range-based sharding</strong>: Range-based sharding, or dynamic sharding, splits database rows based on a range of values. Then the database designer assigns a shard key to the respective range.</li><li><strong>Directory-based sharding</strong>: Directory sharding uses a lookup table to match database information to the corresponding physical shard. A lookup table is like a table on a spreadsheet that links a database column to a shard key.</li><li><strong>Geo sharding</strong>: Geo sharding splits and stores database information according to geographical location.</li></ol><p>For this guide, we are focusing exclusively on <strong>Hash Sharding</strong>. This is the industry standard for multi-tenant applications like the e-commerce platform we will be building in this tutorial.</p><h3>Choosing Your Shard Key</h3><p>If you pick the wrong shard key, your database will still crash under load. When choosing a shard key, you must ensure the data is distributed evenly across your nodes:</p><ol><li><strong>Cardinality</strong>: This refers to the number of unique values a key can have. You want a key with high cardinality like a User ID, not low cardinality like a Gender or State column, so the data can be split into many small, even chunks.</li><li><strong>Frequency</strong>: You must avoid keys where one specific value appears too often. For example, if you shard by a City column and 80% of your users live in Ikeja, the Ikeja node will be overloaded while the others sit idle.</li><li><strong>Monotonic change</strong>: This is the rate of change of the shard key. A monotonically increasing or decreasing shard key results in unbalanced shards. For example, consider a feedback database that is split into three different physical shards as follows:</li></ol><ul><li>Shard A stores feedback from customers who have made 0 to 10 purchases.</li><li>Shard B stores feedback from customers who have made 11 to 20 purchases.</li><li>Shard C stores feedback from customers who have made 21 or more purchases. As the business grows, customers will make 21 or more purchases. The application stores their feedback in Shard C. This results in an unbalanced shard because Shard C contains more feedback records than the other shards.</li></ul><h3>Is Sharding Actually For You?</h3><p>While sharding solves massive scale requirements, it introduces significant technical and operational tradeoffs. You should not shard your database unless a single, heavily provisioned Postgres instance can no longer handle your traffic.</p><p>If you do decide to shard your database, here are some of the biggest challenges you will face:</p><ol><li><strong>Data hotspots</strong>: Even with a good hash function, uneven traffic can create hotspots where one server becomes overloaded by a small group of highly active users.</li><li><strong>Performance regression</strong>: Queries that do not use the shard key require the system to scatter and gather across every server. Cross-shard joins are computationally expensive because the application must pull and merge data from multiple physical locations over the network.</li><li><strong>Operational complexity</strong>: Managing a sharded environment increases the difficulty of routine tasks. Schema updates, backups, and point-in-time recovery must be coordinated across multiple independent instances.</li></ol><h3>How Can We Shard Our Postgres Database: Introducing Citus</h3><p>Citus is an open-source extension that transforms standard PostgreSQL into a distributed database. Instead of being limited to a single server, Citus allows your database to scale horizontally across multiple machines.</p><h3>How Citus Works</h3><ol><li><strong>The Coordinator Node</strong>: When you ask your database a question, you talk to the coordinator. The coordinator directs your request to the right servers, gathers the answers, and combines them for your application.</li><li><strong>Worker Nodes</strong>: Citus breaks down large tables into smaller, manageable chunks (shards) and spreads them across these worker servers. They do the heavy lifting of storing the data and running the queries.</li></ol><h3>Start Early, Scale Later</h3><p>Migrating a traditional, monolithic PostgreSQL database to a distributed, sharded database later in its life is incredibly difficult. You have to change your schema, rewrite complex queries, and alter how your application connects to the database.</p><p>To avoid this nightmare, you can start using Citus on a single node from day one. You design your tables with distribution keys immediately, and your application code is written to query a distributed database from the start.</p><p><strong>The Transition</strong>: When your data outgrows that single machine, you won’t have to rewrite your application. You simply spin up new worker machines, and Citus moves the existing shards over to the new hardware in the background while the application keeps running.</p><h3>Running Citus Locally</h3><p>We will use Docker to run Citus locally. Why use Docker instead of adding the extension directly to your host machine’s Postgres installation?</p><p>Simulating a distributed database means running multiple Postgres instances simultaneously. Doing this natively forces you to manually manage conflicting ports and multiple data directories. Docker Compose solves this by orchestrating the entire cluster’s networking with a single command, giving you a clean state that can be torn down and rebuilt in seconds.</p><h3>Single Node vs Multi-Node Setup</h3><p>While it is possible to run a single node Citus instance using a simple docker run command:</p><pre>docker run -d --name citus_standalone -p 5432:5432 -e POSTGRES_PASSWORD=postgres citusdata/citus:14.1.0</pre><p>This guide will focus exclusively on setting up a <strong>Multi-Node Cluster</strong>. If you are interested in exploring the single node setup further, you can <a href="https://learn.microsoft.com/en-us/postgresql/citus/single-node-docker?view=citus-14">check out the official Citus documentation here</a>.</p><p>For our distributed, multi-node cluster, we will use the following Docker Compose configuration:</p><pre>services:<br>  master:<br>    container_name: &quot;${PROJECT_NAME:-citus}_master&quot;<br>    image: &quot;citusdata/citus:14.1.0&quot;<br>    ports: [&quot;${COORDINATOR_EXTERNAL_PORT:-5433}:5432&quot;]<br>    labels: [&quot;com.citusdata.role=Master&quot;]<br>    environment: &amp;AUTH<br>      POSTGRES_USER: &quot;${POSTGRES_USER:-postgres}&quot;<br>      POSTGRES_PASSWORD: &quot;${POSTGRES_PASSWORD}&quot;<br>      PGUSER: &quot;${POSTGRES_USER:-postgres}&quot;<br>      PGPASSWORD: &quot;${POSTGRES_PASSWORD}&quot;<br>      POSTGRES_HOST_AUTH_METHOD: &quot;${POSTGRES_HOST_AUTH_METHOD:-trust}&quot;<br>  worker:<br>    image: &quot;citusdata/citus:14.1.0&quot;<br>    labels: [&quot;com.citusdata.role=Worker&quot;]<br>    environment: *AUTH</pre><p>Citus has a built-in initialization script in its official Docker image. When launched via Docker Compose with these specific labels like com.citusdata.role, the coordinator automatically detects and registers the workers for you.</p><p>We can build and start the cluster in the background with:</p><pre>docker compose up -d</pre><p>We can also scale up dynamically. If you want to spin up a second or third worker machine on the fly, you do not even need to edit the compose file. Just run:</p><pre>docker compose up -d --scale worker=3</pre><p>Where 3 is the total number of workers you want to have running.</p><p>Simply spinning up the worker containers is not enough. After adding new worker nodes, we must register them with the coordinator so Citus knows they are active and ready to hold data. To do this, we will first connect to the interactive Postgres terminal on the master node:</p><pre>docker compose exec master psql -U postgres</pre><p>Now we can register our workers:</p><pre>SELECT citus_add_node(&#39;db-sharding-worker-1&#39;, 5432);<br>SELECT citus_add_node(&#39;db-sharding-worker-2&#39;, 5432);<br>SELECT citus_add_node(&#39;db-sharding-worker-3&#39;, 5432);</pre><p>So, if you scale up again to say 5 workers, you will have to run this command 2 more times to register the 2 new workers.</p><p>Notice the db-sharding- prefix in the hostnames. This is necessary because Docker Compose prefixes your project folder name to the container&#39;s network alias.</p><h3>A Real World Scenario</h3><p>In order to showcase the functionality of this database sharding setup, let’s try to work with a real world scenario.</p><p>Consider an e-commerce multi-tenant application. It serves multiple independent companies that all share the same database infrastructure. To scale this effectively, we need to use a hash-based distribution with a well-chosen shard key. Let’s assume by design, every tenant has a shared company_id, we will use that as our shard key.</p><p>By using company_id as the shard key across all operational tables, Citus guarantees that all data belonging to a specific company (like its users, its products, and its orders) is physically co-located on the exact same worker node.</p><p>Now that our workers are registered, we can create our core tables directly in the master node. Citus will automatically handle the underlying sharding for us.</p><p>Please note that the following schema is highly simplified to focus on the core concepts of sharding.</p><p>Run the following SQL commands in your coordinator’s postgres interactive terminal:</p><pre>-- 1. Create Tenant Table<br>CREATE TABLE companies (<br>    company_id INT PRIMARY KEY,<br>    company_name TEXT NOT NULL<br>);<br><br>-- 2. Create Tenant-Scoped Orders Table<br>CREATE TABLE orders (<br>    company_id INT NOT NULL,<br>    order_id INT NOT NULL,<br>    user_id INT NOT NULL,<br>    status_id INT NOT NULL, -- References our global order status table<br>    order_amount NUMERIC(10,2) NOT NULL,<br>    PRIMARY KEY (company_id, order_id)<br>);<br><br>-- 3. Create Global Order Reference Table<br>CREATE TABLE order_statuses (<br>    status_id INT PRIMARY KEY,<br>    status_name TEXT NOT NULL<br>);<br><br>-- 4. Create Tenant-Scoped Users Table<br>CREATE TABLE users (<br>    company_id INT NOT NULL,<br>    user_id INT NOT NULL,<br>    username TEXT NOT NULL,<br>    PRIMARY KEY (company_id, user_id)<br>);<br><br>-- 5. Create Tenant-Scoped Products Table<br>CREATE TABLE products (<br>    company_id INT NOT NULL,<br>    product_id INT NOT NULL,<br>    product_name TEXT NOT NULL,<br>    price NUMERIC(10,2) NOT NULL,<br>    PRIMARY KEY (company_id, product_id)<br>);</pre><h3>Telling Citus How to Shard and Replicate</h3><p>Now that we have created our core tables, we have to tell Citus how to shard and replicate them across our worker nodes.</p><h3>Reference Tables</h3><p>First, we will set order_statuses as a reference table. We do this using create_reference_table.</p><p>Why do we create a reference table? A reference table is designed for relatively small, slowly-changing data like user roles, country codes, or order statuses.</p><p>When you mark a table as a reference table, Citus physically replicates a full copy of that entire table to every single worker node. This bypasses network overhead completely during JOIN operations. Because the worker node already has the data locally, it does not need to fetch it from another node to complete a query.</p><h3>Distributed Tables</h3><p>Next, we need to distribute our large tenant-data tables. We do this using create_distributed_table.</p><p>This function is the core of Citus’s sharding mechanism. It tells the coordinator to partition the table based on a specific column (our shard key, company_id), and spread those partitions across the available worker nodes.</p><p>Because we use company_id across all these tables, any query filtering by a specific company will be routed directly to a single node, making it incredibly fast.</p><pre>-- Replicate order_statuses to ALL nodes<br>SELECT create_reference_table(&#39;order_statuses&#39;);<br><br>-- Shard data based on the Hash of company_id<br>SELECT create_distributed_table(&#39;companies&#39;, &#39;company_id&#39;);<br>SELECT create_distributed_table(&#39;users&#39;, &#39;company_id&#39;);<br>SELECT create_distributed_table(&#39;products&#39;, &#39;company_id&#39;);<br>SELECT create_distributed_table(&#39;orders&#39;, &#39;company_id&#39;);</pre><h3>Multi-Tenant Seed Data</h3><p>Now we will populate our cluster with some dummy companies along with some global order status entries, orders, and tenant users.</p><pre>-- Global Order Lookups<br>INSERT INTO order_statuses VALUES (1, &#39;Pending&#39;), (2, &#39;Shipped&#39;), (3, &#39;Delivered&#39;);<br><br>-- Company Tenants<br>INSERT INTO companies VALUES (1, &#39;EbaMart&#39;), (2, &#39;FufuHub&#39;), (3, &#39;GymGear&#39;);<br><br>-- Multi-Tenant Users scattered across companies<br>INSERT INTO users (company_id, user_id, username) VALUES<br>(1, 101, &#39;Samuel&#39;),   -- EbaMart Customer<br>(2, 201, &#39;Folashade&#39;),-- FufuHub Customer<br>(1, 102, &#39;Umoh&#39;),     -- EbaMart Customer<br>(3, 301, &#39;Oladejo&#39;),  -- GymGear Customer<br>(2, 202, &#39;BigSam&#39;);   -- FufuHub Customer<br><br>-- Orders<br>INSERT INTO orders (company_id, order_id, user_id, status_id, order_amount) VALUES<br>(1, 5001, 101, 1, 150.00),  -- EbaMart order: Pending<br>(1, 5002, 102, 3, 45.00),   -- EbaMart order: Delivered<br>(2, 6001, 201, 2, 99.00),   -- FufuHub order: Shipped<br>(2, 6002, 202, 1, 250.00);  -- FufuHub order: Pending</pre><h3>Verify Layout and Node Placement</h3><p>We can now verify the layout and node placement to see where they are added to and display it by running:</p><pre>SELECT<br>    u.company_id,<br>    u.user_id,<br>    u.username,<br>    s.shardid,<br>    s.nodename<br>FROM users u<br>JOIN citus_shards s<br>  ON s.shardid = get_shard_id_for_distribution_column(&#39;users&#39;, u.company_id)<br>ORDER BY u.company_id;</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*QlITGbrsHtfXfyMwU16M_w.png" /></figure><p>As you can see, all data for company_id = 1 sits neatly on db-sharding-worker-2, while company_id = 2 sits on db-sharding-worker-1. This guarantees that queries for a single tenant will only hit one node.</p><p>We can also inspect the query plan for joining distributed tables with reference tables:</p><pre>EXPLAIN (VERBOSE, COSTS OFF)<br>SELECT o.order_id, o.order_amount, s.status_name<br>FROM orders o<br>JOIN order_statuses s ON o.status_id = s.status_id<br>WHERE o.company_id = 1;</pre><p><strong>Output:</strong></p><pre>QUERY PLAN<br>---------------------------------------------------------------------<br>---------------------------------------------------------------------<br>---------------------------------------------------------------------<br>------------------------<br> Custom Scan (Citus Adaptive)<br>   Output: remote_scan.order_id, remote_scan.order_amount, remote_scan.status_name<br>   Task Count: 1<br>   Tasks Shown: All<br>   -&gt;  Task<br>         Query: SELECT o.order_id, o.order_amount, s.status_name FROM (public.orders_102106 o JOIN public.order_statuses_102008 s ON ((o.status_id OPERATOR(pg_catalog.=) s.status_id))) WHERE (o.company_id OPERATOR(pg_catalog.=) 1)<br>         Node: host=db-sharding-worker-2 port=5432 dbname=postgres<br>         -&gt;  Hash Join<br>               Output: o.order_id, o.order_amount, s.status_name<br>               Hash Cond: (s.status_id = o.status_id)<br>               -&gt;  Seq Scan on public.order_statuses_102008 s<br>                     Output: s.status_id, s.status_name<br>               -&gt;  Hash<br>                     Output: o.order_id, o.order_amount, o.status_id<br>                     -&gt;  Bitmap Heap Scan on public.orders_102106 o<br>                           Output: o.order_id, o.order_amount, o.status_id<br>                           Recheck Cond: (o.company_id = 1)<br>                           -&gt;  Bitmap Index Scan on orders_pkey_102106<br>                                 Index Cond: (o.company_id = 1)<br>(19 rows)</pre><p>The query plan shows a Custom Scan (Citus Adaptive) delegating the query to the specific worker node holding company_id = 1.</p><p>We can check the active worker nodes with:</p><pre>SELECT * FROM master_get_active_worker_nodes();</pre><p><strong>Output:</strong></p><p>node_namenode_portdb-sharding-worker-35432db-sharding-worker-15432db-sharding-worker-25432</p><h3>Rebalancing the Cluster</h3><p>Anytime you dynamically scale the cluster and register a new worker node, you must run the Citus Shard Rebalancer:</p><pre>SELECT citus_rebalance_start();</pre><p>When new nodes are added, the coordinator does not automatically move existing data onto them. We have to explicitly balance the load. The rebalancer handles this by dynamically moving a subset of your tenants’ data over to the new worker servers in the background, without taking the database offline.</p><h3>Production Setup</h3><p>The Docker Compose setup is perfect for local testing and development. However, running a distributed database in production across multiple physical servers or virtual machines requires a slightly different approach.</p><p>We must first change how network addressing and orchestration work. In a local setup, Docker Compose handles networking automatically because everything shares a single machine loopback. On production VMs, each container must be bound to the public or private IP address of its physical host machine, and you must enforce strict firewall security.</p><h3>1. Spin up your VMs</h3><p>Spin up your virtual machines on your preferred cloud provider. Assuming we provision 4 VMs, our network layout will look something like this:</p><ul><li><strong>VM 1 (Coordinator Node)</strong>: Private IP 10.0.0.10</li><li><strong>VM 2 (Worker Node 1)</strong>: Private IP 10.0.0.11</li><li><strong>VM 3 (Worker Node 2)</strong>: Private IP 10.0.0.12</li><li><strong>VM 4 (Worker Node 3)</strong>: Private IP 10.0.0.13</li></ul><p>I used random private IPs, but you should substitute them with your real VMs’ private IPs.</p><h3>2. Install Docker</h3><p>Next, you will need to install Docker and Docker Compose on every VM. The installation commands will depend on your specific Linux distribution, so refer to the official Docker documentation for your OS.</p><p>You will no longer use a single master compose file for the cluster. Instead, you deploy an isolated, optimized compose layout directly on each corresponding VM instance.</p><h3>3. The Coordinator Instance (VM 1)</h3><p>Create a docker-compose.yml file specifically tailored to map the Postgres engine port directly out to the host VM network interface:</p><pre>services:<br>  master:<br>    container_name: &quot;citus_coordinator&quot;<br>    image: &quot;citusdata/citus:14.1.0&quot;<br>    ports:<br>      - &quot;5432:5432&quot;<br>    restart: always<br>    environment:<br>      POSTGRES_USER: &quot;citus_admin&quot;<br>      POSTGRES_PASSWORD: &quot;YOUR_SUPER_SECURE_PRODUCTION_PASSWORD&quot;<br>      PGUSER: &quot;citus_admin&quot;<br>      PGPASSWORD: &quot;YOUR_SUPER_SECURE_PRODUCTION_PASSWORD&quot;<br>      POSTGRES_HOST_AUTH_METHOD: &quot;scram-sha-256&quot;<br>    volumes:<br>      - coordinator_data:/var/lib/postgresql/data<br>    volumes:<br>      coordinator_data:</pre><h3>4. The Worker Instances (VMs 2, 3, and 4)</h3><p>Every worker VM gets its own standalone compose file. Notice we expose port 5432 on the workers too, because the coordinator node needs a direct network pipe to talk to them:</p><pre>services:<br>  worker:<br>    container_name: &quot;citus_worker&quot;<br>    image: &quot;citusdata/citus:14.1.0&quot;<br>    ports:<br>      - &quot;5432:5432&quot;<br>    restart: always<br>    environment:<br>      POSTGRES_USER: &quot;citus_admin&quot;<br>      POSTGRES_PASSWORD: &quot;YOUR_SUPER_SECURE_PRODUCTION_PASSWORD&quot;<br>      PGUSER: &quot;citus_admin&quot;<br>      PGPASSWORD: &quot;YOUR_SUPER_SECURE_PRODUCTION_PASSWORD&quot;<br>      POSTGRES_HOST_AUTH_METHOD: &quot;scram-sha-256&quot;<br>    volumes:<br>      - worker_data:/var/lib/postgresql/data<br>    volumes:<br>      worker_data:</pre><h3>5. Configure Network Firewall Security</h3><p>Since you are running across independent cloud instances, your cloud platform’s Security Groups or Firewalls (like AWS Security Groups or ufw on Ubuntu) must be strictly configured to prevent public database scanning.</p><ul><li><strong>On the Coordinator VM (VM 1)</strong>: Allow inbound TCP traffic on port 5432 from Anywhere (0.0.0.0/0) only if your external application servers need public access. If your application servers are in the same VPC, restrict inbound port 5432 access exclusively to your app servers’ IP subnet range.</li><li><strong>On the Worker VMs (VMs 2, 3, 4)</strong>: Allow inbound TCP traffic on port 5432 EXCLUSIVELY from the Coordinator’s Private IP (10.0.0.10). Block all other inbound network requests to the workers. They should never be exposed to the internet.</li></ul><p>Next, log in to each VM and run the containers:</p><pre>docker compose up -d</pre><p>Once all containers are healthy, access the interactive postgres interface on VM 1 (the coordinator node):</p><pre>docker compose exec master psql -U citus_admin</pre><p>Register your external worker instances using their physical Private VPC IP addresses:</p><pre>SELECT citus_add_node(&#39;10.0.0.11&#39;, 5432); -- Register Worker VM 2<br>SELECT citus_add_node(&#39;10.0.0.12&#39;, 5432); -- Register Worker VM 3<br>SELECT citus_add_node(&#39;10.0.0.13&#39;, 5432); -- Register Worker VM 4</pre><p>Verify everything works:</p><pre>SELECT * FROM master_get_active_worker_nodes();</pre><h3>6. Configure Production Password Authentication</h3><p>Because we updated POSTGRES_HOST_AUTH_METHOD to scram-sha-256 for security, your instances will require passwords to authenticate cross-node.</p><p>We must add a Postgres password passfile on the coordinator container:</p><pre>docker compose exec master bash -c &quot;echo &#39;*:*:*:citus_admin:YOUR_SUPER_SECURE_PRODUCTION_PASSWORD&#39; &gt;&gt; /var/lib/postgresql/.pgpass &amp;&amp; chmod 600 /var/lib/postgresql/.pgpass&quot;</pre><p>Surely you will know to replace YOUR_SUPER_SECURE_PRODUCTION_PASSWORD with your actual password.</p><p>Here is a detailed documentation of Citus multi-node installation and setup for reference: <a href="https://learn.microsoft.com/en-us/postgresql/citus/multi-node-ubuntu-debian?view=citus-14">Citus Multi-Node Setup</a>.</p><h3>Adding Citus to an Existing Project</h3><p>To add Citus to an already existing Postgres database project, the process follows these general steps:</p><ol><li><strong>Install the Extension</strong>: Install the Citus extension on your Postgres server. You will also need to add citus to the shared_preload_libraries in your postgresql.conf file and restart the database.</li><li><strong>Create the Extension</strong>: Run CREATE EXTENSION citus; in your database.</li><li><strong>Select a Shard Key</strong>: Identify the column that will serve as the shard key for your distributed tables, such as a company or tenant ID.</li><li><strong>Convert Tables</strong>: Use create_distributed_table() to convert your existing tables into distributed tables. Use create_reference_table() for lookup tables that do not need to be sharded.</li><li><strong>Migrate Data</strong>: If you already have data in the tables, it might need to be exported and loaded back in, depending on the volume of data and the specific requirements of the migration.</li></ol><h3>Conclusion</h3><p>Database sharding is an incredibly powerful architectural pattern, but it comes with immense operational tradeoffs. By using tools like Citus, we can bridge the gap between standard relational SQL databases and massively distributed systems.</p><p>Whether you are starting a new multi-tenant application or scaling out an existing infrastructure, adopting a distributed mindset and orchestrating your local environments with tools like Citus and Docker Compose will save you countless hours of architectural nightmares down the road.</p><p><strong>You can find the full Docker Compose source code for this tutorial on GitHub:</strong> <a href="https://github.com/umohsamuel/database-sharding">umohsamuel/database-sharding</a>.</p><h3>References</h3><ul><li><a href="https://cloud.google.com/discover/what-is-database-sharding">What is Database Sharding? (Google Cloud)</a></li><li><a href="https://aws.amazon.com/what-is/database-sharding/">What is Database Sharding? (AWS)</a></li><li><a href="https://github.com/citusdata/docker/blob/master/docker-compose.yml">Citus Docker Compose Setup</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6059da19ea81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graceful Shutdown in Golang]]></title>
            <link>https://medium.com/@umohsg/graceful-shutdown-in-golang-2b784c67174f?source=rss-98d0e0748007------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b784c67174f</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Samuel Umoh ]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 23:07:01 GMT</pubDate>
            <atom:updated>2026-07-09T23:07:01.678Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>A practical guide to implementing graceful shutdown for Go HTTP servers. Learn what signals are, how Go handles termination under the hood, and how to properly shut down your server without dropping requests or corrupting data.</em></blockquote><h3>What is a Graceful Shutdown?</h3><p>A graceful shutdown is the process where a system, service, or application is stopped in a managed and controlled manner, allowing it to finish processing active requests or jobs and close network connections properly.</p><p>Unlike a forceful shutdown, which can interrupt running tasks and cause data loss, a graceful shutdown ensures that all ongoing processes are completed before terminating the service.</p><h3>Why We Need It</h3><ol><li><strong>Prevents Data Loss and Corruption</strong>: If you cut the power or force-close an app while a process is writing to disk or performing some db operation, you can corrupt your file systems or leave incomplete data. A graceful shutdown gives the app time to finish writing and flush buffers.</li><li><strong>Avoids Dropped User Requests</strong>: In web servers, dropping a process instantly severs active connections. A graceful shutdown allows the Go server to stop accepting new requests while it completes in-flight ones.</li><li><strong>Seamless Deployments &amp; Scaling</strong>: In cloud environments, when using Docker or Kubernetes, instances are constantly spun up and down during rolling updates. Graceful shutdowns ensure instances properly terminate, avoiding downtime and user-facing errors.</li></ol><h3>Prerequisites</h3><p>What do you need to follow this article?</p><ol><li>Working knowledge of Golang.</li><li>Knowledge of HTTP.</li></ol><h3>Understanding Signals</h3><p>Before we can implement graceful shutdown, we need to understand how the operating system actually tells your application to stop. It does this through signals.</p><p>A signal is a standardized asynchronous notification sent to a running process to inform it that an important event has occurred. These events can originate from the user (like pressing Ctrl+C), from the operating system, or even from other programs. When a signal is delivered, the OS interrupts the normal flow of the process to handle it.</p><h3>How a Process Responds to Signals</h3><p>When a process receives a signal, one of three things happens:</p><ul><li><strong>Signal handler</strong>: The process can register a custom handler (a function) for a specific signal. When that signal comes in, the handler runs instead of the default behavior.</li><li><strong>Default action</strong>: If no custom handler is registered, the process follows the default behavior for that signal. Depending on the signal, this might mean terminating, stopping, continuing, or ignoring the process.</li><li><strong>Unblockable signals</strong>: Some signals, like SIGKILL, cannot be caught or ignored. They will always terminate the process, no matter what.</li></ul><h3>Common Signals</h3><p>Here are the signals you will encounter most often:</p><ul><li><strong>SIGINT</strong> (Signal Interrupt): Sent when the user presses Ctrl+C in the terminal.</li><li><strong>SIGTERM</strong> (Signal Terminate): A polite request for a process to terminate. This is what Kubernetes sends to your pod during shutdown.</li><li><strong>SIGKILL</strong>: A forceful termination signal that cannot be caught or ignored.</li><li><strong>SIGSEGV</strong> (Segmentation Violation): Sent when a program attempts to access memory that doesn’t belong to it.</li><li><strong>SIGSTOP and SIGCONT</strong>: Used to pause and resume process execution.</li><li><strong>SIGQUIT</strong>: Quit signal (such as Ctrl+D).</li></ul><p>For our graceful shutdown, we mostly care about <strong>SIGTERM</strong> and <strong>SIGINT</strong>. SIGTERM is what orchestrators like Kubernetes send when they want your app to stop, and SIGINT is what you get when you press Ctrl+C in the terminal of your running server.</p><h3>How Go Handles Termination</h3><p>Now that we understand signals, let’s look at what Go actually does when your app receives one.</p><p>When your Go app gets a SIGTERM, the runtime first catches it using a built-in handler. It checks if a custom handler has been registered. If not, the runtime disables its own handler temporarily and sends the same signal (SIGTERM) to the application again. This time, the OS handles it using the default behavior, which is to terminate the process and clean up any remaining resources.</p><p>The important thing to note here is that Go gives us the ability to intercept these signals before the default behavior kicks in. We can override the signal handling by registering our own handler using the os/signal package. This is exactly how we will implement our graceful shutdown.</p><h3>Option 1: Using Channels</h3><p>The first approach is to use a channel that receives signals:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;os&quot;<br> &quot;os/signal&quot;<br> &quot;syscall&quot;<br>)<br><br>func main() {<br> signalChan := make(chan os.Signal, 1)<br><br> signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)<br> // normal cooking here (server setup, etc...)<br> <br>&lt;-signalChan<br> fmt.Println(&quot;Received, shutting down...&quot;)<br>}</pre><p>We use a buffered channel with a capacity of 1 here to prevent blocking. signal.Notify tells Go to relay SIGINT and SIGTERM to our channel instead of using the default behavior. The &lt;-signalChan line blocks until a signal is received.</p><h3>Option 2: Using Context (the Preferred Approach)</h3><p>Starting with Go 1.16, you can simplify signal handling by using signal.NotifyContext, which ties signal handling directly to context cancellation:</p><pre>ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)<br>defer stop()</pre><p>NotifyContext returns a copy of the parent context that automatically cancels itself whenever one of the specified signals is received. This is the preferred approach because contexts are already deeply integrated into Go&#39;s standard library, and it lets us propagate the shutdown signal to all parts of our application naturally.</p><h3>Building the Graceful Shutdown</h3><p>Now that we have found a way to intercept shutdown signals, let’s build the actual implementation. There are a few things we need to handle before we can wire it together.</p><h3>Don’t Drop Traffic During the Transition</h3><p>This is something a lot of people miss. In a containerized environment (and many other orchestrated environments with external load balancers), you should not stop accepting new requests immediately. Even after a container is marked for shutdown or a pod is marked for termination, it might still receive traffic for a few moments before the load balancer pings again to know that it is inactive.</p><p>To avoid connection errors during this short window, the correct approach is to fail the health check first. This tells the load balancer to stop sending you traffic:</p><pre>var isShuttingDown atomic.Bool<br><br>http.HandleFunc(&quot;/health&quot;, func(w http.ResponseWriter, r *http.Request) {<br>    if isShuttingDown.Load() {<br>        http.Error(w, &quot;Shutting down&quot;, http.StatusServiceUnavailable)<br>        return<br>    }<br>    w.WriteHeader(http.StatusOK)<br>    w.Write([]byte(&quot;OK&quot;))<br>})</pre><p>After updating our availability status, we wait a small interval for the next health check ping from the load balancer. This gives it time to notice we are no longer healthy and stop routing new requests to us.</p><h3>Shutting Down the Server and Notifying Handlers</h3><p>Once the load balancer knows to leave us alone, we can actually shut down the server. With net/http, we do this by calling http.Server.Shutdown. This method stops the server from accepting new connections and waits for all active requests to complete before shutting down.</p><p>It returns in only two situations:</p><ol><li><strong>Good case</strong>: All active connections are closed and all handlers have finished processing.</li><li><strong>“Oof”(Bad) case</strong>: The context passed to Shutdown(ctx) expires before the handlers finish. In this case, the server gives up waiting and returns an error.</li></ol><p>But there is a problem. Handlers are not automatically aware when the server is shutting down. If a handler is doing a long-running operation (like a big database query or a slow external API call), it has no way of knowing it should wrap things up.</p><p>We can solve this by setting the server’s BaseContext field. BaseContext lets us provide a custom context that gets shared across all incoming connections. If we make that context cancellable, we can cancel it during shutdown, and every handler will be able to detect that it&#39;s time to stop:</p><pre>outgoingContext, stopOutgoingContext := context.WithCancel(context.Background())<br>server := &amp;http.Server{<br>    Addr: &quot;:8080&quot;,<br>    BaseContext: func(_ net.Listener) context.Context {<br>        return outgoingContext<br>    },<br>}</pre><p>Here, outgoingContext is our cancellable context, and we wire it into the server through BaseContext. Now every handler can check r.Context().Done() to see if the server is shutting down, and exit early if needed.</p><h3>The Full Implementation</h3><p>Here is the full implementation with all the pieces connected:</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;log&quot;<br> &quot;net&quot;<br> &quot;net/http&quot;<br> &quot;os/signal&quot;<br> &quot;sync/atomic&quot;<br> &quot;syscall&quot;<br> &quot;time&quot;<br>)<br><br>var isShuttingDown atomic.Bool<br><br>func main() {<br> signalContext, stopSignalContext := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)<br> defer stopSignalContext()<br><br> http.HandleFunc(&quot;/health&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  if isShuttingDown.Load() {<br>   http.Error(w, &quot;Shutting down&quot;, http.StatusServiceUnavailable)<br>   return<br>  }<br><br>  w.WriteHeader(http.StatusOK)<br>  w.Write([]byte(&quot;OK&quot;))<br> })<br><br> http.HandleFunc(&quot;/&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  select {<br><br>  case &lt;-time.After(2 * time.Second):<br>   w.WriteHeader(http.StatusOK)<br>   w.Write([]byte(&quot;Aktiv!&quot;))<br><br>  case &lt;-r.Context().Done():<br>   http.Error(w, &quot;Request cancelled.&quot;, http.StatusRequestTimeout)<br>  }<br> })<br><br> outgoingContext, stopOutgoingContext := context.WithCancel(context.Background())<br> server := &amp;http.Server{<br>  Addr: &quot;:8080&quot;,<br>  BaseContext: func(_ net.Listener) context.Context {<br>   return outgoingContext<br>  },<br> }<br><br> go func() {<br>  log.Println(&quot;Server running on http://localhost:8080&quot;)<br>  if err := server.ListenAndServe(); err != nil &amp;&amp; err != http.ErrServerClosed {<br>   panic(err)<br>  }<br> }()<br><br> &lt;-signalContext.Done()<br><br> stopSignalContext()<br> isShuttingDown.Store(true)<br><br> log.Println(&quot;shutdown signal received, shutting down...&quot;)<br> time.Sleep(5 * time.Second)<br> log.Println(&quot;Health check propagated, waiting for ongoing requests to finish.&quot;)<br><br> shutdownContext, cancelShutdownContext := context.WithTimeout(context.Background(), 15*time.Second)<br> defer cancelShutdownContext()<br> err := server.Shutdown(shutdownContext)<br> if err != nil {<br>  log.Println(&quot;Shutdown timed out, cancelling in-flight requests.&quot;)<br>  stopOutgoingContext()<br>  time.Sleep(3 * time.Second)<br>  server.Close()<br> }<br><br> log.Println(&quot;Server shut down gracefully.&quot;)<br>}</pre><p>Let me walk through the shutdown sequence so you can see how all the pieces work together:</p><ol><li>A SIGINT or SIGTERM arrives. signalContext gets cancelled, and the &lt;-signalContext.Done() line unblocks.</li><li>We set isShuttingDown to true, so the /health endpoint starts returning 503 Service Unavailable.</li><li>We wait 5 seconds. This gives the load balancer time to notice the failed health check and stop sending us new traffic.</li><li>We call server.Shutdown() with a 15-second timeout. This stops the server from accepting new connections and waits for all in-flight requests to finish.</li><li>If requests complete within the timeout, we are done. If they don’t, we cancel outgoingContext to signal all handlers to stop, wait a bit, and then force-close the server.</li></ol><h3>A Note on time.Sleep vs time.After</h3><p>If you noticed, the root handler uses time.After inside a select instead of a plain time.Sleep. This is intentional. time.Sleep blocks the goroutine unconditionally, so it will not respond to context cancellation. That completely defeats the purpose of what we are trying to achieve with the BaseContext. The handler would just sit there sleeping even though the server is trying to shut down.</p><p>Instead, we can use a select that listens to both the timer and the context. You can use this helper function for context-aware sleeping:</p><pre>func Sleep(ctx context.Context, duration time.Duration) error {<br>    select {<br>    case &lt;-time.After(duration):<br>        return nil<br>    case &lt;-ctx.Done():<br>        return ctx.Err()<br>    }<br>}</pre><p>This way, if the context gets cancelled while we are waiting, we return immediately instead of blocking until the full duration elapses.</p><h3>Demo</h3><p>Here is a video showing the graceful shutdown in action:</p><p><a href="https://player.cloudinary.com/embed/?cloud_name=db6nohcui&amp;public_id=graceful-shutdown-demo_ypp9sd">https://player.cloudinary.com/embed/?cloud_name=db6nohcui&amp;public_id=graceful-shutdown-demo_ypp9sd</a></p><h3>Conclusion</h3><p>From the implementation above, the server shuts down gracefully, handling in-flight requests properly and releasing resources. The key takeaways are:</p><ol><li><strong>Intercept signals</strong> using signal.NotifyContext so you control what happens when your app receives a SIGTERM or SIGINT.</li><li><strong>Fail the health check first</strong> before stopping the server. This gives your load balancer time to stop routing new traffic to you.</li><li><strong>Use </strong><strong>server.Shutdown()</strong> to let in-flight requests complete before closing.</li><li><strong>Set a </strong><strong>BaseContext</strong> so your handlers can detect the shutdown and exit early if needed.</li><li><strong>Use context-aware sleep</strong> instead of time.Sleep in handlers, otherwise your graceful shutdown is not actually graceful.</li></ol><p>These patterns apply to any Go HTTP server, whether you are running on bare metal, in Docker, or on Kubernetes. The specifics of the timeouts will depend on your setup (how often your load balancer health checks, how long your longest request takes), but the structure stays the same.</p><p>(If you want to see the full codebase, check the <a href="https://github.com/umohsamuel/graceful-shutdown">repository</a>. Play around with it and lmk what you think)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b784c67174f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement Authorization with Role-Based Access Control (RBAC) in Golang]]></title>
            <link>https://medium.com/@umohsg/implement-authorization-with-role-based-access-control-rbac-in-golang-5de65e0b5235?source=rss-98d0e0748007------2</link>
            <guid isPermaLink="false">https://medium.com/p/5de65e0b5235</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[access-control]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Samuel Umoh ]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 10:52:29 GMT</pubDate>
            <atom:updated>2026-06-16T10:52:29.180Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*uoD5rFIbMbrL40l-klGrfw.jpeg" /></figure><p>This is part 2 of our authentication and authorization series. In the previous part, we implemented an authentication system from scratch in Golang with Gin and PostgreSQL. Now in this part, we will go further and see how we can implement authorization in our system.</p><h3>Prerequisites</h3><p>The requirements to follow along are:</p><ol><li>A working laptop or PC with Golang installed.</li><li>Some familiarity with Golang and SQL.</li><li>Having read the first part of this series (<a href="https://www.umohsg.com/blog/build-a-secure-authentication-system-in-golang-with-gin-jwt-and-postgres-48f2e823-f2c3-46c7-a861-ec44e806c38b">link here</a>).</li></ol><h3>What is Authorization?</h3><p>Authorization answers the second half of our dilemma. When we know who you are, surely, we should know what you’re allowed to do in our system?</p><p>Authorization determines what an authenticated identity (user, application, or service) can do and which resources it can access within a system. It ensures that every authenticated identity operates within defined boundaries. Without it, a user who logs in successfully could access all sensitive data and perform any action.</p><h3>What Does Authorization Do in Our System?</h3><p>Authorization connects three main components:</p><ol><li><strong>Users</strong> (authenticated entities)</li><li><strong>Permissions</strong> (actions they can perform)</li><li><strong>Resources</strong> (the things we’re protecting)</li></ol><h3>Common Authorization Models</h3><p>There are mainly three ways to implement authorization in a system:</p><ol><li><strong>Role-Based Access Control (RBAC)</strong> RBAC is the foundational authorization model. It simplifies permission management by assigning permissions to roles (e.g., Admin, Driver, User) and then assigning those roles to users.</li></ol><p><strong>How it works</strong>: The system checks the user’s assigned role(s) and aggregates their permissions to determine if the requested action is allowed.</p><p><strong>2. Attribute-Based Access Control (ABAC)</strong> ABAC uses dynamic policies that evaluate attributes of the user, the resource, and the environment to make an access decision.</p><p><strong>How it works</strong>: Access is determined by policy expressions that evaluate in real time (e.g., user.department == resource.department, or checking if the current time falls within business hours).</p><p><strong>3. Relationship-Based Access Control (ReBAC) and Fine-Grained Authorization (FGA)</strong> ReBAC bases authorization on the relationships and ownership between a user and a specific resource.</p><p><strong>How it works</strong>: The system checks for explicit relationships (e.g., “owner of,” “shared with,” “member of group”) to grant or deny access. Current implementations use graph-based relationship modeling to navigate complex permission chains.</p><p>In this guide, we will be focusing on implementing RBAC. It’s the most common and straightforward to implement, making it a solid starting point.</p><h3>Database Migrations for RBAC</h3><p>Now, let’s implement RBAC into our Golang authentication system.</p><p>First, we need to add some database migrations. In these migrations, we will create:</p><ul><li>A <strong>roles</strong> table to define the available roles.</li><li>A <strong>permissions</strong> table to define the available permissions.</li><li>A <strong>role_permissions</strong> table to establish the many-to-many relationship between roles and permissions.</li><li>A <strong>user_roles</strong> table to establish the many-to-many relationship between users and roles.</li></ul><p>So let’s create a new database migration:</p><pre>goose create create_authorization_tables sql</pre><p>Paste this into the generated migration file:</p><pre>-- migrations/..._create_authorization_tables.sql<br><br>-- +goose Up<br>-- role<br>CREATE TABLE roles (<br>  id SMALLSERIAL PRIMARY KEY,<br>  name VARCHAR(50) UNIQUE NOT NULL<br>);<br>INSERT INTO roles (name)<br>VALUES (&#39;super-admin&#39;),<br>  (&#39;admin&#39;),<br>  (&#39;user&#39;),<br>  (&#39;guest&#39;);<br>--permissions<br>CREATE TABLE permissions (<br>  id SMALLSERIAL PRIMARY KEY,<br>  name VARCHAR(50) UNIQUE NOT NULL<br>);<br>INSERT INTO permissions (name)<br>VALUES (&#39;create_task&#39;),<br>  (&#39;read_task&#39;),<br>  (&#39;update_task&#39;),<br>  (&#39;delete_task&#39;);<br>-- role permissions<br>CREATE TABLE role_permissions (<br>  role_id SMALLINT NOT NULL,<br>  permission_id SMALLINT NOT NULL,<br>  PRIMARY KEY (role_id, permission_id),<br>  FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE,<br>  FOREIGN KEY (permission_id) REFERENCES permissions(id) ON DELETE CASCADE<br>);<br>INSERT INTO role_permissions (role_id, permission_id)<br>SELECT r.id,<br>  p.id<br>FROM (<br>    VALUES (&#39;super-admin&#39;, &#39;create_task&#39;),<br>      (&#39;super-admin&#39;, &#39;read_task&#39;),<br>      (&#39;super-admin&#39;, &#39;update_task&#39;),<br>      (&#39;super-admin&#39;, &#39;delete_task&#39;),<br>      (&#39;admin&#39;, &#39;read_task&#39;),<br>      (&#39;admin&#39;, &#39;update_task&#39;),<br>      (&#39;admin&#39;, &#39;delete_task&#39;),<br>      (&#39;user&#39;, &#39;read_task&#39;),<br>      (&#39;user&#39;, &#39;update_task&#39;),<br>      (&#39;guest&#39;, &#39;read_task&#39;)<br>  ) AS mappings(role_name, permission_name)<br>  JOIN roles r ON r.name = mappings.role_name<br>  JOIN permissions p ON p.name = mappings.permission_name;<br>-- user roles<br>CREATE TABLE user_roles (<br>  user_id UUID NOT NULL,<br>  role_id SMALLINT NOT NULL,<br>  PRIMARY KEY (user_id, role_id),<br>  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,<br>  FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE<br>);<br>INSERT INTO user_roles (user_id, role_id)<br>SELECT u.id,<br> r.id<br>FROM users u<br> CROSS JOIN roles r<br>WHERE r.name = &#39;user&#39;<br> AND NOT EXISTS (<br>  SELECT 1<br>  FROM user_roles ur<br>  WHERE ur.user_id = u.id<br>   AND ur.role_id = r.id<br> );<br>CREATE INDEX idx_user_roles_user_id_role_id ON user_roles (user_id, role_id);<br>-- +goose Down<br>DROP TABLE IF EXISTS roles;<br>DROP TABLE IF EXISTS permissions;<br>DROP TABLE IF EXISTS role_permissions;<br>DROP TABLE IF EXISTS user_roles;<br>DROP INDEX IF EXISTS idx_user_roles_user_id_role_id;</pre><p>We also added an insert statement to set a default “user” role to any existing user who doesn’t have a role (I mean, they shouldn’t before this migration, right?). We then create an index for faster queries.</p><p>Now apply the migration:</p><pre>goose up</pre><h3>RBAC Queries</h3><p>Next, let’s write all our queries and let sqlc run its magic:</p><pre>-- queries/authorization.sql<br><br>-- name: GetRoles :many<br>SELECT *<br>FROM roles;<br>-- name: GetPermissions :many<br>SELECT *<br>FROM permissions;<br>-- name: GetEntityRoles :many<br>SELECT r.name<br>FROM user_roles ur<br> JOIN roles r ON r.id = ur.role_id<br>WHERE ur.user_id = $1;<br>-- name: GetRolePermissions :many<br>SELECT p.name<br>FROM role_permissions rp<br> JOIN permissions p ON p.id = rp.permission_id<br>WHERE rp.role_id = $1;<br>-- name: GetRolePermissionsByRoleName :many<br>SELECT p.name<br>FROM roles r<br> JOIN role_permissions rp ON rp.role_id = r.id<br> JOIN permissions p ON p.id = rp.permission_id<br>WHERE r.name = $1;<br>-- name: GetEntityRolesPermissions :many<br>SELECT DISTINCT p.name<br>FROM user_roles ur<br> JOIN role_permissions rp ON rp.role_id = ur.role_id<br> JOIN permissions p ON p.id = rp.permission_id<br>WHERE ur.user_id = $1;<br>-- name: AssignRoleToEntity :exec<br>INSERT INTO user_roles (user_id, role_id)<br>SELECT $1,<br> id<br>FROM roles<br>WHERE name = $2;<br>-- name: RevokeRoleFromEntity :exec<br>DELETE FROM user_roles<br>WHERE user_id = $1<br> AND role_id = (<br>  SELECT id<br>  FROM roles<br>  WHERE name = $2<br> );<br>-- name: RemoveAllEntityRoles :exec<br>DELETE FROM user_roles<br>WHERE user_id = $1;</pre><p>Then generate the Go code with:</p><pre>sqlc generate</pre><p>Great, we have covered most of what we need.</p><h3>Adding Roles to JWT Claims</h3><p>Next, we need to update our GenerateAccessToken function to accept roles so they can be added to the JWT claims. This way, we don&#39;t have to make a call to our database every time a user hits our RBAC middleware, as that would be very detrimental to performance.</p><h3>A Note on Alternative Approaches</h3><p>Another way we can do this is to store the user roles and permissions in Redis.</p><p>That way, we will get them from Redis and proceed accordingly. This is actually the better approach because we can invalidate permissions and it will update in real time.</p><p>Whereas with our JWT approach, if we invalidate an entity’s permissions, those permissions still live until the JWT access token expires, in our case 10–15 minutes.</p><p>Now you understand the tradeoff, but for simplicity of this guide, we will pass the roles to the JWT claims and then access them in our RBAC middleware. Everything else is the same, just the choice of where to store it.</p><h3>Updating GenerateAccessToken</h3><p>Let’s update our GenerateAccessToken function to accept and add roles to the claims:</p><pre>// pkg/util/auth.go<br><br>func GenerateAccessToken(user sqlc.User, roles []string, jwtSecret []byte, accessTokenTTL time.Duration) (string, error) {<br> expirationTime := time.Now().UTC().Add(accessTokenTTL)<br> claims := jwt.MapClaims{<br>  &quot;sub&quot;:   user.ID.String(),<br>  &quot;email&quot;: user.Email,<br>  &quot;roles&quot;: roles,<br>  &quot;exp&quot;:   expirationTime.Unix(),<br>  &quot;iat&quot;:   time.Now().UTC().Unix(),<br> }<br> token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)<br> tokenString, err := token.SignedString(jwtSecret)<br> if err != nil {<br>  return &quot;&quot;, err<br> }<br> return tokenString, nil<br>}</pre><h3>Updating the Authentication Handlers</h3><h3>Updating the SignUp Handler</h3><p>We need to update our signup handler so that when any entity signs up, we assign them a default role. Just before we send the “user created successfully” response, let’s add:</p><pre>// internal/ports/http/handlers/user/user.go<br><br>err = h.queries.AssignRoleToEntity(c, sqlc.AssignRoleToEntityParams{<br>  UserID: user.ID,<br>  Name:   &quot;user&quot;,<br> })<br> if err != nil {<br>  c.JSON(http.StatusInternalServerError, gin.H{<br>   &quot;message&quot;: err.Error(),<br>  })<br>  return<br> }</pre><h3>Updating the SignIn Handler</h3><p>Next, we’ll have to update our signin handler to get the entity roles so we can pass them to the GenerateAccessToken function we just modified:</p><pre>// internal/ports/http/handlers/user/user.go<br><br>roles, err := h.queries.GetEntityRoles(c, user.ID)<br> if err != nil {<br>  c.JSON(http.StatusInternalServerError, &quot;error&quot;)<br>  return<br> }<br> token, err := util.GenerateAccessToken(*user, roles, []byte(h.environmentVariables.Authentication.JWT_SECRET), 30*time.Minute)<br> if err != nil {<br>  c.JSON(http.StatusInternalServerError, gin.H{<br>   &quot;message&quot;: &quot;failed to generate access token&quot;,<br>  })<br>  return<br> }</pre><h3>Updating the RefreshAccessToken Handler</h3><p>We must also do the same for the RefreshAccessToken handler, as it uses the GenerateAccessToken function as well:</p><pre>// internal/ports/http/handlers/user/user.go<br><br>roles, err := h.queries.GetEntityRoles(c, user.ID)<br> if err != nil {<br>  c.JSON(http.StatusInternalServerError, &quot;error&quot;)<br>  return<br> }<br> accessToken, err := util.GenerateAccessToken(*user, roles, []byte(h.environmentVariables.Authentication.JWT_SECRET), 30*time.Minute)<br> if err != nil {<br>  c.JSON(http.StatusInternalServerError, gin.H{<br>   &quot;message&quot;: &quot;failed to generate access token&quot;,<br>  })<br>  return<br> }</pre><h3>Updating the Auth Middleware</h3><p>Now that our JWT tokens contain role claims, we need to update our AuthMiddleware to extract and set the roles from the token. We also need a new RoleMiddleware that will check if a user has the required roles before granting access to a route.</p><h3>Updated AuthMiddleware</h3><pre>// internal/ports/http/middleware/auth.go<br><br>package middleware<br><br>import (<br> &quot;net/http&quot;<br> &quot;strings&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br> &quot;github.com/google/uuid&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/pkg/env&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/pkg/util&quot;<br>)<br><br>func AuthMiddleware(environmentVariables env.EnvironmentVariables) gin.HandlerFunc {<br> return func(c *gin.Context) {<br>  authHeader := c.GetHeader(&quot;Authorization&quot;)<br><br>  if authHeader == &quot;&quot; {<br>   c.JSON(http.StatusUnauthorized, gin.H{<br>    &quot;error&quot;: &quot;Authorization header required&quot;,<br>   })<br>   c.Abort()<br>   return<br>  }<br><br>  parts := strings.Split(authHeader, &quot; &quot;)<br><br>  if len(parts) != 2 || parts[0] != &quot;Bearer&quot; {<br>   c.JSON(http.StatusUnauthorized, gin.H{<br>    &quot;error&quot;: &quot;Invalid authorization format&quot;,<br>   })<br>   c.Abort()<br>   return<br>  }<br><br>  tokenString := parts[1]<br><br>  claims, err := util.ValidateToken(tokenString, []byte(environmentVariables.Authentication.JWT_SECRET))<br>  if err != nil {<br>   c.JSON(http.StatusUnauthorized, gin.H{<br>    &quot;error&quot;: &quot;Invalid or expired token&quot;,<br>   })<br>   c.Abort()<br>   return<br>  }<br><br>  userIDStr, ok := claims[&quot;sub&quot;].(string)<br>  if !ok {<br>   c.JSON(http.StatusUnauthorized, gin.H{<br>    &quot;error&quot;: &quot;Invalid token&quot;,<br>   })<br>   c.Abort()<br>   return<br>  }<br><br>  userID, err := uuid.Parse(userIDStr)<br>  if err != nil {<br>   c.JSON(http.StatusUnauthorized, gin.H{<br>    &quot;error&quot;: &quot;Invalid token&quot;,<br>   })<br>   c.Abort()<br>   return<br>  }<br><br>  rawRoles, ok := claims[&quot;roles&quot;].([]interface{})<br>  if !ok {<br>   c.JSON(http.StatusUnauthorized, gin.H{<br>    &quot;error&quot;: &quot;Invalid token&quot;,<br>   })<br>   c.Abort()<br>   return<br>  }<br><br>  roles := make([]string, len(rawRoles))<br><br>  for i, r := range rawRoles {<br>   roles[i] = r.(string)<br>  }<br><br>  c.Set(&quot;userID&quot;, userID)<br>  c.Set(&quot;roles&quot;, roles)<br><br>  c.Next()<br> }<br>}</pre><p>So now, we also extract roles from the JWT claims (since we added them in our updated GenerateAccessToken) and we set them as well in the Gin context, easy.</p><h3>RoleMiddleware</h3><p>Since AuthMiddleware runs first and sets the user&#39;s roles in the Gin context, our RoleMiddleware can simply read them and check if the user has the required roles. Now, let&#39;s create it:</p><pre>// internal/ports/http/middleware/auth.go<br><br>func RoleMiddleware(requiredRoles []string) gin.HandlerFunc {<br> return func(c *gin.Context) {<br>  rolesValue, exists := c.Get(&quot;roles&quot;)<br>  if !exists {<br>   c.AbortWithStatus(http.StatusUnauthorized)<br>   return<br>  }<br><br>  roles := rolesValue.([]string)<br><br>  hasRole := false<br><br>  for _, r := range roles {<br>   for _, rr := range requiredRoles {<br>    if r == rr {<br>     hasRole = true<br>    }<br>   }<br>  }<br><br>  if !hasRole {<br>   c.JSON(http.StatusForbidden, gin.H{<br>    &quot;error&quot;: &quot;Forbidden&quot;,<br>   })<br>   c.Abort()<br>   return<br>  }<br><br>  c.Next()<br> }<br>}</pre><p>This middleware:</p><ol><li>Retrieves the user’s roles from the Gin context (remember we set them in the AuthMiddleware).</li><li>Loops through the user’s roles and checks if any match the required roles for the route.</li><li>If the user has at least one of the required roles, the request proceeds. Otherwise, we return a 403 Forbidden response.</li></ol><h3>Updating the API Routes</h3><p>Finally, let’s update our API routes to reflect our authorization updates:</p><pre>// cmd/api/api.go<br><br>package api<br><br>import (<br> &quot;net/http&quot;<br> &quot;time&quot;<br> &quot;github.com/gin-contrib/cors&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/internal/adapters/database/sqlc&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/internal/ports/http/handlers/user&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/internal/ports/http/middleware&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/pkg/env&quot;<br>)<br><br>type Server struct {<br> Engine  *gin.Engine<br> Env     *env.EnvironmentVariables<br> Queries *sqlc.Queries<br>}<br><br>func API(environmentVariables *env.EnvironmentVariables, queries *sqlc.Queries) *Server {<br> s := &amp;Server{<br>  Engine:  gin.Default(),<br>  Env:     environmentVariables,<br>  Queries: queries,<br> }<br><br> config := cors.DefaultConfig()<br> config.AllowAllOrigins = true<br> config.AllowMethods = []string{&quot;POST&quot;, &quot;GET&quot;, &quot;PUT&quot;, &quot;OPTIONS&quot;}<br> config.AllowHeaders = []string{&quot;Origin&quot;, &quot;Content-Type&quot;, &quot;Authorization&quot;, &quot;Accept&quot;, &quot;User-Agent&quot;, &quot;Cache-Control&quot;, &quot;Pragma&quot;}<br> config.ExposeHeaders = []string{&quot;Content-Length&quot;}<br> config.AllowCredentials = true<br> config.MaxAge = 12 * time.Hour<br><br> s.Engine.Use(cors.New(config))<br><br> s.Engine.Static(&quot;/downloads&quot;, &quot;tmp&quot;)<br><br> auth := s.Engine.Group(&quot;/auth&quot;)<br> s.Auth(auth)<br><br> v1 := s.Engine.Group(&quot;/api/v1&quot;)<br> {<br>  protected := v1.Group(&quot;&quot;)<br>  protected.Use(middleware.AuthMiddleware(*s.Env))<br><br>  {<br>   s.Health(protected)<br>   s.OnlyMinLevelAdmin(protected)<br>  }<br> }<br><br> s.Engine.Run()<br><br> return s<br>}<br><br>func (s *Server) Health(rg *gin.RouterGroup) {<br> rg.GET(&quot;/health&quot;, func(ctx *gin.Context) {<br>  ctx.JSON(http.StatusOK, gin.H{<br>   &quot;message&quot;: &quot;Server Up!&quot;,<br>  })<br> })<br>}<br><br>func (s *Server) OnlyMinLevelAdmin(rg *gin.RouterGroup) {<br> g := rg.Group(&quot;/admin&quot;)<br><br> requiredRoles := []string{&quot;super-admin&quot;, &quot;admin&quot;}<br><br> g.Use(middleware.RoleMiddleware(requiredRoles))<br><br> g.GET(&quot;/test&quot;, func(c *gin.Context) {<br>  c.JSON(200, gin.H{<br>   &quot;success&quot;: &quot;you have successfully implemented RBAC&quot;,<br>  })<br> })<br>}<br><br>func (s *Server) Auth(rg *gin.RouterGroup) {<br> userHandler := user.NewUserHandler(*s.Env, *s.Queries)<br><br> rg.POST(&quot;/signup&quot;, userHandler.SignUp)<br> rg.POST(&quot;/signin&quot;, userHandler.SignIn)<br> rg.POST(&quot;/refresh&quot;, userHandler.RefreshAccessToken)<br><br> // admin in case of revoking access token<br> rg.POST(&quot;/revoke-refresh&quot;, userHandler.RevokeRefreshAccessToken)<br>}</pre><p>I updated the route structure a little, so it’s a bit different from Part 1:</p><ul><li><strong>Public routes</strong> (/auth/*) handle signup, signin, and token management.</li><li><strong>Protected routes</strong> (/api/v1/*) use the AuthMiddleware, so you must be authenticated to access them.</li><li><strong>Admin routes</strong> (/api/v1/admin/*) add an extra layer with RoleMiddleware, so only users with the super-admin or admin role can access them.</li></ul><h3>Run the Application</h3><p>Let’s do some testing. You can run the application in your terminal with:</p><pre>go run cmd/main.go</pre><h3>Testing with cURL</h3><p>If we go to an admin-only route now as a regular user:</p><pre>export ACCESS_TOKEN=&quot;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...&quot;<br>curl -X GET http://localhost:8080/api/v1/admin/test \<br>  -H &quot;Authorization: Bearer $ACCESS_TOKEN&quot;</pre><p>You should get the response 403:</p><pre>{<br>  &quot;error&quot;: &quot;Forbidden&quot;<br>}</pre><p>You can update your user role from your database using a query tool, or update your signup AssignRoleToEntity to create an admin entity. Then try the route again, and you should get the response:</p><pre>{<br>  &quot;success&quot;: &quot;you have successfully implemented RBAC&quot;<br>}</pre><h3>Conclusion</h3><p>Congratulations, if you have made it this far, you have successfully implemented RBAC authorization. This system we built includes:</p><ol><li>Database schema for roles, permissions, and their relationships.</li><li>Many-to-many mappings between roles and permissions, and between users and roles.</li><li>Default role assignment on user signup.</li><li>Role-based middleware to protect routes based on required roles.</li><li>A structured API with separated public routes and protected routes.</li></ol><p>As usual, you can checkout the source code on Github here: <a href="https://github.com/umohsamuel/authentication-and-authorization">umohsamuel/authentication-and-authorization</a>, play around with it and lmk what you think.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5de65e0b5235" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Secure Authentication System in Golang with Gin, JWT, and Postgres]]></title>
            <link>https://medium.com/@umohsg/build-a-secure-authentication-system-in-golang-with-gin-jwt-and-postgres-9891d231132d?source=rss-98d0e0748007------2</link>
            <guid isPermaLink="false">https://medium.com/p/9891d231132d</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Samuel Umoh ]]></dc:creator>
            <pubDate>Thu, 11 Jun 2026 23:51:40 GMT</pubDate>
            <atom:updated>2026-06-11T23:51:40.768Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*q7c7wp_8V3-krefjFpYkxQ.jpeg" /></figure><p>Securing user data is a very important part of building any application. At the core of this security are two foundational concepts: authentication and authorization.</p><p>While these terms are often used interchangeably, they represent fundamentally different functions.</p><h3>What are Authentication and Authorization?</h3><p>Simply put, authentication is the process of verifying who a user is, while authorization is the process of verifying what they have access to.</p><p>Comparing these processes to a real-world example, when you go to write an external examination (say JAMB), a student presents their exam slip and ID card (authentication). Then once inside, they can only sit for the subjects they registered for and not any random exam they choose (authorization).</p><p>This simple process is the foundation for web applications; it ensures that the users are who they claim to be and also ensures they can only access what they are allowed to access.</p><p>While both are equally important, this article will focus specifically on the first step: how to build a secure authentication system in Golang using JSON Web Tokens and PostgreSQL.</p><h3>Prerequisites</h3><p>What would you need to follow along?</p><ol><li>Golang installed on your laptop or computer.</li><li>Basic familiarity with SQL and Go.</li></ol><h3>Understanding JSON Web Tokens (JWT)</h3><p>A JSON Web Token (JWT) is a compact, self-contained way to transmit information between two parties as a JSON object securely. It’s designed to ensure data integrity and authenticity without the need for server-side session management. It is secure because the token’s data is digitally signed using a shared secret (HMAC) or public/private key pair (RSA).</p><p>JWTs are essential in an authentication system because their statelessness eliminates the need for repeated database queries, thereby reducing server load and improving response times.</p><h3>JWT Structure</h3><p>A JWT consists of three parts encoded in Base64URL format and separated by dots:</p><pre>Header.Payload.Signature</pre><p>For example:</p><pre>eyJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6InVtb2hzZy5hbHRAZ2LTMzMzlhZDIzNzNjZSJ9.RVQk03jen6HzfHnjXkTiD612gMDrNtFsExWKElWElDg</pre><ol><li>The header identifies the algorithm used for signing.</li><li>The payload contains claims about the user like ID, roles, and expiration time.</li><li>The signature verifies the token hasn’t been tampered with.</li></ol><h3>The Role of JWT in Our System</h3><p>When a user interacts with our system:</p><ol><li>When the user successfully authenticates, our Go service:</li></ol><p>a. Validates the user credentials against PostgreSQL data.</p><p>b. Creates a JWT with the appropriate claims and expiration.</p><p>c. Signs the token with a secret key.</p><p>2. The client:</p><p>a. Stores the JWT (mostly in localStorage or Cookie).</p><p>b. Includes the token in the Authorization header for subsequent requests.</p><p>3. Our middleware:</p><p>a. Extracts the JWT from the request header.</p><p>b. Validates the signature using our secret key.</p><p>c. Checks that the token hasn’t expired.</p><p>d. Extracts the user identity from the claims.</p><p>e. Adds the user ID to the request context.</p><p>4. Since the token contains all the necessary user information, our server can authenticate requests without maintaining session state or making additional database queries.</p><p>The security of the JWT system depends on keeping the signing key secret and using short-lived access tokens. If a token is compromised, it’s only valid for a limited time, reducing the risk of unauthorized access.</p><h3>Project Setup and Database Migrations</h3><p>Let’s initialize a new Go application and install the necessary dependencies:</p><pre>mkdir authentication-authorization<br>cd authentication-authorization<br>go mod init github.com/you/authentication-authorization</pre><p>Now let’s install the essential packages:</p><pre>go get github.com/gin-gonic/gin # HTTP web framework and router<br>go get github.com/gin-contrib/cors # Cross-Origin Resource Sharing (CORS) middleware<br>go get github.com/jackc/pgx/v5 # PostgreSQL driver<br>go get github.com/jackc/pgx/v5/pgconn # PostgreSQL connection<br>go get github.com/jackc/pgx/v5/pgxpool # Connection pooling<br>go get github.com/golang-jwt/jwt/v5 # JWT library<br>go get golang.org/x/crypto/bcrypt # Password hashing<br>go get github.com/google/uuid # UUID generation<br>go get github.com/joho/godotenv # Load environment variables</pre><p>Next, let’s install Goose for our database migrations:</p><pre>go install github.com/pressly/goose/v3/cmd/goose@latest</pre><p>Next, let’s make a migrations folder:</p><pre>mkdir migrations</pre><p>Now, let’s create our very first migration for this project.</p><p>Create a .env file and configure it with your PostgreSQL database credentials (replace GOOSE_DBSTRING with your actual database connection url):</p><pre>export GOOSE_DRIVER=postgres<br>export GOOSE_DBSTRING=postgres://admin:admin@localhost:5432/admin_db<br>export GOOSE_MIGRATION_DIR=./migrations</pre><p>Open your terminal and run:</p><pre>goose create create_user_and_refresh_token_table sql</pre><p>Paste this into the generated migration file:</p><pre>-- migrations/..._create_user_and_refresh_token_table.sql<br><br>-- +goose Up<br>CREATE TABLE users (<br> id uuid PRIMARY KEY DEFAULT uuidv7(),<br> email VARCHAR(255) UNIQUE NOT NULL,<br> password_hash TEXT NOT NULL,<br> created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP<br>);<br>-- refresh token table<br>CREATE TABLE refresh_tokens (<br> id uuid PRIMARY KEY DEFAULT uuidv7(),<br> user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,<br> token VARCHAR(255) UNIQUE NOT NULL,<br> expires_at TIMESTAMPTZ NOT NULL,<br> created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,<br> revoked BOOLEAN NOT NULL DEFAULT FALSE<br>);<br>-- index for fast lookups<br>CREATE INDEX idx_refresh_tokens_token ON refresh_tokens(token);<br>-- +goose Down<br>DROP TABLE IF EXISTS users;<br>DROP TABLE IF EXISTS refresh_tokens;<br>DROP INDEX IF EXISTS idx_refresh_tokens_token;</pre><p>Now we can apply the migration in our terminal:</p><pre>goose up</pre><p>And if you check your PostgreSQL database, the appropriate tables and fields have been created.</p><h3>Loading Environment Variables</h3><p>Our application requires configuration such as the Port, database URL and JWT secret. Let’s create an env package to handle loading these variables using godotenv:</p><pre>// pkg/env/env.go<br><br>package env<br><br>import (<br> &quot;log&quot;<br> &quot;os&quot;<br> &quot;strconv&quot;<br>   &quot;regexp&quot;<br> &quot;github.com/joho/godotenv&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/pkg/util&quot;<br>)<br><br>type AuthenticationEV struct {<br> JWT_SECRET string<br>}<br><br>type DatabaseEV struct {<br> PG_PORT      int<br> DATABASE_URL string<br>}<br><br>type EnvironmentVariables struct {<br> Port                  string<br> ProductionEnvironment bool<br> ClientDomain          string<br> ProjectName           string<br> Authentication        AuthenticationEV<br> Database              DatabaseEV<br>}<br><br>func loadEnv() {<br> rootPath := GetRootPath()<br> err := godotenv.Load(rootPath + `/.env`)<br> if err != nil {<br>  log.Println(&quot;Warning: .env file not found, using environment variables&quot;)<br> }<br>}<br><br>func LoadEnvironmentVariables() *EnvironmentVariables {<br> loadEnv()<br><br> return &amp;EnvironmentVariables{<br>  Port:                  getEnv(&quot;PORT&quot;, &quot;:5000&quot;),<br>  ProductionEnvironment: getEnvAsBool(&quot;PRODUCTION_ENVIRONMENT&quot;, false),<br>  ClientDomain:          getEnv(&quot;CLIENT_DOMAIN&quot;, &quot;localhost&quot;),<br>  ProjectName:           getEnv(&quot;PROJECT_NAME&quot;, &quot;eba&quot;),<br>  Authentication: AuthenticationEV{<br>   JWT_SECRET: getEnvOrError(&quot;JWT_SECRET&quot;),<br>  },<br>  Database: DatabaseEV{<br>   PG_PORT:      getEnvAsInt(&quot;PG_PORT&quot;, 5433),<br>   DATABASE_URL: getEnvOrError(&quot;DATABASE_URL&quot;),<br>  },<br> }<br>}<br><br>func getEnvOrError(key string) string {<br> value, exists := os.LookupEnv(key)<br> if exists {<br>  return value<br> }<br> panic(&quot;Environment variable &quot; + key + &quot; not set&quot;)<br>}<br><br>func getEnv(key string, fallback string) string {<br> value, exists := os.LookupEnv(key)<br> if exists {<br>  return value<br> }<br> return fallback<br>}<br><br>func getEnvAsInt(key string, fallback int) int {<br> value, exist := os.LookupEnv(key)<br> if exist {<br>  valueInt, err := strconv.Atoi(value)<br>  if err != nil {<br>   log.Panicf(&quot;Environment variable \&quot;%v\&quot; not set properly&quot;, key)<br>  }<br>  return valueInt<br> }<br> return fallback<br>}<br><br>func getEnvAsBool(key string, fallback bool) bool {<br> value, exist := os.LookupEnv(key)<br> if exist {<br>  valueBool, err := strconv.ParseBool(value)<br>  if err != nil {<br>   log.Panicf(&quot;Environment variable \&quot;%v\&quot; not set properly&quot;, key)<br>  }<br>  return valueBool<br> }<br> return fallback<br>}<br><br>func GetRootPath() string {<br> projectDirName := os.Getenv(&quot;PROJECT_DIR_NAME&quot;)<br> projectName := regexp.MustCompile(`^(.*` + projectDirName + `)`)<br> currentWorkDirectory, _ := os.Getwd()<br> return string(projectName.Find([]byte(currentWorkDirectory)))<br>}</pre><p>Make sure to add the relevant environment variables to your .env file:</p><pre>JWT_SECRET=your-super-secret-jwt-key<br>DATABASE_URL=postgres://admin:admin@localhost:5432/admin_db</pre><h3>Database Connection Setup</h3><p>Let’s start with a connection to our PostgreSQL Database:</p><pre>// internal/adapters/database/connection.go<br><br>package database<br><br>import (<br> &quot;context&quot;<br> &quot;database/sql&quot;<br> &quot;log&quot;<br> &quot;os&quot;<br> &quot;time&quot;<br> &quot;github.com/jackc/pgx/v5/pgxpool&quot;<br> &quot;github.com/jackc/pgx/v5/stdlib&quot;<br>)<br><br>func NewPool() *sql.DB {<br> pool, err := pgxpool.New(context.Background(), os.Getenv(&quot;DATABASE_URL&quot;))<br> if err != nil {<br>  log.Fatalf(&quot;unable to create pg pool: %v&quot;, err)<br> }<br><br> db := stdlib.OpenDBFromPool(pool)<br> db.SetMaxIdleConns(5)<br> db.SetMaxOpenConns(25)<br> db.SetConnMaxIdleTime(1 * time.Second)<br> db.SetConnMaxLifetime(30 * time.Second)<br><br> if err := db.PingContext(context.Background()); err != nil {<br>  log.Fatalf(&quot;unable to reach database: %v&quot;, err)<br> }<br><br> log.Println(&quot;database created &amp; is reachable&quot;)<br><br> return db<br>}</pre><p>This simple function connects to our PostgreSQL database, creates a connection pool, and pings the database to verify the connection.</p><h3>Password Hashing</h3><p>Now we will create functions that will hash passwords safely during registration and verify them during login:</p><pre>// pkg/util/password.go<br><br>func HashPassword(password string) (string, error) {<br> bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)<br> return string(bytes), err<br>}<br>func CheckPasswordHash(password, hash string) bool {<br> err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))<br> return err == nil<br>}</pre><p>We use Bcrypt for password hashing because:</p><ol><li>It is slow by design, making it impractical for brute-force attacks.</li><li>It is adaptive because it has an adjustable cost factor. This makes computing the hash deliberately computationally expensive, so we can increase security as hardware gets faster.</li><li>It automatically salts passwords. This guarantees that even if two users have the exact same password, their stored hashes will look completely different.</li></ol><p>When a user signs up, we’ll hash their password before storing it. When they log in, we’ll compare their provided password against the stored hash.</p><h3>Database Models and Queries</h3><p>For our database interactions, we will use sqlc, a powerful tool that generates fully type-safe Go code directly from SQL queries.</p><p>Normally, you would configure sqlc and run its CLI to generate these files for you. However, to keep this tutorial focused strictly on the authentication logic, we&#39;ll just create the necessary files manually.</p><p>First, let’s add the foundational db.go file that sqlc uses to define the Queries struct and the database execution interface:</p><pre>// internal/adapters/database/sqlc/db.go<br><br>package sqlc<br><br>import (<br> &quot;context&quot;<br> &quot;database/sql&quot;<br>)<br><br>type DBTX interface {<br> ExecContext(context.Context, string, ...interface{}) (sql.Result, error)<br> PrepareContext(context.Context, string) (*sql.Stmt, error)<br> QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)<br> QueryRowContext(context.Context, string, ...interface{}) *sql.Row<br>}<br><br>func New(db DBTX) *Queries {<br> return &amp;Queries{db: db}<br>}<br><br>type Queries struct {<br> db DBTX<br>}<br><br>func (q *Queries) WithTx(tx *sql.Tx) *Queries {<br> return &amp;Queries{<br>  db: tx,<br> }<br>}</pre><p>Now let’s create a user model and adapter to interact with:</p><pre>// internal/adapters/database/sqlc/user.go<br><br>package sqlc<br><br>import (<br> &quot;context&quot;<br> &quot;github.com/google/uuid&quot;<br>)<br><br>type User struct {<br> ID           uuid.UUID    `json:&quot;id&quot;`<br> Email        string       `json:&quot;email&quot;`<br> PasswordHash string       `json:&quot;password_hash&quot;`<br> CreatedAt    sql.NullTime `json:&quot;created_at&quot;`<br>}<br><br>const addUser = `-- name: AddUser :one<br>INSERT INTO users (email, password_hash)<br>VALUES ($1, $2)<br>RETURNING id, email, password_hash, created_at<br>`<br><br>type AddUserParams struct {<br> Email        string `json:&quot;email&quot;`<br> PasswordHash string `json:&quot;password_hash&quot;`<br>}<br><br>func (q *Queries) AddUser(ctx context.Context, arg AddUserParams) (*User, error) {<br> row := q.db.QueryRowContext(ctx, addUser, arg.Email, arg.PasswordHash)<br><br> var i User<br><br> err := row.Scan(<br>  &amp;i.ID,<br>  &amp;i.Email,<br>  &amp;i.PasswordHash,<br>  &amp;i.CreatedAt,<br> )<br><br> return &amp;i, err<br>}<br><br>const getUser = `-- name: GetUser :one<br>SELECT id, email, password_hash, created_at<br>FROM users<br>WHERE email = $1<br>`<br><br>func (q *Queries) GetUser(ctx context.Context, email string) (*User, error) {<br> row := q.db.QueryRowContext(ctx, getUser, email)<br><br> var i User<br><br> err := row.Scan(<br>  &amp;i.ID,<br>  &amp;i.Email,<br>  &amp;i.PasswordHash,<br>  &amp;i.CreatedAt,<br> )<br><br> return &amp;i, err<br>}<br><br>const getUserByID = `-- name: GetUserByID :one<br>SELECT id, email, password_hash, created_at<br>FROM users<br>WHERE id = $1<br>`<br><br>func (q *Queries) GetUserByID(ctx context.Context, id uuid.UUID) (*User, error) {<br> row := q.db.QueryRowContext(ctx, getUserByID, id)<br><br> var i User<br><br> err := row.Scan(<br>  &amp;i.ID,<br>  &amp;i.Email,<br>  &amp;i.PasswordHash,<br>  &amp;i.CreatedAt,<br> )<br><br> return &amp;i, err<br>}<br><br>const getUsers = `-- name: GetUsers :many<br>SELECT id, email, password_hash, created_at<br>FROM users<br>`<br><br>func (q *Queries) GetUsers(ctx context.Context) ([]*User, error) {<br> rows, err := q.db.QueryContext(ctx, getUsers)<br><br> if err != nil {<br>  return nil, err<br> }<br><br> defer rows.Close()<br><br> var items []*User<br><br> for rows.Next() {<br>  var i User<br><br>  if err := rows.Scan(<br>   &amp;i.ID,<br>   &amp;i.Email,<br>   &amp;i.PasswordHash,<br>   &amp;i.CreatedAt,<br>  ); err != nil {<br>   return nil, err<br>  }<br><br>  items = append(items, &amp;i)<br> }<br><br> if err := rows.Close(); err != nil {<br>  return nil, err<br> }<br><br> if err := rows.Err(); err != nil {<br>  return nil, err<br> }<br><br> return items, nil<br>}</pre><p>This adapter provides methods to interact with a user/users. We’ll need them for our authentication logic. The User struct represents the structure of the user data stored in the database.</p><h3>JWT Generation and Validation</h3><pre>// pkg/util/auth.go<br><br>func GenerateAccessToken(user sqlc.User, jwtSecret []byte, accessTokenTTL time.Duration) (string, error) {<br> expirationTime := time.Now().UTC().Add(accessTokenTTL)<br><br> claims := jwt.MapClaims{<br>  &quot;sub&quot;:   user.ID.String(),<br>  &quot;email&quot;: user.Email,<br>  &quot;exp&quot;:   expirationTime.Unix(),<br>  &quot;iat&quot;:   time.Now().UTC().Unix(),<br> }<br><br> token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)<br><br> tokenString, err := token.SignedString(jwtSecret)<br> if err != nil {<br>  return &quot;&quot;, err<br> }<br><br> return tokenString, nil<br>}<br><br>func ValidateToken(tokenString string, jwtSecret []byte) (jwt.MapClaims, error) {<br> token, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {<br><br>  if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {<br>   return nil, errors.New(&quot;invalid token&quot;)<br>  }<br><br>  return jwtSecret, nil<br> })<br><br> if err != nil {<br>  if errors.Is(err, jwt.ErrTokenExpired) {<br>   return nil, errors.New(&quot;token expired&quot;)<br>  }<br><br>  return nil, errors.New(&quot;invalid token&quot;)<br> }<br><br> if claims, ok := token.Claims.(jwt.MapClaims); ok &amp;&amp; token.Valid {<br>  return claims, nil<br> }<br><br> return nil, errors.New(&quot;invalid token&quot;)<br>}</pre><p>Short-lived access tokens are more secure, but they require users to log in frequently.</p><p>To improve user experience while maintaining security, we can implement a refresh token system. This essentially creates a two-tier authentication system, where a long-lived refresh token is used to obtain short-lived access tokens.</p><p>The refresh token can be revoked if needed, allowing for better control over user sessions.</p><h3>Refresh Token Management</h3><pre>// internal/adapters/database/sqlc/refresh_token.go<br><br>package sqlc<br><br>import (<br> &quot;context&quot;<br> &quot;time&quot;<br> &quot;github.com/google/uuid&quot;<br>)<br><br>type RefreshToken struct {<br> ID        uuid.UUID `json:&quot;id&quot;`<br> UserID    uuid.UUID `json:&quot;user_id&quot;`<br> Token     string    `json:&quot;token&quot;`<br> ExpiresAt time.Time `json:&quot;expires_at&quot;`<br> CreatedAt time.Time `json:&quot;created_at&quot;`<br> Revoked   bool      `json:&quot;revoked&quot;`<br>}<br><br>const createRefreshToken = `-- name: CreateRefreshToken :one<br>INSERT INTO refresh_tokens (user_id, token, expires_at)<br>VALUES ($1, $2, $3)<br>RETURNING id, user_id, token, expires_at, created_at, revoked<br>`<br><br>type CreateRefreshTokenParams struct {<br> UserID    uuid.UUID `json:&quot;user_id&quot;`<br> Token     string    `json:&quot;token&quot;`<br> ExpiresAt time.Time `json:&quot;expires_at&quot;`<br>}<br><br>func (q *Queries) CreateRefreshToken(ctx context.Context, arg CreateRefreshTokenParams) (*RefreshToken, error) {<br> row := q.db.QueryRowContext(ctx, createRefreshToken, arg.UserID, arg.Token, arg.ExpiresAt)<br><br> var i RefreshToken<br><br> err := row.Scan(<br>  &amp;i.ID,<br>  &amp;i.UserID,<br>  &amp;i.Token,<br>  &amp;i.ExpiresAt,<br>  &amp;i.CreatedAt,<br>  &amp;i.Revoked,<br> )<br><br> return &amp;i, err<br>}<br><br>const getRefreshToken = `-- name: GetRefreshToken :one<br>SELECT id, user_id, token, expires_at, created_at, revoked<br>FROM refresh_tokens<br>WHERE token = $1<br>`<br><br>func (q *Queries) GetRefreshToken(ctx context.Context, token string) (*RefreshToken, error) {<br> row := q.db.QueryRowContext(ctx, getRefreshToken, token)<br><br> var i RefreshToken<br><br> err := row.Scan(<br>  &amp;i.ID,<br>  &amp;i.UserID,<br>  &amp;i.Token,<br>  &amp;i.ExpiresAt,<br>  &amp;i.CreatedAt,<br>  &amp;i.Revoked,<br> )<br><br> return &amp;i, err<br>}<br><br>const revokeRefreshToken = `-- name: RevokeRefreshToken :exec<br>UPDATE refresh_tokens<br>SET revoked = true<br>WHERE token = $1<br>`<br><br>func (q *Queries) RevokeRefreshToken(ctx context.Context, token string) error {<br> _, err := q.db.ExecContext(ctx, revokeRefreshToken, token)<br><br> return err<br>}</pre><p>The main benefits of refresh tokens are that they:</p><ol><li>Allow access tokens to be short-lived (e.g., 15 minutes), which reduces the risk if they’re leaked.</li><li>Enable longer sessions without requiring frequent logins.</li><li>Can be revoked server-side if needed, such as on logout or if a security breach is detected.</li></ol><h3>User Authentication Handlers</h3><p>Now let’s create our user authentication handler:</p><pre>// internal/ports/http/handlers/user/user.go<br><br>package user<br><br>import (<br> &quot;net/http&quot;<br> &quot;time&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br> &quot;github.com/google/uuid&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/internal/adapters/database/sqlc&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/pkg/env&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/pkg/util&quot;<br>)<br><br>type Handler struct {<br> environmentVariables env.EnvironmentVariables<br> queries              sqlc.Queries<br><br>}<br>func NewUserHandler(environmentVariables env.EnvironmentVariables, queries sqlc.Queries) *Handler {<br> return &amp;Handler{<br>  environmentVariables: environmentVariables,<br>  queries:              queries,<br> }<br>}<br><br>type SignUpRequest struct {<br> Email    string `json:&quot;email&quot;`<br> Password string `json:&quot;password&quot;`<br>}<br><br>func (h *Handler) SignUp(c *gin.Context) {<br> var signUpReq SignUpRequest<br><br> if err := c.ShouldBindJSON(&amp;signUpReq); err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{<br>   &quot;message&quot;: &quot;invalid request params&quot;,<br>  })<br><br>  return<br> }<br><br> password_hash, err := util.HashPassword(signUpReq.Password)<br> if err != nil {<br>  c.JSON(http.StatusInternalServerError, gin.H{<br>   &quot;message&quot;: &quot;&quot;,<br>  })<br><br>  return<br> }<br><br> user, err := h.queries.AddUser(c, sqlc.AddUserParams{<br>  Email:        signUpReq.Email,<br>  PasswordHash: password_hash,<br> })<br><br> if err != nil {<br>  c.JSON(http.StatusInternalServerError, gin.H{<br>   &quot;message&quot;: err.Error(),<br>  })<br><br>  return<br> }<br><br> c.JSON(http.StatusCreated, gin.H{<br>  &quot;message&quot;: &quot;user created successfully&quot;,<br>  &quot;data&quot;:    user,<br> })<br>}<br><br>type SignInRequest struct {<br> Email    string `json:&quot;email&quot;`<br> Password string `json:&quot;password&quot;`<br>}<br><br>func (h *Handler) SignIn(c *gin.Context) {<br> var signInReq SignInRequest<br><br> if err := c.ShouldBindJSON(&amp;signInReq); err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{<br>   &quot;message&quot;: &quot;invalid request params&quot;,<br>  })<br><br>  return<br> }<br><br> user, err := h.queries.GetUser(c, signInReq.Email)<br> if err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{<br>   &quot;message&quot;: &quot;user not found&quot;,<br>  })<br><br>  return<br> }<br><br> if password_match := util.CheckPasswordHash(signInReq.Password, user.PasswordHash); password_match != true {<br>  c.JSON(http.StatusBadRequest, gin.H{<br>   &quot;message&quot;: &quot;invalid details&quot;,<br>  })<br><br>  return<br> }<br><br> token, err := util.GenerateAccessToken(*user, []byte(h.environmentVariables.Authentication.JWT_SECRET), 30*time.Minute)<br> if err != nil {<br>  c.JSON(http.StatusInternalServerError, gin.H{<br>   &quot;message&quot;: &quot;failed to generate access token&quot;,<br>  })<br><br>  return<br> }<br><br> refreshToken, err := h.queries.CreateRefreshToken(c, sqlc.CreateRefreshTokenParams{<br>  UserID:    user.ID,<br>  Token:     uuid.New().String(),<br>  ExpiresAt: time.Now().UTC().Add(7 * 24 * time.Hour),<br> })<br><br> if err != nil {<br>  c.JSON(http.StatusInternalServerError, gin.H{<br>   &quot;message&quot;: &quot;failed to generate refresh token&quot;,<br>  })<br><br>  return<br> }<br><br> c.JSON(http.StatusOK, gin.H{<br>  &quot;message&quot;: &quot;login successful&quot;,<br>  &quot;data&quot;:    user,<br>  &quot;jwt&quot;: gin.H{<br>   &quot;token&quot;:         token,<br>   &quot;refresh_token&quot;: refreshToken.Token,<br>  },<br> })<br>}<br><br>type RefreshAccessTokenRequest struct {<br> RefreshToken string `json:&quot;refresh_token&quot;`<br>}<br><br>func (h *Handler) RefreshAccessToken(c *gin.Context) {<br> var refreshAccessReq RefreshAccessTokenRequest<br><br> if err := c.ShouldBind(&amp;refreshAccessReq); err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{<br>   &quot;message&quot;: &quot;invalid request params&quot;,<br>  })<br><br>  return<br> }<br><br> rt, err := h.queries.GetRefreshToken(c, refreshAccessReq.RefreshToken)<br> if err != nil {<br>  c.JSON(http.StatusUnauthorized, gin.H{<br>   &quot;message&quot;: &quot;invalid refresh token&quot;,<br>  })<br><br>  return<br> }<br><br> if rt.Revoked {<br>  c.JSON(http.StatusUnauthorized, gin.H{<br>   &quot;message&quot;: &quot;invalid refresh token&quot;,<br>  })<br><br>  return<br> }<br><br> if time.Now().UTC().After(rt.ExpiresAt) {<br>  c.JSON(http.StatusUnauthorized, gin.H{<br>   &quot;message&quot;: &quot;expired refresh token&quot;,<br>  })<br><br>  return<br> }<br><br> user, err := h.queries.GetUserByID(c, rt.UserID)<br> if err != nil {<br>  c.JSON(http.StatusUnauthorized, gin.H{<br>   &quot;message&quot;: &quot;invalid refresh token&quot;,<br>  })<br><br>  return<br> }<br><br> accessToken, err := util.GenerateAccessToken(*user, []byte(h.environmentVariables.Authentication.JWT_SECRET), 30*time.Minute)<br> if err != nil {<br>  c.JSON(http.StatusInternalServerError, gin.H{<br>   &quot;message&quot;: &quot;failed to generate access token&quot;,<br>  })<br><br>  return<br> }<br><br> c.JSON(http.StatusOK, gin.H{<br>  &quot;message&quot;: &quot;success&quot;,<br>  &quot;jwt&quot;: gin.H{<br>   &quot;token&quot;: accessToken,<br>  },<br> })<br>}<br><br>type RevokeRefreshAccessTokenRequest struct {<br> RefreshToken string `json:&quot;refresh_token&quot;`<br>}<br><br>func (h *Handler) RevokeRefreshAccessToken(c *gin.Context) {<br> var refreshAccessReq RefreshAccessTokenRequest<br><br> if err := c.ShouldBind(&amp;refreshAccessReq); err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{<br>   &quot;message&quot;: &quot;invalid request params&quot;,<br>  })<br><br>  return<br> }<br><br> err := h.queries.RevokeRefreshToken(c, refreshAccessReq.RefreshToken)<br> if err != nil {<br>  c.JSON(http.StatusUnauthorized, gin.H{<br>   &quot;message&quot;: &quot;failed to revoke refresh token&quot;,<br>  })<br><br>  return<br> }<br><br> c.JSON(http.StatusNoContent, gin.H{})<br>}</pre><p>This handler exposes endpoints for signin, signup, RefreshAccessToken, and RevokeRefreshAccessToken.</p><h3>Protecting Routes with Middleware</h3><p>Now let’s test our authentication system and create a middleware to protect routes that require authentication:</p><pre>// internal/ports/http/middleware/auth.go<br><br>package middleware<br><br>import (<br> &quot;net/http&quot;<br> &quot;strings&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br> &quot;github.com/google/uuid&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/pkg/env&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/pkg/util&quot;<br>)<br><br>func AuthMiddleware(environmentVariables env.EnvironmentVariables) gin.HandlerFunc {<br> return func(c *gin.Context) {<br><br>  authHeader := c.GetHeader(&quot;Authorization&quot;)<br><br>  if authHeader == &quot;&quot; {<br>   c.JSON(http.StatusUnauthorized, gin.H{<br>    &quot;error&quot;: &quot;Authorization header required&quot;,<br>   })<br><br>   c.Abort()<br><br>   return<br>  }<br><br>  parts := strings.Split(authHeader, &quot; &quot;)<br><br>  if len(parts) != 2 || parts[0] != &quot;Bearer&quot; {<br>   c.JSON(http.StatusUnauthorized, gin.H{<br>    &quot;error&quot;: &quot;Invalid authorization format&quot;,<br>   })<br><br>   c.Abort()<br><br>   return<br>  }<br><br>  tokenString := parts[1]<br><br>  claims, err := util.ValidateToken(tokenString, []byte(environmentVariables.Authentication.JWT_SECRET))<br>  if err != nil {<br>   c.JSON(http.StatusUnauthorized, gin.H{<br>    &quot;error&quot;: &quot;Invalid or expired token&quot;,<br>   })<br><br>   c.Abort()<br><br>   return<br>  }<br><br>  userIDStr, ok := claims[&quot;sub&quot;].(string)<br><br>  if !ok {<br>   c.JSON(http.StatusUnauthorized, gin.H{<br>    &quot;error&quot;: &quot;Invalid token claims&quot;,<br>   })<br><br>   c.Abort()<br><br>   return<br>  }<br><br>  userID, err := uuid.Parse(userIDStr)<br>  if err != nil {<br>   c.JSON(http.StatusUnauthorized, gin.H{<br>    &quot;error&quot;: &quot;Invalid user ID in token&quot;,<br>   })<br><br>   return<br>  }<br><br>  c.Set(&quot;userID&quot;, userID)<br>  c.Next()<br> }<br>}</pre><p>The middleware extracts the JWT token from the Authorization header, validates it, and adds the user ID to the request context. This allows subsequent handlers to access the authenticated user’s identity.</p><h3>Key Things the Auth Middleware Does</h3><ol><li>Extracting the JWT token from the Authorization header.</li><li>Validating the token signature and expiration.</li><li>Adding the authenticated user’s ID to the request context.</li><li>Rejecting requests with invalid or missing tokens.</li></ol><h3>Connecting the API and Main Application</h3><p>Let’s connect everything together in our API module:</p><pre>// cmd/api/api.go<br><br>package api<br><br>import (<br> &quot;net/http&quot;<br> &quot;time&quot;<br> &quot;github.com/gin-contrib/cors&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/internal/adapters/database/sqlc&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/internal/ports/http/handlers/user&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/internal/ports/http/middleware&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/pkg/env&quot;<br>)<br><br>type Server struct {<br> Engine  *gin.Engine<br> Env     *env.EnvironmentVariables<br> Queries *sqlc.Queries<br>}<br><br>func API(environmentVariables *env.EnvironmentVariables, queries *sqlc.Queries) *Server {<br> s := &amp;Server{<br>  Engine:  gin.Default(),<br>  Env:     environmentVariables,<br>  Queries: queries,<br><br> }<br> config := cors.DefaultConfig()<br> config.AllowAllOrigins = true<br> config.AllowMethods = []string{&quot;POST&quot;, &quot;GET&quot;, &quot;PUT&quot;, &quot;OPTIONS&quot;}<br> config.AllowHeaders = []string{&quot;Origin&quot;, &quot;Content-Type&quot;, &quot;Authorization&quot;, &quot;Accept&quot;, &quot;User-Agent&quot;, &quot;Cache-Control&quot;, &quot;Pragma&quot;}<br> config.ExposeHeaders = []string{&quot;Content-Length&quot;}<br> config.AllowCredentials = true<br> config.MaxAge = 12 * time.Hour<br> s.Engine.Use(cors.New(config))<br><br> s.Engine.Static(&quot;/downloads&quot;, &quot;tmp&quot;)<br><br> s.Health()<br> s.User()<br><br> s.Engine.Run()<br><br> return s<br>}<br><br>func (s *Server) Health() {<br> s.Engine.GET(&quot;/health&quot;, middleware.AuthMiddleware(*s.Env), func(ctx *gin.Context) {<br>  ctx.JSON(http.StatusOK, gin.H{<br>   &quot;message&quot;: &quot;Server Up!&quot;,<br>  })<br> })<br>}<br><br>func (s *Server) User() {<br> userHandler := user.NewUserHandler(*s.Env, *s.Queries)<br><br> rg := s.Engine.Group(&quot;/user&quot;)<br><br> rg.POST(&quot;/signup&quot;, userHandler.SignUp)<br> rg.POST(&quot;/signin&quot;, userHandler.SignIn)<br> rg.POST(&quot;/refresh&quot;, userHandler.RefreshAccessToken)<br><br> // admin in case of revoking access token<br> rg.POST(&quot;/revoke-refresh&quot;, userHandler.RevokeRefreshAccessToken)<br>}</pre><p>Now let’s connect everything to our main application:</p><pre>// cmd/main.go<br><br>package main<br><br>import (<br> &quot;github.com/umohsamuel/authentication-authorization/cmd/api&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/internal/adapters/database&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/internal/adapters/database/sqlc&quot;<br> &quot;github.com/umohsamuel/authentication-authorization/pkg/env&quot;<br>)<br><br>var (<br> environmentVariables = env.LoadEnvironmentVariables()<br>)<br><br>func main() {<br> db := database.NewPool()<br><br> queries := sqlc.New(db)<br><br> api.API(environmentVariables, queries)<br>}</pre><h3>Run the Application</h3><p>We can run the application by running:</p><pre>go run cmd/main.go</pre><p>You should see among the output, first:</p><pre>2026/06/11 16:14:11 database created &amp; is reachable</pre><p>Then lastly:</p><pre>[GIN-debug] Listening and serving HTTP on :8080</pre><h3>Testing with cURL</h3><pre>curl -X POST http://localhost:8080/user/signup \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;email&quot;: &quot;umohsg.alt@gmail.com&quot;,<br>    &quot;password&quot;: &quot;SecureP@ssw0rd!&quot;<br>  }&#39;</pre><p>We should get the response:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;id&quot;: &quot;019eb743-87a6-701b-861a-3339ad2373ce&quot;,<br>    &quot;email&quot;: &quot;umohsg.alt@gmail.com&quot;,<br>    &quot;password_hash&quot;: &quot;$2a$14$vE3/zq1/WzK3z.uSH4v.9ebvyJfPmAyBZNCLy1Pyr4.ezaX/Zq23q&quot;,<br>    &quot;created_at&quot;: {<br>      &quot;Time&quot;: &quot;2026-06-11T16:18:36.709895+01:00&quot;,<br>      &quot;Valid&quot;: true<br>    }<br>  },<br>  &quot;message&quot;: &quot;user created successfully&quot;<br>}</pre><p>Next, let’s log in with the newly created user:</p><pre>curl -X POST http://localhost:8080/user/signin \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;email&quot;: &quot;umohsg.alt@gmail.com&quot;,<br>    &quot;password&quot;: &quot;SecureP@ssw0rd!&quot;<br>  }&#39;</pre><p>We should get the response:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;id&quot;: &quot;019eb743-87a6-701b-861a-3339ad2373ce&quot;,<br>    &quot;email&quot;: &quot;umohsg.alt@gmail.com&quot;,<br>    &quot;password_hash&quot;: &quot;$2a$14$vE3/zq1/WzK3z.uSH4v.9ebvyJfPmAyBZNCLy1Pyr4.ezaX/Zq23q&quot;,<br>    &quot;created_at&quot;: {<br>      &quot;Time&quot;: &quot;2026-06-11T16:18:36.709895+01:00&quot;,<br>      &quot;Valid&quot;: true<br>    }<br>  },<br>  &quot;jwt&quot;: {<br>    &quot;refresh_token&quot;: &quot;1fe63ff8-30c8-4666-a53d-951401f71216&quot;,<br>    &quot;token&quot;: &quot;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InVtb2hzZy5hbHRAZ21haWwuY29tIiwiZXhwIjoxNzgxMTkzMDAzLCJpYXQiOjE3ODExOTEyMDMsInN1YiI6IjAxOWViNzQzLTg3YTYtNzAxYi04NjFhLTMzMzlhZDIzNzNjZSJ9.RVQk03jen6HzfHnjXkTiD612gMDrNtFsExWKElWElDg&quot;<br>  },<br>  &quot;message&quot;: &quot;login successful&quot;<br>}</pre><p>Save the access_token and refresh_token from the response for the next steps.</p><p>Now let’s use the access token to access a protected route:</p><pre>export ACCESS_TOKEN=&quot;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...&quot;<br>curl -X GET http://localhost:8080/health \<br>  -H &quot;Authorization: Bearer $ACCESS_TOKEN&quot;</pre><p>You should get the response:</p><pre>{<br>  &quot;message&quot;: &quot;Server Up!&quot;<br>}</pre><p>When your access token expires, refresh it using the refresh token you received during login:</p><pre>export REFRESH_TOKEN=&quot;c3d4e5f6-7890-....&quot;<br>curl -X POST http://localhost:8080/user/refresh \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;refresh_token&quot;: &quot;&#39;$REFRESH_TOKEN&#39;&quot;<br>  }&#39;</pre><p>You should get the response:</p><pre>{<br>  &quot;jwt&quot;: {<br>    &quot;token&quot;: &quot;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InVtb2hzZy5hbHRAZ21haWwuY29tIiwiZXhwIjoxNzgxMTkzMjc0LCJpYXQiOjE3ODExOTE0NzQsInN1YiI6IjAxOWViNzQzLTg3YTYtNzAxYi04NjFhLTMzMzlhZDIzNzNjZSJ9.L6dGe2NbRof2Pjks-83xXZWeFPsqy3Dp06TO2FwNd5Y&quot;<br>  },<br>  &quot;message&quot;: &quot;success&quot;<br>}</pre><p>You can also test an invalid token to see the authentication fail:</p><pre>curl -X GET http://localhost:8080/api/profile \<br>  -H &quot;Authorization: Bearer invalid-token&quot;</pre><p>Then lastly, for whatever suspicious reason, you can revoke a user’s refresh token:</p><pre>export REFRESH_TOKEN=&quot;c3d4e5f6-7890-....&quot;<br>curl -X POST http://localhost:8080/user/revoke-refresh \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;refresh_token&quot;: &quot;&#39;$REFRESH_TOKEN&#39;&quot;<br>  }&#39;</pre><p>And you should get a 204 No Content response.</p><h3>Conclusion</h3><p>In this article, we built a secure authentication system in Go, using JWT and PostgreSQL. The system includes secure password hashing, token-based authentication, refresh token support, middleware-protected routes, and bcrypt hashing to prevent brute-force attacks, amongst others. Security headers and best practices were used to protect us against common web vulnerabilities.</p><p>You can checkout the source code on Github here: <a href="https://github.com/umohsamuel/authentication-and-authorization">umohsamuel/authentication-and-authorization</a>, play around with it and let me know what you think.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9891d231132d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>