This resume is also available in English.

4. Reliability7 / 7 · All columns

Columns › 4. Reliability › Part 20

Event-Driven Go with Watermill: What It Is, What It Solves, and Wiring It to an Outbox

用 Watermill 寫 Go 事件驅動:它是什麼、解決什麼問題、怎麼接上 Outbox

Write event consumers by hand and every service re-implements acks, retries, poison messages, timeouts, panics, shutdown, the outbox relay and tests. This article explains what Watermill is and when it fits, rewrites the inventory consumer with its Router and middleware, replaces the hand-written relay with the SQL outbox and forwarder, and tests it all with an in-memory Pub/Sub.

  • Go
  • Watermill
  • Event-Driven
  • NATS
In this article
  1. What this article solves
  2. Step 1: What you end up writing by hand
  3. Step 2: What Watermill is
  4. Step 3: Events and the envelope
  5. Step 4: Connecting to NATS JetStream
  6. Step 5: Router and middleware: the inventory consumer
  7. Step 6: Inbox dedupe, and “out of stock” isn’t an error
  8. Step 7: Replacing the hand-written relay with the SQL outbox and forwarder
  9. Step 8: Wiring it up in main, with graceful shutdown
  10. Step 9: Testing with an in-memory Pub/Sub
  11. Step 10: Observability and operations
  12. Common pitfalls
  13. Key takeaways
  14. References
  15. Next

The last two articles laid the groundwork for event-driven design: “Message Queues and Event-Driven Design” covered events, acknowledgements, retries, dead-letter queues and idempotent consumers, and the previous one, “Distributed Transactions: Sagas and the Outbox Pattern”, used a transactional outbox to make data and events succeed together, with a hand-written relay and inbox. This article hands that “write it again in every service” infrastructure to Watermill, a library widely used in the Go community: first what it is, what it solves and when you don’t need it, then the shop’s order and inventory services rewritten with it.

What this article solves

Writing a consumer by hand with a broker’s client isn’t hard for the first service: connect, subscribe, loop over messages, handle, acknowledge. The trouble comes with the second and third services, and after going live:

  • Every consumer re-implements the same things: how many retries and how far apart when handling fails; where messages go when retries run out (dead letter/poison); a time limit per message; a panic in a handler mustn’t take down the process; finishing in-flight messages before shutting down.
  • The outbox relay is hand-written too: polling, locking, marking published, resending, cleaning up; the previous article’s code once per service.
  • Tests need a real broker: to test “succeeds after two retries” or “a bad message goes to the dead letters”, a test has to start NATS or Kafka.
  • Switching brokers touches everything: going from NATS to Kafka means changing every consumer and every publish.

This article works through:

  1. What hand-written consumers end up repeating.
  2. What Watermill is: messages, Publisher, Subscriber, Router, middleware and adapters.
  3. When to use it and when you don’t need it.
  4. Events and their envelope, mapped onto Watermill messages.
  5. Connecting to NATS JetStream.
  6. The inventory consumer with a Router and middleware: retries, poison messages, timeouts and panics.
  7. Deduplicating with an inbox, and treating “out of stock” as an event rather than an error.
  8. Replacing the hand-written relay with the SQL outbox and the forwarder.
  9. Wiring it up in main with graceful shutdown.
  10. Testing with an in-memory Pub/Sub, no broker needed.
  11. Observability and operations.

Step 1: What you end up writing by hand

Step 7 of “Message Queues and Event-Driven Design” suggested treating consumers as an adapter layer, with timeouts, graceful shutdown and consumer lag. Put all of that in and a consumer looks roughly like this:

// fragment: a hand-written consume loop (a sketch)
for {
	msg, err := sub.Next(ctx) // depends on the broker's client
	if err != nil {
		if ctx.Err() != nil {
			return // shutting down
		}
		continue
	}
	func() {
		defer func() {
			if r := recover(); r != nil { /* log, Nak */ }
		}()
		hctx, cancel := context.WithTimeout(ctx, 10*time.Second)
		defer cancel()
		var err error
		for attempt := 0; attempt < 3; attempt++ {
			if err = handle(hctx, msg); err == nil {
				break
			}
			time.Sleep(backoff(attempt))
		}
		if err != nil {
			publishToDLQ(msg, err) // to the dead letters, then ack the original
		}
		msg.Ack()
	}()
}

The business logic is the single handle line; everything else is infrastructure, and every line has a way to go wrong (is the timeout reset between retries, what if publishing the dead letter fails, what happens to a message mid-retry at shutdown). Copied into every service and every topic, one bug fix means changes in many places.

ConcernBy handWatermill
Acks and redeliveryDifferent API per clientUniform Ack()/Nack(); the handler returns nil or an error
Retries and backoffYour own loopmiddleware.Retry
Dead letters / poison messagesPublish and ack yourselfmiddleware.PoisonQueue
Timeouts and panicscontext.WithTimeout, recovermiddleware.Timeout, middleware.Recoverer
Graceful shutdownHandle signals and waiting yourselfRouter and plugin.SignalsHandler
Outbox relayYour own polling, locking, markingwatermill-sql + the forwarder component
TestingStart a real brokerThe in-memory gochannel
Switching brokersChange every publish and subscribeSwap one adapter

Step 2: What Watermill is

Watermill is an open-source (MIT) Go library from Three Dots Labs for working with message streams. It isn’t a broker, nor a framework that dictates how to organise your whole project; it’s a thin abstraction that lets you work with different brokers in one way, with the logic every consumer shares turned into components you compose.

Brokers (swap one: change only the adapter) NATS JetStream Kafka RabbitMQ PostgreSQL gochannel Adapters: watermill-nats, watermill-kafka, watermill-amqp, watermill-sql… all implementing the same Publisher/Subscriber interfaces Subscriber Subscribe(ctx, topic) Publisher Publish(topic, msgs...) Router middleware: retry, poison, timeout… handler(msg) → nil / error nil → Ack; error → Nack messages messages a handler emits

Figure: adapters wrap each broker in the same Publisher/Subscriber interfaces; the Router reads from a Subscriber and passes each message through layers of middleware to the handler, whose result decides between ack and redelivery.

There are only a few core concepts:

  • message.Message: a message with a UUID (unique ID), Metadata (string key-values, like HTTP headers), a Payload (bytes), and Ack()/Nack(). msg.Context() carries the message’s context.
  • message.Publisher: Publish(topic, msgs...) sends messages to a topic.
  • message.Subscriber: Subscribe(ctx, topic) returns a channel of messages.
  • Adapters (Pub/Subs): one implementation per broker, such as Kafka, NATS JetStream, RabbitMQ (AMQP), Google Cloud Pub/Sub, Redis Streams, AWS SNS/SQS, PostgreSQL/MySQL (SQL), and the in-memory gochannel for tests.
  • message.Router: takes over “subscribe to a topic, handle, acknowledge”; you write only the handler. When the handler returns nil the Router acks; when it returns an error it doesn’t (Nack), so the message is redelivered.
  • Middleware: functions wrapped around the handler, the same idea as HTTP middleware: retries, poison queues, timeouts, panic recovery, correlation IDs, throttling and circuit breaking come ready-made.
  • Components: higher-level features built on top, such as the forwarder for the outbox, Prometheus metrics, and CQRS (typed command and event buses).

When to use it:

  • Several services and topics to consume, wanting consistent retries, dead letters and timeouts rather than one set per service.
  • A transactional outbox without maintaining a relay per service.
  • Testing event handling in unit tests without starting a broker.
  • A broker that may change, or different ones per environment (say PostgreSQL in development, NATS in production).

When you don’t need it:

  • A single simple consumer, where the broker’s official client is enough.
  • Features specific to one broker, such as Kafka transactions (exactly-once read-process-write), fine control of partition assignment, or NATS’s Key-Value store. The abstraction hides these, or they need the adapter’s configuration.
  • Squeezing out maximum throughput: every layer of abstraction costs a little, and the official client gives direct control of batching, buffering and acknowledgement.

Step 3: Events and the envelope

Step 6 of “Message Queues and Event-Driven Design” designed an event envelope: event ID, type, version, partition key, trace ID, and the business content. Mapped onto Watermill: the event ID is the UUID, the other envelope fields go in Metadata, and the business content is the Payload. Write that mapping in one shared package for every service:

// Package events defines the events between the shop's services: topics, content and envelope metadata.
package events

import (
	"encoding/json"
	"fmt"

	"github.com/ThreeDotsLabs/watermill/message"
)

// topics: the same as the event types in “Message Queues and Event-Driven Design”
const (
	TopicOrderPlaced       = "order.placed"
	TopicInventoryRejected = "inventory.rejected" // out of stock: the saga compensates
	TopicPoison            = "shop.poison"        // messages still failing after every retry
)

// OrderPlaced is the event published once an order is created.
type OrderPlaced struct {
	OrderID  string `json:"order_id"`
	UserID   int64  `json:"user_id"`
	Total    int64  `json:"total"` // in cents
	Currency string `json:"currency"`
	Items    []Item `json:"items"`
}

type Item struct {
	SKU string `json:"sku"`
	Qty int64  `json:"qty"`
}

// InventoryRejected is published when stock runs short.
type InventoryRejected struct {
	OrderID string `json:"order_id"`
	SKU     string `json:"sku"`
}

// NewMessage builds a message: the UUID is the event ID (unchanged on redelivery), the envelope goes in Metadata.
func NewMessage(eventID, eventType, subject string, data any) (*message.Message, error) {
	payload, err := json.Marshal(data)
	if err != nil {
		return nil, fmt.Errorf("events: encode %s: %w", eventType, err)
	}
	msg := message.NewMessage(eventID, payload)
	msg.Metadata.Set("type", eventType)
	msg.Metadata.Set("version", "1")
	msg.Metadata.Set("subject", subject) // partition key: one order's events are handled in order
	return msg, nil
}

// Decode turns a message's payload back into an event.
func Decode[T any](msg *message.Message) (T, error) {
	var v T
	if err := json.Unmarshal(msg.Payload, &v); err != nil {
		return v, fmt.Errorf("events: decode %s: %w", msg.UUID, err)
	}
	return v, nil
}

The publisher decides the event ID, and it never changes on resend. That’s what lets consumers deduplicate: never generate a new UUID on a retry or a forward.

Step 4: Connecting to NATS JetStream

The series has used NATS JetStream all along (“Message Queues and Event-Driven Design” compared Kafka, RabbitMQ and NATS). Watermill’s NATS adapter is github.com/ThreeDotsLabs/watermill-nats/v2:

// internal/platform/nats.go: publisher and subscriber for NATS JetStream
package platform

import (
	"time"

	"github.com/ThreeDotsLabs/watermill"
	wnats "github.com/ThreeDotsLabs/watermill-nats/v2/pkg/nats"
	"github.com/nats-io/nats.go"
)

// NewNATS builds a JetStream publisher and subscriber; the durable name lets a restarted consumer resume where it acked.
func NewNATS(url, durable string, logger watermill.LoggerAdapter) (*wnats.Publisher, *wnats.Subscriber, error) {
	marshaler := &wnats.NATSMarshaler{}
	js := wnats.JetStreamConfig{
		AutoProvision: false, // operations create the stream (retention, replicas, dedupe window); don't auto-create
		TrackMsgID:    true,  // the message UUID as Nats-Msg-Id: the server drops repeat publishes within its window
		DurablePrefix: durable,
	}
	pub, err := wnats.NewPublisher(wnats.PublisherConfig{
		URL:       url,
		Marshaler: marshaler,
		JetStream: js,
	}, logger)
	if err != nil {
		return nil, nil, err
	}
	sub, err := wnats.NewSubscriber(wnats.SubscriberConfig{
		URL:              url,
		QueueGroupPrefix: durable, // replicas of one service share the messages
		SubscribersCount: 4,
		AckWaitTimeout:   30 * time.Second,
		CloseTimeout:     30 * time.Second,
		Unmarshaler:      marshaler,
		NatsOptions:      []nats.Option{nats.RetryOnFailedConnect(true)},
		JetStream:        js,
	}, logger)
	if err != nil {
		pub.Close()
		return nil, nil, err
	}
	return pub, sub, nil
}

What the settings mean:

  • TrackMsgID: uses the message UUID as JetStream’s Nats-Msg-Id, so the server drops a repeat publish of the same ID within its deduplication window. That stops duplicates from the publishing side; redeliveries to consumers still need step 6’s inbox.
  • DurablePrefix: the durable consumer’s name, so a restarted consumer continues from its last acknowledgement rather than from the beginning or from now.
  • QueueGroupPrefix: replicas of one service join one queue group and share the messages, instead of each receiving a copy.
  • AckWaitTimeout: how long after delivery without an ack before the server redelivers. It must exceed “the time limit plus every retry”, or a message still being retried is delivered again to another replica.
  • AutoProvision: creates the stream automatically, handy in development; in production, operations should create the stream (retention, replicas, deduplication window) in advance and keep it under version control, so it’s off here.

To move to Kafka or RabbitMQ, only this file changes: the Router and handlers further on see only the message.Publisher/message.Subscriber interfaces.

Step 5: Router and middleware: the inventory consumer

The inventory service consumes order.placed and reserves stock for each item. With a Router, the handler is down to “decode, call the service”:

// internal/inventory/consumer.go: consuming order.placed with Watermill's Router
package inventory

import (
	"context"
	"time"

	"github.com/ThreeDotsLabs/watermill"
	"github.com/ThreeDotsLabs/watermill/message"
	"github.com/ThreeDotsLabs/watermill/message/router/middleware"
	"github.com/ThreeDotsLabs/watermill/message/router/plugin"

	"example.com/shop/internal/events"
)

// Reserver is the inventory logic: write the inbox (dedupe by event ID) and reserve stock in one transaction.
type Reserver interface {
	ReserveForOrder(ctx context.Context, eventID string, e events.OrderPlaced) error
}

// NewRouter wires up the inventory service's event handling: middleware wraps from outside in, in the order added.
func NewRouter(sub message.Subscriber, poisonPub message.Publisher, svc Reserver, logger watermill.LoggerAdapter) (*message.Router, error) {
	router, err := message.NewRouter(message.RouterConfig{CloseTimeout: 30 * time.Second}, logger)
	if err != nil {
		return nil, err
	}
	router.AddPlugin(plugin.SignalsHandler) // shut down gracefully on SIGINT/SIGTERM

	poison, err := middleware.PoisonQueue(poisonPub, events.TopicPoison)
	if err != nil {
		return nil, err
	}
	router.AddMiddleware(
		middleware.CorrelationID, // carry the correlation ID onto messages produced while handling
		poison,                   // outermost: still failing after retries, send to the poison topic and ack
		middleware.Retry{ // retry with exponential backoff
			MaxRetries:      3,
			InitialInterval: 100 * time.Millisecond,
			MaxInterval:     2 * time.Second,
			Multiplier:      2,
			Logger:          logger,
		}.Middleware,
		middleware.Timeout(10*time.Second), // a time limit per message (through msg.Context())
		middleware.Recoverer,               // innermost: turn a panic into an error for the retry
	)

	router.AddConsumerHandler("inventory.reserve", events.TopicOrderPlaced, sub,
		func(msg *message.Message) error {
			e, err := events.Decode[events.OrderPlaced](msg)
			if err != nil {
				return err
			}
			// nil: the Router acks; an error: the middleware retries, and finally the poison topic
			return svc.ReserveForOrder(msg.Context(), msg.UUID, e)
		})
	return router, nil
}

Middleware order matters. Middleware wraps the handler from outside in, in the order added; a message enters at the outermost layer and the result comes back out from the innermost:

CorrelationID carry the correlation ID PoisonQueue still failing → shop.poison, ack original Retry up to 3, exponential backoff Timeout 10 s per attempt Recoverer panic → error handler decode → service (inbox) Messages go in, errors come out: Recoverer turns panics into errors, Retry tries again, PoisonQueue only after.

Figure: a message passes from outside in through CorrelationID, PoisonQueue, Retry, Timeout and Recoverer to the handler; errors travel outward, and only when Retry has run out does PoisonQueue take over.

  • Recoverer innermost: a panic in the handler becomes an error that the Retry outside can see and retry. Placed outside, a panic would pass straight through Retry.
  • Timeout inside Retry: each attempt gets its own time limit. Outside, all three attempts would share one.
  • PoisonQueue outside Retry: only after every retry has failed is the message sent to the poison topic shop.poison and the original acknowledged, so it stops blocking those behind it. Inside Retry, the first failure would send it away.
  • Timeout works through msg.Context(): the handler’s database calls must use msg.Context() for the cancellation to reach them.

The handler’s return value is the acknowledgement. nil: ack. An error: over to the middleware, ending either in a successful retry or in the poison topic. So returning nil halfway through, or handing work to a background goroutine and returning, acknowledges the message before it’s handled, and it’s lost if the process crashes.

Someone has to watch the poison topic: alert when it has messages, provide a way to redeliver (Watermill’s requeuer component moves messages back to their original topic), and keep the reason for each (PoisonQueue writes the error, the original topic and the handler name into the message’s Metadata, for example reason_poisoned).

Step 6: Inbox dedupe, and “out of stock” isn’t an error

Even with TrackMsgID, consumers still see duplicates: if the process crashes after handling but before the ack is sent, the message is redelivered. So follow the inbox from step 7 of “Sagas and the Outbox”: insert the event ID in the same transaction as the business change, and carry on only if the insert succeeded.

The other matter is classifying errors. A briefly busy database or a dropped connection might succeed on retry, so return the error to Retry. But “out of stock” won’t improve after a hundred retries; it’s a business outcome, and should become an event (inventory.rejected) for the saga’s orchestrator to compensate (cancel the order, notify the user), not an error that ends in the poison topic after retrying:

// internal/inventory/service.go: inbox dedupe, reserving stock and the out-of-stock event, each in one transaction
package inventory

import (
	"context"
	"database/sql"

	"github.com/ThreeDotsLabs/watermill"
	"github.com/google/uuid"

	"example.com/shop/internal/events"
	"example.com/shop/internal/platform"
)

type Service struct {
	db     *sql.DB
	logger watermill.LoggerAdapter
}

func NewService(db *sql.DB, logger watermill.LoggerAdapter) *Service {
	return &Service{db: db, logger: logger}
}

// ReserveForOrder follows the inbox from “Sagas and the Outbox”: only a newly inserted event ID is processed.
func (s *Service) ReserveForOrder(ctx context.Context, eventID string, e events.OrderPlaced) error {
	tx, err := s.db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()

	res, err := tx.ExecContext(ctx,
		`INSERT INTO inbox (event_id) VALUES ($1) ON CONFLICT DO NOTHING`, eventID)
	if err != nil {
		return err
	}
	if n, _ := res.RowsAffected(); n == 0 {
		return nil // already handled: return nil so the Router acknowledges the duplicate
	}
	for _, it := range e.Items {
		res, err := tx.ExecContext(ctx, `
			UPDATE inventory SET reserved = reserved + $2
			WHERE sku = $1 AND stock - reserved >= $2`, it.SKU, it.Qty)
		if err != nil {
			return err // a transient database error: return it for a retry
		}
		if n, _ := res.RowsAffected(); n == 0 {
			// out of stock is a business outcome, not an error (retrying won't help):
			// drop this transaction's reservations, and record the inbox entry and a rejection event in a new one
			_ = tx.Rollback()
			return s.reject(ctx, eventID, e.OrderID, it.SKU)
		}
	}
	return tx.Commit()
}

func (s *Service) reject(ctx context.Context, eventID, orderID, sku string) error {
	tx, err := s.db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()
	res, err := tx.ExecContext(ctx,
		`INSERT INTO inbox (event_id) VALUES ($1) ON CONFLICT DO NOTHING`, eventID)
	if err != nil {
		return err
	}
	if n, _ := res.RowsAffected(); n == 0 {
		return nil // another replica just handled the same event
	}
	msg, err := events.NewMessage(uuid.NewString(), events.TopicInventoryRejected, orderID,
		events.InventoryRejected{OrderID: orderID, SKU: sku})
	if err != nil {
		return err
	}
	if err := platform.PublishInTx(tx, s.logger, events.TopicInventoryRejected, msg); err != nil {
		return err
	}
	return tx.Commit()
}

Both PlaceOrder and this reject use the same platform.PublishInTx to write events into their own outbox, covered next.

Watermill also has a middleware.Deduplicator, which by default drops messages with the same content hash within a time window (one minute by default). Its records live in the process’s memory by default, not shared between replicas and gone on restart (its documentation notes that the default doesn’t support distributed operation); it’s fine for short bursts of duplicates but no substitute for an inbox. To be correct, dedupe records must be written in the same transaction as the business change.

Step 7: Replacing the hand-written relay with the SQL outbox and forwarder

The previous article’s relay dealt with polling, FOR UPDATE SKIP LOCKED, marking published and resending. Watermill assembles two ready-made pieces instead:

  • watermill-sql’s Publisher: writes messages into a PostgreSQL table. The key is that it can be created from a transaction (*sql.Tx), so the event is written in the same transaction as the business data.
  • The forwarder component: on write, wraps each message in an envelope saying which topic it’s meant for and stores everything under one outbox topic; on the other side, the Forwarder reads from the outbox, unwraps, and publishes to the real broker (NATS here).

Wrapped as two functions shared by every service:

// internal/platform/outbox.go: the transactional outbox and forwarder (shared by every service)
package platform

import (
	"context"
	"database/sql"

	"github.com/ThreeDotsLabs/watermill"
	wsql "github.com/ThreeDotsLabs/watermill-sql/v3/pkg/sql"
	"github.com/ThreeDotsLabs/watermill/components/forwarder"
	"github.com/ThreeDotsLabs/watermill/message"
)

// OutboxTopic is the outbox's topic in the database (table watermill_outbox).
const OutboxTopic = "outbox"

// PublishInTx writes events into the outbox in this transaction: they exist only if it commits.
// forwarder.Publisher records the topic each message was meant for.
func PublishInTx(tx *sql.Tx, logger watermill.LoggerAdapter, topic string, msgs ...*message.Message) error {
	sqlPub, err := wsql.NewPublisher(tx, wsql.PublisherConfig{
		SchemaAdapter: wsql.DefaultPostgreSQLSchema{},
	}, logger)
	if err != nil {
		return err
	}
	return forwarder.NewPublisher(sqlPub, forwarder.PublisherConfig{ForwarderTopic: OutboxTopic}).
		Publish(topic, msgs...)
}

// RunForwarder reads events from the outbox and sends them to the real broker (replacing the hand-written relay).
func RunForwarder(ctx context.Context, db *sql.DB, out message.Publisher, logger watermill.LoggerAdapter) error {
	sub, err := wsql.NewSubscriber(db, wsql.SubscriberConfig{
		SchemaAdapter:    wsql.DefaultPostgreSQLSchema{},
		OffsetsAdapter:   wsql.DefaultPostgreSQLOffsetsAdapter{},
		InitializeSchema: true,
	}, logger)
	if err != nil {
		return err
	}
	fwd, err := forwarder.NewForwarder(sub, out, logger, forwarder.Config{ForwarderTopic: OutboxTopic})
	if err != nil {
		return err
	}
	return fwd.Run(ctx)
}

When the order service creates an order, the order and its event share one transaction:

// internal/order/outbox.go: the order and its event in one transaction (transactional outbox)
package order

import (
	"context"
	"database/sql"
	"fmt"

	"github.com/ThreeDotsLabs/watermill"
	"github.com/google/uuid"

	"example.com/shop/internal/events"
	"example.com/shop/internal/platform"
)

type Order struct {
	ID       string
	UserID   int64
	Total    int64
	Currency string
	Items    []events.Item
}

// PlaceOrder writes the order and its order.placed event in one transaction: both commit, or neither.
func PlaceOrder(ctx context.Context, db *sql.DB, logger watermill.LoggerAdapter, o Order) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback() // a no-op once committed

	if _, err := tx.ExecContext(ctx,
		`INSERT INTO orders (id, user_id, total, currency, status) VALUES ($1, $2, $3, $4, 'pending')`,
		o.ID, o.UserID, o.Total, o.Currency); err != nil {
		return fmt.Errorf("insert order: %w", err)
	}

	// the event ID is fixed here: resends carry the same ID, so consumers can dedupe
	msg, err := events.NewMessage(uuid.NewString(), events.TopicOrderPlaced, o.ID, events.OrderPlaced{
		OrderID: o.ID, UserID: o.UserID, Total: o.Total, Currency: o.Currency, Items: o.Items,
	})
	if err != nil {
		return err
	}
	if err := platform.PublishInTx(tx, logger, events.TopicOrderPlaced, msg); err != nil {
		return fmt.Errorf("write outbox: %w", err)
	}
	return tx.Commit()
}
Order service PlaceOrder order + event, one transaction PostgreSQL (order) orders watermill_outbox one transaction Forwarder read outbox → publish NATS JetStream Inventory Router middleware → handler at least once PostgreSQL (inventory) inbox dedupe + reserve; if short, inventory.rejected to its outbox sent on by its forwarder

Figure: the order and the outbox are written to PostgreSQL in one transaction; the forwarder reads the outbox and sends to NATS; the inventory Router consumes and dedupes with its inbox, and when stock is short writes inventory.rejected into its own outbox.

How it differs from the hand-written relay:

  • Watermill manages the tables: DefaultPostgreSQLSchema names a table per topic (here watermill_outbox), with read progress in an offsets table. InitializeSchema: true creates them on the first subscribe; in production you can put the creation SQL in your migrations instead (the migration flow from “database/sql, Transactions and Connection Pools in Go”).
  • No AutoInitializeSchema on a Publisher created from a transaction: running CREATE TABLE inside a transaction can commit it implicitly. Leave table creation to the forwarder’s Subscriber or to migrations.
  • Still at least once: if the forwarder crashes after sending but before recording progress, it sends again. Consumers still dedupe with the inbox; TrackMsgID adds another layer within JetStream’s deduplication window.
  • Ordering: a topic’s outbox is read in write order; a single forwarder instance keeps ordering simplest. To scale out, shard by partition key, as with the previous article’s relay.

Step 8: Wiring it up in main, with graceful shutdown

The inventory service’s main: connect to the database and NATS, build the Router, run until a signal arrives:

// cmd/inventory/main.go: wire up NATS, the Router and the service, and shut down gracefully on a signal
package main

import (
	"context"
	"database/sql"
	"log/slog"
	"os"
	"os/signal"
	"syscall"

	"github.com/ThreeDotsLabs/watermill"
	_ "github.com/jackc/pgx/v5/stdlib"

	"example.com/shop/internal/inventory"
	"example.com/shop/internal/platform"
)

func main() {
	logger := watermill.NewSlogLogger(slog.Default())
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
	if err != nil {
		slog.Error("open database", "err", err)
		os.Exit(1)
	}
	defer db.Close()

	pub, sub, err := platform.NewNATS(os.Getenv("NATS_URL"), "inventory", logger)
	if err != nil {
		slog.Error("connect nats", "err", err)
		os.Exit(1)
	}
	defer pub.Close()

	router, err := inventory.NewRouter(sub, pub, inventory.NewService(db, logger), logger)
	if err != nil {
		slog.Error("build router", "err", err)
		os.Exit(1)
	}
	// Run blocks until ctx is cancelled (or a signal arrives), then waits for in-flight messages
	if err := router.Run(ctx); err != nil {
		slog.Error("router stopped", "err", err)
		os.Exit(1)
	}
}

router.Run(ctx) subscribes every handler’s topic and returns only when ctx is cancelled (here by signal.NotifyContext on SIGINT/SIGTERM); before returning it stops taking new messages and waits for in-flight ones (up to RouterConfig.CloseTimeout). That’s the behaviour “Configuration and Graceful Shutdown in Go” asks for, without writing it yourself. The order service’s main does one thing more: run platform.RunForwarder in a goroutine on the same ctx.

watermill.NewSlogLogger routes Watermill’s logs through the standard library’s log/slog, alongside the service’s other structured logs (the format from the observability article).

Step 9: Testing with an in-memory Pub/Sub

gochannel is an in-memory Pub/Sub implementing the same interfaces. Hand it straight to NewRouter in a test, and the whole handling flow, retries, dedupe and poison messages included, can be checked in a unit test:

package inventory

import (
	"context"
	"errors"
	"sync"
	"testing"
	"time"

	"github.com/ThreeDotsLabs/watermill"
	"github.com/ThreeDotsLabs/watermill/message"
	"github.com/ThreeDotsLabs/watermill/pubsub/gochannel"

	"example.com/shop/internal/events"
)

// fakeReserver stands in for the database: an inbox dedupes by event ID, and the first failFirst calls fail
type fakeReserver struct {
	mu        sync.Mutex
	inbox     map[string]bool
	reserved  map[string]int64
	calls     int
	failFirst int
}

func (f *fakeReserver) ReserveForOrder(_ context.Context, eventID string, e events.OrderPlaced) error {
	f.mu.Lock()
	defer f.mu.Unlock()
	f.calls++
	if f.calls <= f.failFirst {
		return errors.New("database is busy")
	}
	if f.inbox[eventID] {
		return nil // already handled: acknowledge anyway
	}
	f.inbox[eventID] = true
	f.reserved[e.OrderID] += e.Total
	return nil
}

func TestRouterRetriesDedupesAndPoisons(t *testing.T) {
	logger := watermill.NopLogger{}
	// gochannel: an in-memory Pub/Sub, so the test needs no real NATS
	pubsub := gochannel.NewGoChannel(gochannel.Config{OutputChannelBuffer: 16}, logger)
	svc := &fakeReserver{inbox: map[string]bool{}, reserved: map[string]int64{}, failFirst: 2}

	router, err := NewRouter(pubsub, pubsub, svc, logger)
	if err != nil {
		t.Fatal(err)
	}
	poisoned, err := pubsub.Subscribe(context.Background(), events.TopicPoison)
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go func() { _ = router.Run(ctx) }()
	<-router.Running()

	ok, _ := events.NewMessage("evt-1", events.TopicOrderPlaced, "A-1001",
		events.OrderPlaced{OrderID: "A-1001", UserID: 42, Total: 129900, Currency: "TWD"})
	dup, _ := events.NewMessage("evt-1", events.TopicOrderPlaced, "A-1001",
		events.OrderPlaced{OrderID: "A-1001", UserID: 42, Total: 129900, Currency: "TWD"})
	bad := message.NewMessage("evt-2", []byte("not json"))
	for _, m := range []*message.Message{ok, dup, bad} {
		if err := pubsub.Publish(events.TopicOrderPlaced, m); err != nil {
			t.Fatal(err)
		}
	}

	select {
	case m := <-poisoned:
		if m.UUID != "evt-2" {
			t.Fatalf("poisoned %s, want evt-2", m.UUID)
		}
		m.Ack()
	case <-time.After(10 * time.Second):
		t.Fatal("the bad message never reached the poison topic")
	}
	svc.mu.Lock()
	defer svc.mu.Unlock()
	if got := svc.reserved["A-1001"]; got != 129900 {
		t.Fatalf("reserved %d, want 129900 once despite the retry and the duplicate", got)
	}
}

The test checks three things: a briefly busy database (the first two calls fail) is retried until it succeeds; the same event ID sent twice reserves stock once; a message that can’t be decoded reaches the poison topic after the retries run out. It uses a fake Reserver in place of the database; the inbox and outbox SQL themselves get integration tests against a real PostgreSQL, as in “database/sql, Transactions and Connection Pools in Go”.

Step 10: Observability and operations

  • Tracing: put trace_id in Metadata when publishing (an envelope field from “Message Queues and Event-Driven Design”), and pick it up when consuming to continue the trace, so a request’s path across order, NATS and inventory is visible. middleware.CorrelationID carries a correlation ID onto the messages a handler publishes.
  • Metrics: Watermill’s metrics component exposes Prometheus metrics (messages handled, failures, handling time); add JetStream consumer lag, the size of the poison topic, and the age of the oldest unforwarded outbox event.
  • Alerts: messages in the poison topic, steadily rising consumer lag, and an oldest outbox event older than a few minutes should all notify a person.
  • Evolving event structure: keep version in Metadata and evolve by the compatibility rules from “Message Queues and Event-Driven Design”; when a handler meets a version it doesn’t know, return an error so it lands in the poison topic, rather than silently dropping it.

Common pitfalls

Returning nil before the work is done. For example, handing work to a background goroutine. The message is acknowledged and lost if the process crashes; do the work synchronously in the handler.

Middleware in the wrong order. Recoverer outside lets a panic pass through the retries; PoisonQueue inside Retry sends messages away on the first failure.

AckWaitTimeout shorter than all the retries. The broker redelivers a message still being retried to another replica, and two replicas handle it at once.

Treating business outcomes as errors. Out of stock or a frozen account won’t improve on retry; make them events for the saga rather than poison messages after retrying.

Thinking Deduplicator or TrackMsgID is enough. They stop only some duplicates; correct dedupe is an inbox written in the same transaction as the business change.

A new UUID on resend. The event ID is fixed when written to the outbox, and every resend carries the same ID, so consumers can dedupe.

Not using msg.Context() in the handler. Timeout and shutdown cancellation never reach the database calls, and middleware.Timeout does nothing.

AutoProvision in production. The stream is created with default retention, replicas and deduplication window, and you discover during an incident that data was kept for only a short time.

Nobody watches the poison topic. Messages pile up quietly, and their orders stay pending forever.

Key takeaways

  • Hand-written consumers make every service re-implement acks, retries, dead letters, timeouts, panics, shutdown, the outbox relay and tests; Watermill turns these into components you compose, leaving handlers with only business logic.
  • Watermill is a library, not a broker or a framework: Message (UUID, Metadata, Payload, Ack/Nack), Publisher, Subscriber, adapters for each broker, the Router, middleware and components (forwarder, metrics, CQRS).
  • Good for: several services and topics, consistent reliability handling, an outbox, tests without a broker, a broker that may change. Not needed for: a single simple consumer, broker-specific features, maximum throughput tuning.
  • The event ID is the message UUID, the envelope fields go in Metadata; the publisher decides the ID and it never changes on resend.
  • NATS JetStream: TrackMsgID stops publish-side duplicates; durables and queue groups let replicas share messages and resume where they left off; AckWaitTimeout must exceed all the retries; no AutoProvision in production.
  • Router middleware from outside in: CorrelationID → PoisonQueue → Retry → Timeout → Recoverer; only a nil return acknowledges.
  • Dedupe with an inbox in the same transaction as the business change; return transient errors for a retry, turn business outcomes into events for the saga.
  • Transactional outbox: a watermill-sql Publisher created from the transaction, wrapped by the forwarder, with the Forwarder sending to NATS, replacing the hand-written relay; still at least once.
  • router.Run(ctx) handles signals and graceful shutdown; gochannel lets the whole handling flow be checked in unit tests.

References

  • Router (Watermill documentation): how a handler's return value decides ack or nack, and CloseTimeout on shutdown, used in steps 2, 5 and 8.
  • Middleware (Watermill documentation): Retry, PoisonQueue, Timeout, Recoverer and the Deduplicator, which is in-memory by default and not distributed, used in steps 5 and 6.
  • Forwarder (the outbox pattern) (Watermill documentation): the forwarder component that moves messages from a SQL outbox to a broker, used in step 7.
  • SQL (PostgreSQL, MySQL) (Watermill documentation): creating a publisher from a transaction and why AutoInitializeSchema is forbidden inside one, used in step 7.
  • NATS Jetstream (Watermill documentation): settings such as TrackMsgID, DurablePrefix and QueueGroupPrefix, used in step 4.
  • JetStream (NATS documentation): streams, consumers, acknowledgements and at-least-once redelivery, used in step 4.
  • Go Channel (Watermill documentation): the in-memory Pub/Sub used for unit tests, used in step 9.

Next

Publishing and consuming events is now reliable, and every service does it the same way. But when an order is stuck in pending, it’s still hard to answer “which service, which step, and why”. Before answering that, we need to know which version is actually running. The next article, “Versioning with Git: Branches, Tags and Rolling Back”, opens “going live and operating”: how to number versions, tag releases and roll back when something breaks.