Skip to content

Event-Driven Go: Watermill, RabbitMQ Emitters/Consumers, SQS, RPC between Services ​

"Design a receiver to be an Idempotent Receiver--one that can safely receive the same message multiple times." — Gregor Hohpe and Bobby Woolf, "Idempotent Receiver", Enterprise Integration Patterns

Summary: An event-driven Go service talks to its neighbours through a broker instead of calling them: it publishes facts, consumes messages with handlers that can safely run twice, acknowledges only after the work is stored, and shuts down without dropping what is in flight. This chapter builds that with Watermill (a Go library over many brokers), the raw RabbitMQ client amqp091-go, AWS SQS through aws-sdk-go-v2, and request-reply over messaging. Focus: message.Message, Publisher, Subscriber, the Watermill Router and its middleware (retry, poison queue, correlation ID, throttle), the CQRS component (command bus, event bus, event processors), the Pub/Subs (GoChannel, AMQP, Kafka, SQL, NATS), the AMQP calls (Dial, Channel, ExchangeDeclare, QueueDeclare, QueueBind, publish with confirms, Consume, Ack/Nack/Reject, prefetch Qos), a message envelope, idempotent consumers with an inbox table, the outbox from PostgreSQL, dead-letter exchanges and delayed retries, ordering per key, SQS long polling, visibility timeout, FIFO queues, SNS fan-out and DLQ redrive, RPC over messaging, graceful shutdown, OpenTelemetry messaging spans, and testing without a broker. Learning goal: Design a consumer you can restart at any moment: know which broker acknowledgement means "stored", where duplicates come from and which table removes their effect, how a failed message is retried with backoff and finally parked, how a request gets its reply across a broker, and how to prove all of it in a unit test that needs no broker.

This page owns the Go side of messaging: the libraries, the code shapes and the failure handling. The broker concepts themselves are one link away and are not re-taught: RabbitMQ for exchanges, queues and acknowledgements, Delivery Guarantees for at-most-once, at-least-once and "exactly once", Idempotent Consumer & Inbox and Outbox Pattern for the two tables, Dead Letter Queues and Retry, Backoff & Delayed Delivery for failure paths, Request-Reply over REST and AMQP for the pattern, Event-Driven Architecture for the design view, and Other Brokers for Kafka, NATS and Pulsar. Go prerequisites are context (every handler takes one), Worker Pools & Pipelines for bounded concurrency, and the capstone Microservices Project that uses these pieces together.

Facts below were checked against the Watermill documentation and source (v1.5.1 module cache), the watermill-amqp v3 source, the amqp091-go v1.17.0 source, the RabbitMQ documentation (confirms, consumer prefetch, dead lettering, quorum queues, TTL, publishers, consumers), the AWS SQS and SNS developer guides, the aws-sdk-go-v2 SQS client source, the OpenTelemetry messaging semantic conventions, the Enterprise Integration Patterns pages, microservices.io, the Go 1.20/1.21/1.22/1.24 release notes and the Laravel 13 queue and event documentation. No broker is installed on the build machine, so every test uses Watermill's in-memory GoChannel Pub/Sub or a hand-written fake; the labs that need RabbitMQ or SQS are marked "expected, not run". The snippets declare go 1.24 and pin versions whose go.mod still says 1.24 or lower (Watermill v1.5.1, watermill-amqp v3.1.0, amqp091-go v1.17.0, aws-sdk-go-v2/service/sqs v1.53.2, OpenTelemetry v1.41.0, golang.org/x/sys v0.41.0); newer Watermill (v1.5.2) and OpenTelemetry (v1.42.0 and later) need Go 1.25 or newer. They were compiled, vetted and tested with -race on Go 1.27.4 (macOS).

Page map ​

If you are looking forGo to
The tables you can memorise in one minuteEverything in one minute
Why services publish events instead of calling each otherWhy it exists
Where Watermill, amqp091-go and the SQS client come fromWhere it comes from
A consumer that loses and duplicates work, then the fixGo
Which term lives in which sectionKeyword inventory
message.Message, Publisher, Subscriber, Ack and NackThe Watermill message model
The Router and its handlersRouter and handlers
Retry, poison queue, correlation ID, throttle, recovererRouter middleware
Command bus, event bus, event processorsThe CQRS component
GoChannel, AMQP, Kafka, SQL and NATS Pub/SubsPub/Subs and the choice of broker
A message envelope: ID, type, occurred_at, traceMessage envelope
JSON versus protobuf payloadsPayload encoding
Dial, Channel, ExchangeDeclare, QueueDeclare, QueueBindRabbitMQ topology in Go
Publishing with confirms, mandatory, durableThe emitter
Consume, prefetch Qos, Ack, Nack, RejectThe consumer
Reconnect handlingReconnecting
Dead-letter exchanges, retries with backoffDelayed retry and parking
Idempotent consumers and the inbox tableInbox
Outbox publishing from PostgresOutbox
Ordering per keyOrdering
SQS: long polling, visibility timeout, DeleteMessage, FIFO, SNS fan-out, DLQ redriveAWS SQS
RPC between services over messaging, reply queueRequest-reply
When gRPC is the better callWhen to use gRPC instead
Graceful shutdown and in-flight drainGraceful shutdown
OpenTelemetry messaging spans, metrics, logsObservability
Testing with GoChannel and fakesTesting
Exact errors, knobs and limitsMechanics
Monolith to a distributed systemIn architecture
Run itLab
Laravel queues and events side by sideFor PHP/Laravel developers

Everything in one minute ​

The words.

WordPlain meaningGo type or callWho settles it
MessageA payload plus ID and metadatamessage.Message (UUID, Metadata, Payload)Handler returns, router calls Ack/Nack
PublisherThe sending halfmessage.Publisher.Publish(topic, msgs...)Returns when the broker took it (implementation specific)
SubscriberThe receiving halfmessage.Subscriber.Subscribe(ctx, topic) returns <-chan *message.MessageMust Ack or Nack each message
RouterRuns handlers, wires middlewaremessage.NewRouter, AddHandler, Run, CloseCloses after in-flight handlers finish
EmitterOur name for "the code that publishes events"rabbit.Emitter hereWaits for a publisher confirm
ConsumerOur name for "the code that handles deliveries"rabbit.Consumer hereAck, Nack or Reject

The failure ladder. Every consumer needs an answer for each rung.

FailureWhat the broker doesWhat your code must do
Handler succeeds, ack lostRedelivers: a duplicateBe idempotent (inbox row or natural key)
Handler fails onceNothing, unless you nackRetry with backoff
Handler fails every time (poison message)Redelivers forever, or dead-lettersCap attempts, park the message, alert
Process killed mid-handlerRedelivers after the connection dropsDo work and ack in the right order; be idempotent
Broker restartsCloses your connectionReconnect, re-declare topology, resume
Publisher crashes after the DB commit, before publishNothing arrivesOutbox: write the event in the same transaction
Slow consumerQueue growsBound prefetch, scale consumers, alert on depth

The delivery guarantee you actually get.

BrokerDefault guaranteeWhat makes it durableOrdering
RabbitMQAt-least-once with manual acks and confirmsdurable queue + persistent message + publisher confirmPer queue, lost on requeue or with several consumers
AWS SQS standardAt-least-once, best-effort orderingReplicated by SQSNone guaranteed
AWS SQS FIFODeduplicated within the deduplication interval, ordered per message groupReplicatedPer MessageGroupId
KafkaAt-least-once by default for consumersReplication, acks=allPer partition
NATS coreAt-most-onceNonePer publisher
NATS JetStreamAt-least-onceStream storagePer stream
Watermill GoChannelIn-process onlyNothing: lost on exitPer topic unless Persistent

The sentence to remember: a message is acknowledged after its effect is committed, and the effect is safe to repeat.

Why it exists ​

Two services that call each other with HTTP or gRPC are coupled in time: the caller needs the callee up, fast and correct at the moment of the call. An order service that must call billing, stock, email and analytics synchronously is as available as the product of the four. Event-driven architecture in Go services replaces that chain with a log of facts ("order placed") that interested services consume at their own pace. The price is that you now own a failure model: duplicates, reordering, poison messages, lag, and a second system (the broker) to operate.

Direct calls (HTTP, gRPC)Events through a broker
Caller waits for the answerPublisher continues; consumers catch up
Callee down means caller failsBroker holds the message until the consumer returns
Adding a consumer means editing the callerA new queue bound to the same exchange or topic
Failure is an error valueFailure is a redelivery, a retry or a parked message
Exactly one execution per call (or an error)At least one execution; duplicates are normal
Easy to traceNeeds propagated trace context
Latency is the sum of hopsLatency is publish time plus lag

An everyday picture. A post office with numbered pigeonholes. The sender drops a letter in the slot and walks away (publish with confirm: the clerk stamps "received"). The clerk sorts it into the pigeonholes of everyone who subscribed to that kind of letter (routing). Each recipient collects at their own speed and signs for it only after reading and acting (ack). A letter that nobody can read ends up in a "dead letters" box that a human inspects (parking lot). A recipient who signs and then loses the letter is the lost-message bug; a clerk who hands the same letter twice because the signature slip got lost is the duplicate.

Three common misunderstandings, up front ​

  1. "The broker delivers each message exactly once." No mainstream broker does end to end. RabbitMQ, SQS standard and Kafka consumers are at-least-once; "exactly once" in marketing means "effectively once" with idempotent processing, which is your code.
  2. "A publisher confirm means the consumer got it." A confirm means the broker took responsibility (for a quorum queue: replicated to a majority). Nobody has consumed anything yet.
  3. "Retrying in the handler is enough." Retrying inside the handler holds a delivery and a prefetch slot. A message that fails for an hour needs a delayed retry path and a parking lot, not a loop.

Where it comes from ​

Hohpe and Woolf's Enterprise Integration Patterns (2003) named the vocabulary used everywhere here: Publish-Subscribe Channel, Dead Letter Channel, Idempotent Receiver, Correlation Identifier, Request-Reply, Envelope Wrapper. AMQP 0-9-1 (the protocol RabbitMQ implements) defines exchanges, queues and bindings; the Go client github.com/rabbitmq/amqp091-go is "a Go AMQP 0.9.1 client maintained by the RabbitMQ core team", the continuation of the older streadway/amqp. Watermill, by Three Dots Labs, describes itself as "a Go library for working efficiently with message streams" for "building event driven applications, enabling event sourcing, RPC over messages, sagas". Its design point is a tiny Publisher/Subscriber interface pair so that the same handler runs on Kafka, RabbitMQ, SQL or an in-memory channel. AWS SQS is one of the oldest AWS services; aws-sdk-go-v2 is the modular Go SDK where each service is its own module (service/sqs), which is why the snippets import only that module and config.

On the Go side, three language features shape the code: context (Go 1.7) carries cancellation into handlers, errors.Join (Go 1.20) combines settle and cleanup errors, and Go 1.21 added context.WithoutCancel (let in-flight work finish after shutdown starts) and the min/max builtins. Go 1.22 added range over integers and math/rand/v2 (used for jitter), and Go 1.24 added T.Context, which cancels after the test ends.

Go ​

Before ​

A consumer that acknowledges first and applies every delivery it sees. It looks fine on a quiet day. When the handler fails after the ack, the message is gone; when the broker redelivers a message whose ack was lost, the account is credited twice.

go
// Package before shows the consumer most teams write first: it acknowledges
// the message before the work is done and applies every delivery it sees.
package before

import "sync"

// Message is what the broker hands to the consumer.
type Message struct {
	ID     string
	Amount int
}

// Source is the broker side: Next hands out a delivery, Ack removes it from
// the queue for good.
type Source interface {
	Next() (Message, bool)
	Ack(Message)
}

// Account is the state the consumer changes.
type Account struct {
	mu      sync.Mutex
	balance int
}

// Credit adds n to the balance.
func (a *Account) Credit(n int) {
	a.mu.Lock()
	defer a.mu.Unlock()
	a.balance += n
}

// Balance returns the current balance.
func (a *Account) Balance() int {
	a.mu.Lock()
	defer a.mu.Unlock()
	return a.balance
}

// Run drains the source. Two design mistakes live here:
//
//  1. Ack comes before the work, so a failure after Ack loses the message
//     (at-most-once by accident).
//  2. Nothing remembers message IDs, so a redelivery credits the account again
//     (not idempotent).
func Run(src Source, acct *Account, work func(Message) error) {
	for {
		m, ok := src.Next()
		if !ok {
			return
		}
		src.Ack(m)
		if err := work(m); err != nil {
			continue // the message is already gone from the queue
		}
		acct.Credit(m.Amount)
	}
}

The test proves both bugs on purpose:

go
package before

import (
	"errors"
	"testing"
)

type fakeSource struct {
	queue []Message
	acked []string
}

func (f *fakeSource) Next() (Message, bool) {
	if len(f.queue) == 0 {
		return Message{}, false
	}
	m := f.queue[0]
	f.queue = f.queue[1:]
	return m, true
}

func (f *fakeSource) Ack(m Message) { f.acked = append(f.acked, m.ID) }

func TestRedeliveryCreditsTwice(t *testing.T) {
	src := &fakeSource{queue: []Message{{"m-1", 100}, {"m-1", 100}}} // broker redelivered m-1
	acct := &Account{}
	Run(src, acct, func(Message) error { return nil })
	if got := acct.Balance(); got != 200 {
		t.Fatalf("balance = %d, want 200 (the duplicate was applied)", got)
	}
}

func TestFailureAfterAckLosesTheMessage(t *testing.T) {
	src := &fakeSource{queue: []Message{{"m-2", 50}}}
	acct := &Account{}
	Run(src, acct, func(Message) error { return errors.New("database down") })
	if len(src.acked) != 1 {
		t.Fatalf("acked = %v, want the message acked before the work", src.acked)
	}
	if got := acct.Balance(); got != 0 {
		t.Fatalf("balance = %d, want 0", got)
	}
	if len(src.queue) != 0 {
		t.Fatal("nothing is left to redeliver: the credit is lost for good")
	}
}

After ​

The same work on a Watermill router. Panics become errors (Recoverer), errors are retried with exponential backoff (Retry), what still fails goes to a poison topic with its reason (PoisonQueue), the correlation ID is copied to every message the handler produces (CorrelationID), and the handler is idempotent on the message UUID.

go
// Package after wires a Watermill router the way production consumers run:
// panics become errors, errors are retried with backoff, exhausted messages go
// to a poison topic, the correlation ID follows the message, and the handler
// is idempotent on the message UUID.
package after

import (
	"encoding/json"
	"errors"
	"sync"
	"time"

	"github.com/ThreeDotsLabs/watermill"
	"github.com/ThreeDotsLabs/watermill/message"
	"github.com/ThreeDotsLabs/watermill/message/router/middleware"
	"github.com/ThreeDotsLabs/watermill/pubsub/gochannel"
)

// Topic names used by the example.
const (
	TopicCredits = "payments.credit.requested"
	TopicApplied = "payments.credit.applied"
	TopicPoison  = "payments.poison"
)

// Credit is the payload of a credit request.
type Credit struct {
	Account string `json:"account"`
	Amount  int    `json:"amount"`
}

// Service holds the business state and the idempotency memory (an inbox).
type Service struct {
	mu       sync.Mutex
	seen     map[string]struct{}
	balances map[string]int
	// Apply is the unit of work; tests make it fail on purpose.
	Apply func(Credit) error
}

// NewService returns a service whose Apply simply adds to the balance.
func NewService() *Service {
	s := &Service{seen: map[string]struct{}{}, balances: map[string]int{}}
	s.Apply = func(c Credit) error {
		s.balances[c.Account] += c.Amount
		return nil
	}
	return s
}

// Balance returns the balance of one account.
func (s *Service) Balance(account string) int {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.balances[account]
}

// HandleCredit is the idempotent handler: the message UUID is the dedup key.
// It returns the "applied" event that the router publishes on success.
func (s *Service) HandleCredit(msg *message.Message) ([]*message.Message, error) {
	var c Credit
	if err := json.Unmarshal(msg.Payload, &c); err != nil {
		return nil, err // a malformed payload will fail every retry: poison queue
	}
	if c.Amount <= 0 {
		return nil, errors.New("amount must be positive")
	}

	s.mu.Lock()
	defer s.mu.Unlock()
	if _, dup := s.seen[msg.UUID]; dup {
		return nil, nil // at-least-once delivery: the second copy is a no-op
	}
	if err := s.Apply(c); err != nil {
		return nil, err
	}
	s.seen[msg.UUID] = struct{}{}

	applied := message.NewMessage(watermill.NewUUID(), msg.Payload)
	return []*message.Message{applied}, nil
}

// NewRouter builds the router. The first middleware added is the outermost:
// poison queue catches what Retry gives up on, Retry wraps Recoverer.
func NewRouter(ps *gochannel.GoChannel, svc *Service, logger watermill.LoggerAdapter) (*message.Router, error) {
	router, err := message.NewRouter(message.RouterConfig{CloseTimeout: 5 * time.Second}, logger)
	if err != nil {
		return nil, err
	}
	poison, err := middleware.PoisonQueue(ps, TopicPoison)
	if err != nil {
		return nil, err
	}
	retry := middleware.Retry{
		MaxRetries:          3,
		InitialInterval:     2 * time.Millisecond,
		MaxInterval:         20 * time.Millisecond,
		Multiplier:          2,
		RandomizationFactor: 0.5,
		Logger:              logger,
	}
	router.AddMiddleware(
		middleware.CorrelationID,
		poison,
		retry.Middleware,
		middleware.Recoverer,
	)
	router.AddHandler("credit", TopicCredits, ps, TopicApplied, ps, svc.HandleCredit)
	return router, nil
}

The tests drive it through GoChannel, an in-memory Pub/Sub, so no broker is needed: a duplicate is applied once, a transient failure succeeds on the third try, an exhausted message arrives on the poison topic with reason_poisoned, and a panic and a malformed payload end up there too.

go
package after

import (
	"errors"
	"sync/atomic"
	"testing"
	"time"

	"github.com/ThreeDotsLabs/watermill"
	"github.com/ThreeDotsLabs/watermill/message"
	"github.com/ThreeDotsLabs/watermill/message/router/middleware"
	"github.com/ThreeDotsLabs/watermill/pubsub/gochannel"
)

func start(t *testing.T, svc *Service) *gochannel.GoChannel {
	t.Helper()
	ps := gochannel.NewGoChannel(gochannel.Config{}, watermill.NopLogger{})
	router, err := NewRouter(ps, svc, watermill.NopLogger{})
	if err != nil {
		t.Fatal(err)
	}
	go func() { _ = router.Run(t.Context()) }()
	select {
	case <-router.Running():
	case <-time.After(2 * time.Second):
		t.Fatal("router did not start")
	}
	t.Cleanup(func() { _ = router.Close() })
	return ps
}

func next(t *testing.T, ch <-chan *message.Message) *message.Message {
	t.Helper()
	select {
	case m := <-ch:
		m.Ack()
		return m
	case <-time.After(2 * time.Second):
		t.Fatal("timed out waiting for a message")
		return nil
	}
}

func TestDuplicateDeliveryIsAppliedOnce(t *testing.T) {
	svc := NewService()
	ps := start(t, svc)
	applied, err := ps.Subscribe(t.Context(), TopicApplied)
	if err != nil {
		t.Fatal(err)
	}

	// The same UUID twice: what a redelivery after a lost ack looks like.
	for range 2 {
		m := message.NewMessage("m-1", []byte(`{"account":"a1","amount":100}`))
		middleware.SetCorrelationID("req-7", m)
		if err := ps.Publish(TopicCredits, m); err != nil {
			t.Fatal(err)
		}
	}

	got := next(t, applied)
	if cid := middleware.MessageCorrelationID(got); cid != "req-7" {
		t.Fatalf("correlation id = %q, want req-7", cid)
	}
	select {
	case <-applied:
		t.Fatal("the duplicate produced a second applied event")
	case <-time.After(100 * time.Millisecond):
	}
	if b := svc.Balance("a1"); b != 100 {
		t.Fatalf("balance = %d, want 100", b)
	}
}

func TestTransientFailureIsRetried(t *testing.T) {
	svc := NewService()
	var calls atomic.Int32
	inner := svc.Apply
	svc.Apply = func(c Credit) error {
		if calls.Add(1) < 3 {
			return errors.New("deadlock detected")
		}
		return inner(c)
	}
	ps := start(t, svc)
	applied, _ := ps.Subscribe(t.Context(), TopicApplied)

	if err := ps.Publish(TopicCredits, message.NewMessage("m-2", []byte(`{"account":"a2","amount":5}`))); err != nil {
		t.Fatal(err)
	}
	next(t, applied)
	if n := calls.Load(); n != 3 {
		t.Fatalf("Apply called %d times, want 3 (two failures, one success)", n)
	}
}

func TestExhaustedRetriesGoToPoisonQueue(t *testing.T) {
	svc := NewService()
	var calls atomic.Int32
	svc.Apply = func(Credit) error { calls.Add(1); return errors.New("permanent failure") }
	ps := start(t, svc)
	poison, _ := ps.Subscribe(t.Context(), TopicPoison)

	if err := ps.Publish(TopicCredits, message.NewMessage("m-3", []byte(`{"account":"a3","amount":9}`))); err != nil {
		t.Fatal(err)
	}
	got := next(t, poison)
	if got.UUID != "m-3" {
		t.Fatalf("poison message uuid = %q", got.UUID)
	}
	if r := got.Metadata.Get(middleware.ReasonForPoisonedKey); r != "permanent failure" {
		t.Fatalf("reason = %q", r)
	}
	if n := calls.Load(); n != 4 {
		t.Fatalf("Apply called %d times, want 4 (first try + MaxRetries 3)", n)
	}
}

func TestRecovererTurnsPanicIntoRetryThenPoison(t *testing.T) {
	svc := NewService()
	svc.Apply = func(Credit) error { panic("nil map") }
	ps := start(t, svc)
	poison, _ := ps.Subscribe(t.Context(), TopicPoison)
	if err := ps.Publish(TopicCredits, message.NewMessage("m-4", []byte(`{"account":"a4","amount":1}`))); err != nil {
		t.Fatal(err)
	}
	got := next(t, poison)
	if r := got.Metadata.Get(middleware.ReasonForPoisonedKey); r == "" {
		t.Fatal("poison message carries no reason")
	}
}

func TestMalformedPayloadIsPoisoned(t *testing.T) {
	ps := start(t, NewService())
	poison, _ := ps.Subscribe(t.Context(), TopicPoison)
	if err := ps.Publish(TopicCredits, message.NewMessage("m-5", []byte(`not json`))); err != nil {
		t.Fatal(err)
	}
	next(t, poison)
}
Watermill router: the middleware onionSubscribertopic inCorrelationIDcopy ID to outputsPoisonQueuecatch final errorRetrybackoff, N triesRecovererpanic to errorHandleridempotentPublisherproduced messagespoison topicreason in metadataAck / Nackafter the chainreturned messageserror after retries

The Go angle ​

Go has no framework that owns the consumer loop, so the shape is explicit: a channel of deliveries, a handler function, a settle decision, a context that says when to stop. That explicitness is the benefit. The decision "ack, requeue or park" is an ordinary function you can table-test (the rabbit.Consumer.Dispatch test below has six rows and needs no broker). Watermill gives you the loop, middleware and many brokers behind one interface; the raw amqp091-go client gives you every AMQP knob and none of the loop. Teams commonly use Watermill where the broker choice may change or where CQRS fits, and the raw client where they need exact control of topology, confirms and dead-lettering. Both approaches appear below because the failure handling is the same idea expressed twice.

Keyword inventory ​

Every term a practitioner meets on this topic, with the section that explains it.

TermSection
event-driven architecture in Go services; publish/subscribeWhy, Pub/Subs
Watermill, message.Message, Publisher, Subscriber, Router, handlersMessage model, Router
middleware: retry, poison queue, correlation ID, throttleMiddleware
CQRS component: command bus, event bus, event processorsCQRS
Pub/Subs: GoChannel, AMQP, Kafka, SQL, NATSPub/Subs
amqp091-go, rabbitmq/amqp091-go: Dial, Channel, ExchangeDeclare, QueueDeclare, QueueBindAMQP topology
Publish with confirms, mandatory, durableEmitter
Consume, Ack/Nack/Reject, prefetch QosConsumer
reconnect handlingReconnecting
emitter/consumer patternsEmitter, Consumer
message envelope: ID, type, occurred_at, traceEnvelope
JSON vs protobuf payloadsEncoding
idempotent consumers, inbox tableInbox
outbox publishing from PostgresOutbox
at-least-once and duplicatesGuarantees
dead-letter exchanges, retries with backoffDLX
ordering per keyOrdering
AWS SQS with aws-sdk-go-v2, ReceiveMessage long polling, visibility timeout, DeleteMessageSQS
FIFO queues, SNS fan-out, DLQ redriveSQS, SNS
RPC between services over messaging, reply queue, correlation IDRPC
when to use gRPC insteadgRPC
graceful shutdown of consumers, context, in-flight drainShutdown
observability, OpenTelemetry messaging spansObservability
testing with GoChannel pub/sub and fakesTesting
Laravel queues/events comparisonPHP/Laravel

The concept catalogue ​

At-least-once delivery and duplicates {#guarantees} Must-know ​

In plain words: The broker would rather deliver a message twice than lose it, so every consumer must expect the same message again.

Common misunderstanding: "I use durable queues and confirms, so there are no duplicates." Those settings prevent loss. Duplicates come from the other side: the consumer finished the work, the network or process died before the ack reached the broker, and the broker (correctly) redelivers. SQS documents the same thing for its standard queues: "Design your applications to be idempotent (they should not be affected adversely when processing the same message more than once)."

Definition: At-least-once: every message is delivered one or more times. At-most-once: zero or one (ack before work). Exactly-once processing is built from at-least-once delivery plus idempotent handling.

consumer                               broker
1  receive msg m-1  <------------------ deliver (tag 7)
2  UPDATE balance (committed)
3  ack(7) ---X network drops
4  ...                                  connection closed, m-1 unacked
5  receive msg m-1  <------------------ redeliver (Redelivered = true)
6  UPDATE balance AGAIN (without an inbox row)

Real scenario: a payment credited twice after a rolling deploy killed the pod between commit and ack; an email sent twice; a stock decrement applied twice; a webhook fired twice.

Cause of duplicateWhereCure
Lost ackConsumer to brokerInbox row / natural idempotency
Consumer timeout (SQS visibility, RabbitMQ consumer timeout)Slow handlerExtend visibility, shorten work, idempotency
Publisher retry after unconfirmed publishPublisher to brokerStable message ID, consumers dedupe
Relay crash after publish, before marking outbox rowOutbox relayStable message ID
Redrive from a DLQOperatorIdempotent handlers

Fix / how to use it: the inbox table for database effects, a natural key (UPDATE ... WHERE status = 'new') for state transitions, and a stable message ID created at the source, never at publish time (a retried publish must carry the same ID).

The Watermill message model {#message} Must-know ​

In plain words: A Watermill message is a small struct with an ID, a bag of string metadata and a byte payload, plus two ways to say "done" or "not done": Ack() and Nack().

Common misunderstanding: "Ack on a Watermill message acknowledges the work for the whole system." It signals the Subscriber, which then settles with the broker according to its implementation. The docs say: "Acks and Nacks are processed by Subscribers (in default implementations, the subscribers are waiting for an Ack or a Nack)." Until you call one, a default subscriber does not hand you the next message.

Definition: message.NewMessage(uuid, payload) returns *message.Message with UUID string, Metadata message.Metadata (a map[string]string with Get/Set) and Payload message.Payload ([]byte). Publisher.Publish(topic string, messages ...*Message) error and Subscriber.Subscribe(ctx, topic) (<-chan *Message, error) are the two interfaces every Pub/Sub implements. Ack() and Nack() return false if the message was already settled; Acked()/Nacked() expose channels. Each message carries a Context(): the subscriber's context, canceled when the message is acked or nacked.

publisher                subscriber (GoChannel)            your handler
1  Publish("orders", m)
2                          m delivered on channel ------->  runs
3                                                          returns nil
4                          <---------------------------  m.Ack()
5  Publish returns (only if BlockPublishUntilSubscriberAck)

Real scenario: a Kafka-to-RabbitMQ migration where only the Pub/Sub constructor changes; a test that swaps the production subscriber for GoChannel; a poison-queue consumer that reads reason_poisoned from Metadata.

PieceWhereNote
UUIDmessage.Message.UUIDUse as the dedup key; keep stable across retries
Metadatastring mapCorrelation ID, type, trace parent, schema version
Payload[]byteAny encoding; see encoding
Context()derived from the subscriptionCanceled on Ack or Nack; SetContext lets middleware add spans

Fix / how to use it: put the identity and routing facts in Metadata (see envelope) and keep the payload free of transport concerns. Never share one *Message across goroutines after Ack.

Router and handlers {#router} Must-know ​

In plain words: The router connects a topic to a function, runs that function for each message, publishes what it returns and acks or nacks for you.

Common misunderstanding: "Returning an error just logs it." Returning an error Nacks the message, so the subscriber redelivers it, unless a middleware (retry, poison queue) intercepts the error first. The router recovers a panic and nacks too, but only as the last resort; install Recoverer to turn panics into retryable errors.

Definition: message.NewRouter(RouterConfig{CloseTimeout}, logger); AddHandler(name, subscribeTopic, subscriber, publishTopic, publisher, HandlerFunc) where HandlerFunc is func(*Message) ([]*Message, error); AddConsumerHandler (alias AddNoPublisherHandler) takes a func(*Message) error. Run(ctx) starts every handler; Running() is closed when ready; Close() stops and waits for in-flight handlers up to CloseTimeout. Middleware added with AddMiddleware: "first added middlewares should be executed first (so should be at the top of call stack)" in the source.

1  Run(ctx)            -> subscribe every handler's topic
2  msg arrives         -> go handleMessage(msg)
3  middleware chain    -> CorrelationID -> PoisonQueue -> Retry -> Recoverer -> handler
4  handler returns (msgs, nil)  -> publish msgs, then msg.Ack()
5  handler returns (_, err)     -> msg.Nack()  (redelivery)
6  Close()             -> stop subscribers, wait for running handlers

Real scenario: a billing handler that consumes orders.placed and publishes invoices.created; a notification consumer with no output topic; a handler added at runtime with AddHandler followed by RunHandlers.

Router callEffectGotcha
AddHandlerConsume, transform, publishDuplicate handler names panic (DuplicateHandlerNameError)
AddConsumerHandlerConsume onlyNo publisher needed
AddMiddlewareRouter-level wrappingOrder matters
Handler.AddMiddlewarePer-handlerApplies to that handler only
Run(ctx)Blocks until closedRun in a goroutine, wait on Running()
Close()Graceful stopReturns "router close timeout" if handlers overrun

Fix / how to use it: After above is the template: one NewRouter function that takes the Pub/Sub and returns the router, so tests and main build the same thing.

Router middleware: retry, poison queue, correlation ID, throttle {#middleware} Must-know ​

In plain words: Middleware wraps the handler the way HTTP middleware wraps an HTTP handler, so cross-cutting failure policy lives in one place.

Common misunderstanding: "Retry then poison queue means three attempts total." middleware.Retry{MaxRetries: 3} means the first attempt plus up to three retries: four calls. The test asserts exactly that (Apply called 4 times). Also, PoisonQueue publishes the failed message and then returns nil, so the original is acked; the failure moves, it does not disappear.

Definition: the middleware that ships in message/router/middleware:

MiddlewareWhat it doesKey knobs
RetryRe-runs the handler with exponential backoffMaxRetries, InitialInterval, MaxInterval, Multiplier, RandomizationFactor, MaxElapsedTime, ShouldRetry, OnRetryHook
PoisonQueue, PoisonQueueWithFilterPublishes an unprocessable message to another topic with metadata reason_poisoned, topic_poisoned, handler_poisoned, subscriber_poisonedTopic; filter on which errors
CorrelationID + SetCorrelationIDCopies the correlation ID from the input to all produced messagesCall SetCorrelationID where the message enters
ThrottleAt most count messages per duration, shared by handlersNewThrottle(10, time.Second)
TimeoutCancels the message context after a durationHandler must honour ctx
RecovererTurns a panic into RecoveredPanicErrorPut it innermost so Retry sees it
DuplicatorRuns the handler twice (a test aid for idempotency)Use in tests only
1  msg m-3 arrives
2  Retry: attempt 1 fails, wait ~2 ms
3  Retry: attempt 2 fails, wait ~4 ms
4  Retry: attempt 3 fails, wait ~8 ms
5  Retry: attempt 4 fails, give up -> error propagates
6  PoisonQueue: publish m-3 to payments.poison, set reason_poisoned
7  PoisonQueue returns nil -> router acks the original

Real scenario: a handler calling a flaky partner API gets Retry with ShouldRetry rejecting 4xx errors; a consumer that fans out to a rate-limited SMS gateway gets Throttle; an ops dashboard shows the poison topic depth.

Fix / how to use it: order is CorrelationID, PoisonQueue, Retry, Recoverer, handler (outermost first). Retry only errors that can heal; return a permanent error type that ShouldRetry recognises. In-handler retry holds the delivery, so cap total time (MaxElapsedTime) below the broker's own timeout (SQS visibility timeout, RabbitMQ consumer timeout).

The CQRS component {#cqrs} Important ​

In plain words: CQRS splits "do this" (a command, one handler) from "this happened" (an event, any number of handlers), and Watermill gives you a typed bus for each.

Common misunderstanding: "A command bus is a queue of events." A command is addressed to exactly one handler; an event is a fact that zero or more handlers react to. Neither bus is synchronous: Send and Publish return when the message was published (and can return an error if publishing fails), while a command handler runs later, in another goroutine or process, so its failure reaches the sender only as a redelivery, never as the return value of Send. The command_handler.go source comment says it directly: "In contrast to EventHandler, every Command must have only one CommandHandler."

Definition: component github.com/ThreeDotsLabs/watermill/components/cqrs. CommandBus.Send(ctx, cmd) and EventBus.Publish(ctx, event) marshal with a CommandEventMarshaler (cqrs.JSONMarshaler, plus protobuf variants), set a name metadata field from the type, and publish to a topic produced by GeneratePublishTopic. CommandProcessor and EventProcessor register typed handlers (cqrs.NewCommandHandler, cqrs.NewEventHandler generics) on a router and subscribe through a SubscriberConstructor. AckCommandHandlingErrors and AckOnUnknownEvent control what happens on handler errors and unknown types.

1  commands.Send(ctx, &BookRoom{r-12, 2})     -> topic commands.BookRoom
2  CommandProcessor -> BookRoomHandler.Handle  -> decides, persists
3  handler: events.Publish(ctx, &RoomBooked)   -> topic events.RoomBooked
4  EventProcessor   -> every registered EventHandler for RoomBooked (fan-out)

Real scenario: booking, ordering and ticketing systems where the command validates and the events feed billing, notifications and search indexing.

go
// Package cqrsdemo shows Watermill's CQRS component: a command bus that sends
// one command to exactly one handler, and an event bus that fans an event
// out to every subscribed event handler.
package cqrsdemo

import (
	"context"
	"errors"
	"fmt"

	"github.com/ThreeDotsLabs/watermill"
	"github.com/ThreeDotsLabs/watermill/components/cqrs"
	"github.com/ThreeDotsLabs/watermill/message"
	"github.com/ThreeDotsLabs/watermill/pubsub/gochannel"
)

// BookRoom is a command: an instruction with one owner.
type BookRoom struct {
	RoomID string
	Guests int
}

// RoomBooked is an event: a fact other parts may react to.
type RoomBooked struct {
	RoomID string
	Guests int
}

// ErrInvalidCommand is returned to the sender when validation fails before Send.
var ErrInvalidCommand = errors.New("cqrsdemo: invalid command")

// Validate is the synchronous check. An asynchronous command bus only reports
// publish errors to the sender; an error inside the handler happens later, in
// another process, and shows up as a redelivery.
func (b BookRoom) Validate() error {
	if b.RoomID == "" || b.Guests <= 0 {
		return fmt.Errorf("%w: room %q, guests %d", ErrInvalidCommand, b.RoomID, b.Guests)
	}
	return nil
}

// System bundles the buses so callers (and tests) can send and observe.
type System struct {
	Commands *cqrs.CommandBus
	Events   *cqrs.EventBus
	Router   *message.Router
}

// Book validates first, then sends: the only way the sender learns about a
// business-rule failure. Send itself fails only when publishing fails.
func (s *System) Book(ctx context.Context, cmd BookRoom) error {
	if err := cmd.Validate(); err != nil {
		return err
	}
	return s.Commands.Send(ctx, &cmd)
}

// Wire builds the buses and registers the handlers on a new router. Topics are
// derived from the type name: command and event types never share a topic.
func Wire(ps *gochannel.GoChannel, onBooked ...func(context.Context, *RoomBooked) error) (*System, error) {
	logger := watermill.NopLogger{}
	marshaler := cqrs.JSONMarshaler{GenerateName: cqrs.StructName}

	router, err := message.NewRouter(message.RouterConfig{}, logger)
	if err != nil {
		return nil, err
	}

	events, err := cqrs.NewEventBusWithConfig(ps, cqrs.EventBusConfig{
		GeneratePublishTopic: func(p cqrs.GenerateEventPublishTopicParams) (string, error) {
			return "events." + p.EventName, nil
		},
		Marshaler: marshaler,
		Logger:    logger,
	})
	if err != nil {
		return nil, err
	}
	commands, err := cqrs.NewCommandBusWithConfig(ps, cqrs.CommandBusConfig{
		GeneratePublishTopic: func(p cqrs.CommandBusGeneratePublishTopicParams) (string, error) {
			return "commands." + p.CommandName, nil
		},
		Marshaler: marshaler,
		Logger:    logger,
	})
	if err != nil {
		return nil, err
	}

	// The command handler owns the decision and emits the event.
	bookRoom := cqrs.NewCommandHandler("BookRoomHandler", func(ctx context.Context, cmd *BookRoom) error {
		// Defence in depth: a malformed command that bypassed Book fails here, and
		// the error makes the router nack, so the broker redelivers it.
		if err := cmd.Validate(); err != nil {
			return err
		}
		return events.Publish(ctx, &RoomBooked{RoomID: cmd.RoomID, Guests: cmd.Guests})
	})

	cp, err := cqrs.NewCommandProcessorWithConfig(router, cqrs.CommandProcessorConfig{
		GenerateSubscribeTopic: func(p cqrs.CommandProcessorGenerateSubscribeTopicParams) (string, error) {
			return "commands." + p.CommandName, nil
		},
		SubscriberConstructor: func(cqrs.CommandProcessorSubscriberConstructorParams) (message.Subscriber, error) {
			return ps, nil
		},
		Marshaler: marshaler,
		Logger:    logger,
	})
	if err != nil {
		return nil, err
	}
	if err := cp.AddHandlers(bookRoom); err != nil {
		return nil, err
	}

	ep, err := cqrs.NewEventProcessorWithConfig(router, cqrs.EventProcessorConfig{
		GenerateSubscribeTopic: func(p cqrs.EventProcessorGenerateSubscribeTopicParams) (string, error) {
			return "events." + p.EventName, nil
		},
		SubscriberConstructor: func(cqrs.EventProcessorSubscriberConstructorParams) (message.Subscriber, error) {
			return ps, nil
		},
		Marshaler: marshaler,
		Logger:    logger,
	})
	if err != nil {
		return nil, err
	}
	for i, fn := range onBooked {
		h := cqrs.NewEventHandler(fmt.Sprintf("OnRoomBooked-%d", i), fn)
		if err := ep.AddHandlers(h); err != nil {
			return nil, err
		}
	}
	return &System{Commands: commands, Events: events, Router: router}, nil
}
go
package cqrsdemo

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

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

func TestCommandProducesEventForEveryEventHandler(t *testing.T) {
	ps := gochannel.NewGoChannel(gochannel.Config{}, watermill.NopLogger{})
	got1 := make(chan RoomBooked, 1)
	got2 := make(chan RoomBooked, 1)
	sys, err := Wire(ps,
		func(_ context.Context, e *RoomBooked) error { got1 <- *e; return nil },
		func(_ context.Context, e *RoomBooked) error { got2 <- *e; return nil },
	)
	if err != nil {
		t.Fatal(err)
	}
	go func() { _ = sys.Router.Run(t.Context()) }()
	<-sys.Router.Running()
	t.Cleanup(func() { _ = sys.Router.Close() })

	if err := sys.Commands.Send(t.Context(), &BookRoom{RoomID: "r-12", Guests: 2}); err != nil {
		t.Fatal(err)
	}
	for i, ch := range []chan RoomBooked{got1, got2} {
		select {
		case e := <-ch:
			if e.RoomID != "r-12" || e.Guests != 2 {
				t.Fatalf("handler %d got %+v", i, e)
			}
		case <-time.After(2 * time.Second):
			t.Fatalf("event handler %d never saw the event: events fan out to all handlers", i)
		}
	}
}

func TestEventIsNotACommand(t *testing.T) {
	ps := gochannel.NewGoChannel(gochannel.Config{}, watermill.NopLogger{})
	seen := make(chan struct{}, 1)
	sys, err := Wire(ps, func(context.Context, *RoomBooked) error { seen <- struct{}{}; return nil })
	if err != nil {
		t.Fatal(err)
	}
	go func() { _ = sys.Router.Run(t.Context()) }()
	<-sys.Router.Running()
	t.Cleanup(func() { _ = sys.Router.Close() })

	// Publishing the event directly reaches the event handler, not the command handler.
	if err := sys.Events.Publish(t.Context(), &RoomBooked{RoomID: "r-1", Guests: 1}); err != nil {
		t.Fatal(err)
	}
	select {
	case <-seen:
	case <-time.After(2 * time.Second):
		t.Fatal("event handler did not run")
	}
}

func TestInvalidCommandIsRejectedBeforeSend(t *testing.T) {
	ps := gochannel.NewGoChannel(gochannel.Config{}, watermill.NopLogger{})
	events := make(chan struct{}, 1)
	sys, err := Wire(ps, func(context.Context, *RoomBooked) error { events <- struct{}{}; return nil })
	if err != nil {
		t.Fatal(err)
	}
	go func() { _ = sys.Router.Run(t.Context()) }()
	<-sys.Router.Running()
	t.Cleanup(func() { _ = sys.Router.Close() })

	if err := sys.Book(t.Context(), BookRoom{RoomID: "r-1", Guests: 0}); !errors.Is(err, ErrInvalidCommand) {
		t.Fatalf("Book = %v, want ErrInvalidCommand returned to the sender", err)
	}
	select {
	case <-events:
		t.Fatal("an invalid command produced an event")
	case <-time.After(100 * time.Millisecond):
	}
}
QuestionCommand busEvent bus
Addressed toOne handlerZero to many handlers
NameImperative (BookRoom)Past tense (RoomBooked)
Error returned by the callOnly if publishing failsOnly if publishing fails
Where a business rule is checkedBefore Send (the demo's Book), and again in the handlerIn the handler; an event describes something that already happened
Handler failureNack, redelivery (the sender never sees it)Nack, redelivery per handler
Topiccommands.<Name> hereevents.<Name> here

Fix / how to use it: validate before Send when the caller needs an immediate rejection (the snippet's System.Book returns ErrInvalidCommand synchronously and publishes nothing; its test proves no event follows), keep the handler check as defence, and derive topics from type names (as the snippet does) so a rename is a compile-time change, and give each event handler its own queue (consumer group) so one slow handler does not block another.

Pub/Subs and the choice of broker {#pubsubs} Must-know ​

In plain words: A Pub/Sub is "a Publisher and a Subscriber for one broker". Watermill ships the interfaces and a set of implementations; you pick by what you already run.

Common misunderstanding: "Watermill's topic is the AMQP topic exchange." The watermill-amqp docs warn: "Watermill's topic is not mapped directly to the AMQP's topic exchange type. It is used to generate exchange name, routing key and queue name." The mapping is configuration (Exchange.GenerateName, Queue.GenerateName, Publish.GenerateRoutingKey).

Definition: the implementations used in this chapter:

Pub/SubModuleUse it forOrdering
GoChannelwatermill/pubsub/gochannelTests and in-process fan-outPer topic (not guaranteed when Persistent)
AMQPwatermill-amqp/v3RabbitMQPer queue (its characteristics table: ExactlyOnceDelivery no, GuaranteedOrder yes)
Kafkawatermill-kafkaPartitioned logPer partition
SQLwatermill-sqlPostgreSQL or MySQL as a queue, and the outbox forwarderPer offset
NATSwatermill-natsNATS JetStreamPer stream
AWS SNS/SQSwatermill-aws (separate repository, not read in depth here)SQS consumers and SNS publishingStandard queues: none

The GoChannel doc comment says "GoChannel is the simplest Pub/Sub implementation. It is based on Golang's channels which are sent within the process." Its Config has OutputChannelBuffer, Persistent (new subscribers receive earlier messages), BlockPublishUntilSubscriberAck (makes Publish wait for the Ack, ideal in tests) and PreserveContext.

1  AMQP durable pub/sub config:  topic "orders.placed"
2  exchange   = "orders.placed"  (fanout, durable)
3  queue      = "orders.placed_billing" (durable, one per service via suffix)
4  routing key = ""
5  every service with its own suffix gets its own copy

Real scenario: unit tests on GoChannel, staging on RabbitMQ, production moving to Kafka for replay without touching handlers; the SQL Pub/Sub as the transport for an outbox forwarder.

NeedChoice
Tests without a brokerGoChannel
Routing keys, per-message TTL, priorities, work queuesRabbitMQ (raw client, or Watermill AMQP)
Replay, huge throughput, partitionsKafka
One more database, small scale, transactional enqueueSQL Pub/Sub
Lightweight subjects, request-reply built inNATS
Managed queue, no serversSQS (+ SNS for fan-out)

Fix / how to use it: build a NewWatermillPubSub constructor like the one in rabbit/watermill.go (durable fanout exchange per topic, one queue per service via GenerateQueueNameTopicNameWithSuffix, Publish.ConfirmDelivery, Mandatory, reconnect config, prefetch). Constructing it dials the broker, so it is compiled and not run here.

go
package rabbit

import (
	"github.com/ThreeDotsLabs/watermill"
	wamqp "github.com/ThreeDotsLabs/watermill-amqp/v3/pkg/amqp"
)

// NewWatermillPubSub builds a Watermill AMQP publisher and subscriber for one
// service. Pub/sub style: one fanout exchange per topic and one durable queue
// per (topic, service), so every service gets its own copy of every event.
// Expected, not run: constructing them dials the broker.
func NewWatermillPubSub(uri, serviceName string, logger watermill.LoggerAdapter) (*wamqp.Publisher, *wamqp.Subscriber, error) {
	cfg := wamqp.NewDurablePubSubConfig(uri, wamqp.GenerateQueueNameTopicNameWithSuffix(serviceName))
	cfg.Connection.Reconnect = wamqp.DefaultReconnectConfig()
	cfg.Publish.ConfirmDelivery = true
	cfg.Publish.Mandatory = true
	cfg.Consume.Qos.PrefetchCount = 10

	pub, err := wamqp.NewPublisher(cfg, logger)
	if err != nil {
		return nil, nil, err
	}
	sub, err := wamqp.NewSubscriber(cfg, logger)
	if err != nil {
		_ = pub.Close()
		return nil, nil, err
	}
	return pub, sub, nil
}

Message envelope: ID, type, occurred_at, trace {#envelope} Must-know ​

In plain words: An envelope is the stable header every event carries so any consumer can route, deduplicate, order and trace it without reading the body.

Common misunderstanding: "The timestamp is when the message was sent." occurred_at is when the fact happened in the business (the order was placed); the publish time can be minutes later after an outbox delay. Use occurred_at for ordering decisions in projections, not the arrival time.

Definition: the EIP "Envelope Wrapper" idea, in practice a fixed set of fields:

FieldCarried asPurpose
IDmessage UUID / AMQP message-id / SQS MessageId plus a body fieldDedup key; stable across retries
typemetadata type, e.g. orders.order_placed.v1Routing and decoding; include the schema version
occurred_atRFC 3339 with nanoseconds, UTCBusiness time
trace (traceparent)W3C Trace ContextLink producer and consumer spans
correlation_idmetadataTie a request, its events and replies
schema_versionmetadataLet consumers refuse or upcast
go
// Package envelope defines the message envelope used between services: a
// stable header (ID, type, occurred_at, trace) around a payload that can
// evolve. The header travels as broker metadata, the payload as the body.
package envelope

import (
	"encoding/json"
	"errors"
	"fmt"
	"time"

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

// Metadata keys on the wire (AMQP headers, SQS message attributes, Kafka headers).
const (
	KeyType          = "type"
	KeyOccurredAt    = "occurred_at"
	KeyTraceParent   = "traceparent"
	KeyCorrelationID = "correlation_id"
	KeyVersion       = "schema_version"
)

// Envelope is the in-memory view of one message.
type Envelope struct {
	ID            string          // unique per message: the dedup key
	Type          string          // "orders.order_placed.v1": routing and decoding
	OccurredAt    time.Time       // when the fact happened, not when it was sent
	TraceParent   string          // W3C trace context, so consumers continue the trace
	CorrelationID string          // ties a request, its events and replies together
	Version       int             // payload schema version
	Payload       json.RawMessage // JSON body
}

// ErrUnknownVersion is returned for payloads newer than this consumer knows.
var ErrUnknownVersion = errors.New("envelope: unsupported schema version")

// New builds an envelope around a typed payload.
func New(id, typ string, occurredAt time.Time, version int, payload any) (Envelope, error) {
	body, err := json.Marshal(payload)
	if err != nil {
		return Envelope{}, fmt.Errorf("envelope: marshal %s: %w", typ, err)
	}
	return Envelope{ID: id, Type: typ, OccurredAt: occurredAt.UTC(), Version: version, Payload: body}, nil
}

// ToMessage maps the envelope onto a Watermill message: ID becomes the UUID,
// the rest goes to metadata, the payload is the body.
func (e Envelope) ToMessage() *message.Message {
	m := message.NewMessage(e.ID, message.Payload(e.Payload))
	m.Metadata.Set(KeyType, e.Type)
	m.Metadata.Set(KeyOccurredAt, e.OccurredAt.Format(time.RFC3339Nano))
	m.Metadata.Set(KeyVersion, fmt.Sprint(e.Version))
	if e.TraceParent != "" {
		m.Metadata.Set(KeyTraceParent, e.TraceParent)
	}
	if e.CorrelationID != "" {
		m.Metadata.Set(KeyCorrelationID, e.CorrelationID)
	}
	return m
}

// FromMessage is the inverse of ToMessage.
func FromMessage(m *message.Message) (Envelope, error) {
	at, err := time.Parse(time.RFC3339Nano, m.Metadata.Get(KeyOccurredAt))
	if err != nil {
		return Envelope{}, fmt.Errorf("envelope: bad occurred_at: %w", err)
	}
	var v int
	if _, err := fmt.Sscan(m.Metadata.Get(KeyVersion), &v); err != nil {
		return Envelope{}, fmt.Errorf("envelope: bad schema_version: %w", err)
	}
	return Envelope{
		ID:            m.UUID,
		Type:          m.Metadata.Get(KeyType),
		OccurredAt:    at,
		TraceParent:   m.Metadata.Get(KeyTraceParent),
		CorrelationID: m.Metadata.Get(KeyCorrelationID),
		Version:       v,
		Payload:       json.RawMessage(m.Payload),
	}, nil
}

// Decode unmarshals the payload into out. A consumer that only knows
// versions up to maxVersion refuses newer ones instead of guessing. Unknown
// JSON fields are ignored on purpose, so adding a field is a compatible change.
func (e Envelope) Decode(maxVersion int, out any) error {
	if e.Version > maxVersion {
		return fmt.Errorf("%w: got %d, know %d", ErrUnknownVersion, e.Version, maxVersion)
	}
	return json.Unmarshal(e.Payload, out)
}
go
package envelope

import (
	"errors"
	"testing"
	"time"
)

type orderPlaced struct {
	OrderID string `json:"order_id"`
	Total   int    `json:"total_cents"`
}

func TestRoundTripThroughMessage(t *testing.T) {
	at := time.Date(2026, 11, 28, 10, 30, 0, 123, time.UTC)
	env, err := New("e-1", "orders.order_placed.v1", at, 1, orderPlaced{"o-9", 4200})
	if err != nil {
		t.Fatal(err)
	}
	env.TraceParent = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
	env.CorrelationID = "req-1"

	back, err := FromMessage(env.ToMessage())
	if err != nil {
		t.Fatal(err)
	}
	if back.ID != "e-1" || back.Type != env.Type || !back.OccurredAt.Equal(at) ||
		back.TraceParent != env.TraceParent || back.CorrelationID != "req-1" || back.Version != 1 {
		t.Fatalf("round trip lost header data: %+v", back)
	}
	var p orderPlaced
	if err := back.Decode(1, &p); err != nil || p.OrderID != "o-9" || p.Total != 4200 {
		t.Fatalf("payload = %+v, err = %v", p, err)
	}
}

func TestNewerVersionIsRefused(t *testing.T) {
	env, _ := New("e-2", "orders.order_placed.v2", time.Now(), 2, orderPlaced{"o-1", 1})
	var p orderPlaced
	if err := env.Decode(1, &p); !errors.Is(err, ErrUnknownVersion) {
		t.Fatalf("err = %v, want ErrUnknownVersion", err)
	}
}

func TestUnknownFieldsAreIgnored(t *testing.T) {
	env := Envelope{ID: "e-3", Version: 1, Payload: []byte(`{"order_id":"o-3","total_cents":7,"coupon":"X"}`)}
	var p orderPlaced
	if err := env.Decode(1, &p); err != nil || p.OrderID != "o-3" {
		t.Fatalf("added field broke the old consumer: %v", err)
	}
}

func TestMissingHeadersAreErrors(t *testing.T) {
	env, _ := New("e-4", "t", time.Now(), 1, struct{}{})
	m := env.ToMessage()
	m.Metadata.Set(KeyOccurredAt, "yesterday")
	if _, err := FromMessage(m); err == nil {
		t.Fatal("expected an error for a malformed occurred_at")
	}
}

Real scenario: a consumer that sees orders.order_placed.v2 while it knows version 1 refuses the message (permanent error, to the parking lot) instead of misreading it; an analytics service orders by occurred_at.

Fix / how to use it: put header fields in transport metadata (AMQP headers and properties, SQS message attributes, Kafka headers) so the body stays the payload. Adding a JSON field is a compatible change; renaming or retyping is a new version.

JSON vs protobuf payloads {#encoding} Important ​

In plain words: The payload is just bytes; the choice is readable and loose (JSON) or compact and strict (protobuf).

Common misunderstanding: "Protobuf is always better for events." It is smaller and has a schema, but you need a registry or shared .proto repository and tooling to read a message in a dead-letter queue. JSON is debuggable with jq at 3 a.m.

ConcernJSONProtobuf
Size and speedLarger, slowerSmaller, faster
SchemaConvention or JSON Schema.proto with field numbers
EvolveAdd fields; consumers ignore unknownAdd fields with new numbers; never reuse numbers
Debug a parked messageReadableNeeds the schema
Watermillcqrs.JSONMarshalercqrs.ProtobufMarshaler
Content-Type to setapplication/jsonapplication/x-protobuf

Fix / how to use it: default to JSON for domain events between your own services; use protobuf where throughput or a cross-team contract justifies the tooling, and always carry the type and version in the envelope. See gRPC & Protobuf in Go for the schema workflow.

RabbitMQ topology in Go: Dial, Channel, ExchangeDeclare, QueueDeclare, QueueBind {#amqp-topology} Must-know ​

In plain words: Before anything flows you declare the plumbing: exchanges (where publishers send), queues (where consumers read) and bindings (which messages go from one to the other). Declaring is idempotent when the arguments match.

Common misunderstanding: "ExchangeDeclare creates a new exchange every time." If it exists with the same arguments it is a no-op; with different arguments the broker closes the channel with 406 PRECONDITION_FAILED. Changing a queue argument (say, adding a dead-letter exchange) means a new queue name or a policy, not a redeclare.

Definition: rabbitmq/amqp091-go: Dial (amqp.Dial(url) or amqp.DialConfig) returns a *amqp.Connection; conn.Channel() returns a *amqp.Channel, the unit you publish and consume on (channels are cheap, connections are not; do not share one channel between goroutines for publishing). The calls: ch.ExchangeDeclare(name, kind, durable, autoDelete, internal, noWait, args), ch.QueueDeclare(name, durable, autoDelete, exclusive, noWait, args), ch.QueueBind(queue, key, exchange, noWait, args). durable makes the exchange or queue survive a broker restart; it does not make messages persistent (that is the publishing DeliveryMode).

1  conn := amqp.Dial("amqp://...")
2  ch   := conn.Channel()
3  ch.ExchangeDeclare("orders", "topic", durable=true)
4  ch.QueueDeclare("orders.created.q", durable=true, args{x-queue-type: quorum, x-dead-letter-exchange: orders.retry})
5  ch.QueueBind("orders.created.q", "orders.created", "orders")
6  publish("orders", key "orders.created") -> routed by the binding -> queue

Real scenario: every service declares the topology it consumes at startup (the owner of the queue declares it); a deploy that changes x-message-ttl fails with 406 until the old queue is deleted or renamed.

Exchange typeRoutes byTypical use
directExact routing keyWork queues, tutorial 4
fanoutIgnores the keyPub/sub, Watermill AMQP default
topicKey pattern with * and #Domain events (orders.created, orders.*)
headersHeader matchRare
Queue type (x-queue-type)Property
classicDefault; single node data
quorumReplicated with Raft; the recommended durable queue. Dead-lettering is at-most-once by default; it becomes at-least-once only with x-dead-letter-strategy=at-least-once and x-overflow=reject-publish (plus a dead-letter exchange)
streamAppend-only log with replay

Fix / how to use it: keep the declaration in one function that takes a small Declarer interface (a real *amqp.Channel satisfies it), so a test can record the calls and assert the arguments, as the topology test does.

go
// Package rabbit holds the RabbitMQ side: topology declaration, an emitter that
// waits for publisher confirms, a consumer that maps handler results onto
// Ack/Nack/Reject, and a reconnect supervisor. The parts that need a broker
// are thin adapters; the decisions are in plain functions that tests drive
// with fakes.
package rabbit

import (
	"fmt"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
)

// Declarer is the part of *amqp.Channel used to declare topology. A real
// *amqp.Channel satisfies it.
type Declarer interface {
	ExchangeDeclare(name, kind string, durable, autoDelete, internal, noWait bool, args amqp.Table) error
	QueueDeclare(name string, durable, autoDelete, exclusive, noWait bool, args amqp.Table) (amqp.Queue, error)
	QueueBind(name, key, exchange string, noWait bool, args amqp.Table) error
}

var _ Declarer = (*amqp.Channel)(nil)

// Topology is one work queue with a delayed-retry path and a parking queue.
//
//	orders (topic) --orders.created--> orders.created.q --reject--> orders.retry (fanout)
//	                                          ^                          |
//	                                          |                  orders.created.retry.q (TTL)
//	                                          +---- expires, dead-letters back to orders
//	orders.dead (fanout) --> orders.created.dead.q   (parking lot, inspected by a human)
type Topology struct {
	Exchange   string        // main topic exchange, e.g. "orders"
	RoutingKey string        // e.g. "orders.created"
	Queue      string        // work queue, e.g. "orders.created.q"
	RetryDelay time.Duration // how long a failed message waits before redelivery
}

func (t Topology) retryExchange() string { return t.Exchange + ".retry" }
func (t Topology) deadExchange() string  { return t.Exchange + ".dead" }
func (t Topology) retryQueue() string    { return t.Queue + ".retry" }
func (t Topology) deadQueue() string     { return t.Queue + ".dead" }

// Declare creates exchanges, queues and bindings. It is idempotent: declaring
// the same thing twice with the same arguments is a no-op, with different
// arguments the broker answers 406 PRECONDITION_FAILED.
func (t Topology) Declare(ch Declarer) error {
	for _, ex := range []struct{ name, kind string }{
		{t.Exchange, amqp.ExchangeTopic},
		{t.retryExchange(), amqp.ExchangeFanout},
		{t.deadExchange(), amqp.ExchangeFanout},
	} {
		if err := ch.ExchangeDeclare(ex.name, ex.kind, true, false, false, false, nil); err != nil {
			return fmt.Errorf("declare exchange %s: %w", ex.name, err)
		}
	}

	queues := []struct {
		name string
		args amqp.Table
	}{
		// Work queue: a rejected message is dead-lettered to the retry exchange.
		// Quorum queues dead-letter at-most-once by default, so a message can be
		// lost between the two queues. at-least-once needs overflow=reject-publish.
		{t.Queue, amqp.Table{
			amqp.QueueTypeArg:        amqp.QueueTypeQuorum,
			"x-dead-letter-exchange": t.retryExchange(),
			"x-dead-letter-strategy": "at-least-once",
			"x-overflow":             "reject-publish",
		}},
		// Retry queue: nobody consumes it; the TTL expires and the message is
		// dead-lettered back to the main exchange with its original routing key.
		{t.retryQueue(), amqp.Table{
			amqp.QueueTypeArg:        amqp.QueueTypeQuorum,
			"x-message-ttl":          t.RetryDelay.Milliseconds(),
			"x-dead-letter-exchange": t.Exchange,
			"x-dead-letter-strategy": "at-least-once",
			"x-overflow":             "reject-publish",
		}},
		{t.deadQueue(), amqp.Table{amqp.QueueTypeArg: amqp.QueueTypeQuorum}},
	}
	for _, q := range queues {
		if _, err := ch.QueueDeclare(q.name, true, false, false, false, q.args); err != nil {
			return fmt.Errorf("declare queue %s: %w", q.name, err)
		}
	}

	for _, b := range []struct{ queue, key, exchange string }{
		{t.Queue, t.RoutingKey, t.Exchange},
		{t.retryQueue(), "", t.retryExchange()},
		{t.deadQueue(), "", t.deadExchange()},
	} {
		if err := ch.QueueBind(b.queue, b.key, b.exchange, false, nil); err != nil {
			return fmt.Errorf("bind %s to %s: %w", b.queue, b.exchange, err)
		}
	}
	return nil
}

// DeadExchange is where a consumer parks a message it gave up on.
func (t Topology) DeadExchange() string { return t.deadExchange() }
Delayed retry with a TTL queue and a parking lotorders.created.qwork queue (quorum)Consumerhandler returns errororders.retryfanout exchangeretry.q (TTL 5 s)no consumersorders (topic)main exchangedead.qafter MaxAttemptsdeliverNack requeue=falseTTL expires, dead-letterrouting key againx-death count >= MaxAttempts: park, then Ack

The emitter: publish with confirms, mandatory, durable {#emitter} Must-know ​

In plain words: An emitter publishes an event and returns only after the broker says "I have it". Without that, Publish returning means only "I wrote bytes to a socket".

Common misunderstanding: "PublishWithContext returned nil, so the message is safe." It means the frame was handed to the connection. On a channel in confirm mode (ch.Confirm(false)) the broker later sends basic.ack or basic.nack; only that is the confirmation. A message published as mandatory that matches no queue is returned with basic.return and then still confirmed ("the basic.return is sent to the client before basic.ack"), so a confirm alone would report success for a message nobody will ever receive. RabbitMQ's publisher docs: if a message cannot be routed and "the publisher set the mandatory message property to false (this is the default), the message is discarded or republished to an alternate exchange".

Definition: ch.PublishWithDeferredConfirmWithContext(ctx, exchange, key, mandatory, immediate, amqp.Publishing{...}) returns *amqp.DeferredConfirmation; its WaitContext(ctx) yields (acked bool, err error). Publishing fields that matter: DeliveryMode: amqp.Persistent, ContentType, MessageId, Type, Timestamp, CorrelationId, ReplyTo, Headers, Body. ch.NotifyReturn delivers unroutable messages. NewChannelPublisher registers for them and matches each return to its confirm by MessageId, so Emit returns ErrUnroutable for a confirmed-but-returned message (the test uses a fake confirmation that reports exactly that, and a tracker test matches returns by ID). The emitter below hides the real type behind a Confirmation interface (a *amqp.DeferredConfirmation cannot be faked directly), so the decision logic is tested.

1  ch.Confirm(false)                          // once per channel
2  PublishDeferred(exchange, key, mandatory=true, persistent)  -> DeferredConfirmation
3  WaitContext(timeout)
4     broker: basic.ack   -> acked=true  -> Emit returns nil
5     broker: basic.return, then basic.ack -> ErrUnroutable (mandatory, no queue matched)
6     broker: basic.nack  -> acked=false -> ErrNacked
7     no answer           -> ErrUnconfirmed (message MAY exist: retry with the same ID)

Real scenario: an order service whose Emit returns ErrUnconfirmed during a broker failover and retries with the same message ID; a typo in a routing key caught by mandatory returns instead of silently dropping events.

SettingWhat it protectsCost
Durable queueQueue survives restartNone
DeliveryMode: PersistentMessage written to diskThroughput
Publisher confirmYou know the broker took responsibilityLatency; batch or pipeline confirms
mandatory: trueUnroutable message returned, not droppedEmit reports ErrUnroutable; needs NewChannelPublisher
Quorum queueConfirm after replication to a majorityReplication latency

Fix / how to use it: confirm every business event; for throughput issue many publishes and wait for their confirmations concurrently instead of one by one (see publisher confirms). Do not use AMQP transactions (Tx); confirms are far cheaper.

go
package rabbit

import (
	"context"
	"errors"
	"fmt"
	"sync"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"

	"academy/event-driven-go/envelope"
)

// Confirmation is what a publish returns until the broker answers. The real
// type is *amqp.DeferredConfirmation.
type Confirmation interface {
	WaitContext(ctx context.Context) (acked bool, err error)
}

// ConfirmPublisher publishes with publisher confirms switched on.
type ConfirmPublisher interface {
	PublishDeferred(ctx context.Context, exchange, key string, mandatory bool, msg amqp.Publishing) (Confirmation, error)
}

// ErrUnroutable means the broker confirmed the publish but returned the message
// (basic.return) because no queue matched: nobody will ever receive it.
var ErrUnroutable = errors.New("rabbit: mandatory publish matched no queue")

// returnTracker remembers basic.return notifications by message ID. RabbitMQ
// sends basic.return before the basic.ack for the same message, so draining the
// buffered channel after the confirm sees every return that belongs to it.
type returnTracker struct {
	mu       sync.Mutex
	in       <-chan amqp.Return
	returned map[string]struct{}
}

func newReturnTracker(in <-chan amqp.Return) *returnTracker {
	return &returnTracker{in: in, returned: map[string]struct{}{}}
}

// Take reports (once) whether the message with this ID was returned.
func (t *returnTracker) Take(id string) bool {
	t.mu.Lock()
	defer t.mu.Unlock()
	for {
		select {
		case r := <-t.in:
			t.returned[r.MessageId] = struct{}{}
			continue
		default:
		}
		break
	}
	_, ok := t.returned[id]
	delete(t.returned, id)
	return ok
}

// ChannelPublisher adapts a channel in confirm mode (ch.Confirm(false)). Build it
// with NewChannelPublisher so mandatory returns are tracked.
type ChannelPublisher struct {
	Ch      *amqp.Channel
	returns *returnTracker
}

// NewChannelPublisher registers for basic.return on ch.
func NewChannelPublisher(ch *amqp.Channel) *ChannelPublisher {
	return &ChannelPublisher{Ch: ch, returns: newReturnTracker(ch.NotifyReturn(make(chan amqp.Return, 256)))}
}

type confirmation struct {
	c      *amqp.DeferredConfirmation
	id     string
	tracks *returnTracker
}

// WaitContext waits for the broker's answer, then reports an unroutable message
// as ErrUnroutable even though the broker acked it.
func (c confirmation) WaitContext(ctx context.Context) (bool, error) {
	acked, err := c.c.WaitContext(ctx)
	if err != nil {
		return acked, err
	}
	if c.tracks.Take(c.id) {
		return acked, ErrUnroutable
	}
	return acked, nil
}

// PublishDeferred implements ConfirmPublisher.
func (p *ChannelPublisher) PublishDeferred(ctx context.Context, exchange, key string, mandatory bool, msg amqp.Publishing) (Confirmation, error) {
	c, err := p.Ch.PublishWithDeferredConfirmWithContext(ctx, exchange, key, mandatory, false, msg)
	if err != nil {
		return nil, err // do not wrap a nil *DeferredConfirmation in a non-nil interface
	}
	return confirmation{c: c, id: msg.MessageId, tracks: p.returns}, nil
}

// ErrNacked means the broker took responsibility for the message and failed.
var ErrNacked = errors.New("rabbit: broker nacked the publish")

// ErrUnconfirmed means no answer arrived in time: the message may or may not
// have been stored, so the caller must retry with the same message ID.
var ErrUnconfirmed = errors.New("rabbit: publish not confirmed in time")

// Emitter publishes envelopes to one exchange and returns only after the
// broker confirmed them.
type Emitter struct {
	Pub            ConfirmPublisher
	Exchange       string
	ConfirmTimeout time.Duration
}

// Emit publishes one envelope persistently with the mandatory flag, so an
// unroutable message is returned instead of silently dropped.
func (e *Emitter) Emit(ctx context.Context, routingKey string, env envelope.Envelope) error {
	headers := amqp.Table{envelope.KeyVersion: int32(env.Version)}
	if env.TraceParent != "" {
		headers[envelope.KeyTraceParent] = env.TraceParent
	}
	msg := amqp.Publishing{
		ContentType:   "application/json",
		DeliveryMode:  amqp.Persistent,
		MessageId:     env.ID,
		Type:          env.Type,
		Timestamp:     env.OccurredAt,
		CorrelationId: env.CorrelationID,
		Headers:       headers,
		Body:          env.Payload,
	}

	conf, err := e.Pub.PublishDeferred(ctx, e.Exchange, routingKey, true, msg)
	if err != nil {
		return fmt.Errorf("rabbit: publish %s: %w", env.ID, err)
	}

	waitCtx, cancel := context.WithTimeout(ctx, e.ConfirmTimeout)
	defer cancel()
	acked, err := conf.WaitContext(waitCtx)
	switch {
	case errors.Is(err, ErrUnroutable):
		return fmt.Errorf("%w: %s (key %q)", ErrUnroutable, env.ID, routingKey)
	case err != nil:
		return fmt.Errorf("%w: %s: %v", ErrUnconfirmed, env.ID, err)
	case !acked:
		return fmt.Errorf("%w: %s", ErrNacked, env.ID)
	}
	return nil
}

The consumer: Consume, prefetch Qos, Ack, Nack, Reject {#consumer} Must-know ​

In plain words: A consumer asks for deliveries, works on them, and tells the broker the outcome: done (ack), failed (nack) or "never going to work" (reject). It also limits how many unfinished deliveries it holds (prefetch).

Common misunderstanding: "Auto-ack is just faster." With autoAck=true the broker considers a delivery done the moment it is sent; a crash loses everything in flight. And "a bigger prefetch is always better": a large prefetch makes one slow consumer hoard messages while others sit idle. RabbitMQ also notes: "Global (per-channel) QoS prefetch is deprecated and disabled by default starting with RabbitMQ 4.3. Use per-consumer prefetch instead." (ch.Qos(count, 0, false) is per consumer.)

Definition: ch.Qos(prefetchCount, 0, false) before ch.Consume(queue, tag, autoAck=false, exclusive, noLocal, noWait, args), which returns <-chan amqp.Delivery. Settling: d.Ack(multiple) (basic.ack), d.Nack(multiple, requeue) (basic.nack, a RabbitMQ extension that can settle many), d.Reject(requeue) (basic.reject, one delivery). With requeue=false and a dead-letter exchange configured, the message is dead-lettered; d.Redelivered is true on a redelivery. The rabbit.Consumer.Dispatch decision, tested in six rows:

Handler resultSettleWhy
nilAck(false)Effect committed
transient error, failures below maxNack(false, false)Dead-letter to the retry queue
transient error, failures at maxPark, then AckStop the loop; keep the evidence
ErrPermanentPark, then AckNo retry will help
context.CanceledNack(false, true)Not the message's fault; requeue, uncounted
Park itself failsNack(false, true)Never lose a message because the parking lot is down

The failure count is read from the broker-maintained x-death header (entries with queue, reason and count), as the Failures function does.

1  Qos(prefetch=10)
2  Consume(queue)  -> deliveries chan
3  worker takes d  -> handler(ctx, d)
4  err == nil      -> d.Ack(false)
5  err transient   -> d.Nack(false, false)   -> DLX -> retry queue -> back to main
6  x-death count reached -> park to dead exchange, d.Ack(false)

Real scenario: a billing consumer with prefetch=10 and four workers; a deploy sends SIGTERM and in-flight deliveries finish before the process exits.

Fix / how to use it: set HandlerTimeout below RabbitMQ's delivery acknowledgement timeout, make the handler idempotent, and settle every delivery exactly once.

go
package rabbit

import (
	"context"
	"errors"
	"fmt"
	"sync"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
)

// ErrPermanent marks an error that no retry will fix (bad payload, unknown
// type, business rule violated). The consumer parks the message at once.
var ErrPermanent = errors.New("permanent failure")

// Handler processes one delivery. It must be idempotent: the broker delivers at
// least once.
type Handler func(ctx context.Context, d amqp.Delivery) error

// Consumer maps a handler result onto the three acknowledgements.
type Consumer struct {
	Queue          string  // the work queue; used to read the x-death count
	Handler        Handler // business logic
	MaxAttempts    int64   // total tries before the message is parked
	HandlerTimeout time.Duration
	// Park stores a message the consumer gave up on (publish to the dead
	// exchange with confirms, or write it to a table). The delivery is acked
	// only after Park succeeds.
	Park func(ctx context.Context, d amqp.Delivery, cause error) error
}

// Failures counts how often the broker already dead-lettered this delivery
// from queue for the reason "rejected" (every Nack or Reject without requeue),
// read from the x-death header the broker maintains.
func Failures(h amqp.Table, queue string) int64 {
	deaths, _ := h["x-death"].([]interface{})
	var n int64
	for _, d := range deaths {
		t, ok := d.(amqp.Table)
		if !ok || t["queue"] != queue || t["reason"] != "rejected" {
			continue
		}
		if c, ok := t["count"].(int64); ok {
			n += c
		}
	}
	return n
}

// Dispatch runs the handler once and settles the delivery:
//
//	success              -> Ack
//	handler canceled     -> Nack(requeue=true): not the message's fault, not counted
//	permanent or too many failures -> Park, then Ack
//	other error          -> Nack(requeue=false): dead-letters to the retry queue
func (c *Consumer) Dispatch(ctx context.Context, d amqp.Delivery) error {
	hctx, cancel := context.WithTimeout(ctx, c.HandlerTimeout)
	defer cancel()

	err := c.Handler(hctx, d)
	switch {
	case err == nil:
		return d.Ack(false)
	case errors.Is(err, context.Canceled):
		return d.Nack(false, true) // someone stopped the handler: not the message's fault
	case errors.Is(err, ErrPermanent) || Failures(d.Headers, c.Queue)+1 >= c.MaxAttempts:
		if perr := c.Park(ctx, d, err); perr != nil {
			return errors.Join(perr, d.Nack(false, true)) // never lose it: put it back
		}
		return d.Ack(false)
	default:
		return d.Nack(false, false)
	}
}

// Run starts workers goroutines that read deliveries until the channel closes
// or ctx is canceled. Handlers run under a context that is NOT canceled by ctx,
// so in-flight messages finish (bounded by HandlerTimeout) before Run returns.
func (c *Consumer) Run(ctx context.Context, deliveries <-chan amqp.Delivery, workers int) error {
	inflight := context.WithoutCancel(ctx)
	var wg sync.WaitGroup
	var mu sync.Mutex
	var all []error
	record := func(err error) {
		mu.Lock()
		all = append(all, err)
		mu.Unlock()
	}
	for range workers {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for ctx.Err() == nil {
				select {
				case <-ctx.Done():
					return
				case d, ok := <-deliveries:
					if !ok {
						return
					}
					if ctx.Err() != nil {
						// Shutdown raced with a delivery: hand it back untouched.
						if err := d.Nack(false, true); err != nil {
							record(err)
						}
						return
					}
					if err := c.Dispatch(inflight, d); err != nil {
						record(fmt.Errorf("settle delivery %d: %w", d.DeliveryTag, err))
					}
				}
			}
		}()
	}
	wg.Wait()
	return errors.Join(all...)
}

// StartConsuming opens a consumer on queue with a prefetch window and manual
// acknowledgements. Qos must be set before Consume.
func StartConsuming(ch *amqp.Channel, queue, consumerTag string, prefetch int) (<-chan amqp.Delivery, error) {
	if err := ch.Qos(prefetch, 0, false); err != nil {
		return nil, fmt.Errorf("qos: %w", err)
	}
	return ch.Consume(queue, consumerTag, false, false, false, false, nil)
}
go
package rabbit

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

	amqp "github.com/rabbitmq/amqp091-go"

	"academy/event-driven-go/envelope"
)

// ---- fakes -----------------------------------------------------------

type fakeAck struct {
	mu    sync.Mutex
	calls []string
}

func (f *fakeAck) rec(s string) error {
	f.mu.Lock()
	f.calls = append(f.calls, s)
	f.mu.Unlock()
	return nil
}
func (f *fakeAck) Ack(uint64, bool) error { return f.rec("ack") }
func (f *fakeAck) Nack(_ uint64, _, requeue bool) error {
	if requeue {
		return f.rec("nack-requeue")
	}
	return f.rec("nack")
}
func (f *fakeAck) Reject(_ uint64, requeue bool) error {
	if requeue {
		return f.rec("reject-requeue")
	}
	return f.rec("reject")
}
func (f *fakeAck) last() string {
	f.mu.Lock()
	defer f.mu.Unlock()
	return f.calls[len(f.calls)-1]
}

func delivery(a *fakeAck, tag uint64, deaths int64) amqp.Delivery {
	d := amqp.Delivery{Acknowledger: a, DeliveryTag: tag, Body: []byte(`{}`), Headers: amqp.Table{}}
	if deaths > 0 {
		d.Headers["x-death"] = []interface{}{
			amqp.Table{"queue": "orders.created.q", "reason": "rejected", "count": deaths},
		}
	}
	return d
}

func newConsumer(h Handler, parked *atomic.Int32) *Consumer {
	return &Consumer{
		Queue: "orders.created.q", Handler: h, MaxAttempts: 3, HandlerTimeout: time.Second,
		Park: func(context.Context, amqp.Delivery, error) error { parked.Add(1); return nil },
	}
}

// ---- consumer decisions ------------------------------------------------

func TestDispatchMapsResultsToAcknowledgements(t *testing.T) {
	cases := []struct {
		name   string
		err    error
		deaths int64
		want   string
		parked int32
	}{
		{"success acks", nil, 0, "ack", 0},
		{"transient error dead-letters to the retry queue", errors.New("timeout"), 0, "nack", 0},
		{"second failure still retries", errors.New("timeout"), 1, "nack", 0},
		{"third failure is parked then acked", errors.New("timeout"), 2, "ack", 1},
		{"permanent error is parked at once", ErrPermanent, 0, "ack", 1},
		{"canceled handler is requeued without counting", context.Canceled, 0, "nack-requeue", 0},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			var parked atomic.Int32
			a := &fakeAck{}
			c := newConsumer(func(context.Context, amqp.Delivery) error { return tc.err }, &parked)
			if err := c.Dispatch(t.Context(), delivery(a, 1, tc.deaths)); err != nil {
				t.Fatal(err)
			}
			if got := a.last(); got != tc.want {
				t.Fatalf("settled with %q, want %q", got, tc.want)
			}
			if parked.Load() != tc.parked {
				t.Fatalf("parked = %d, want %d", parked.Load(), tc.parked)
			}
		})
	}
}

func TestFailedParkRequeuesInsteadOfLosingTheMessage(t *testing.T) {
	a := &fakeAck{}
	c := &Consumer{
		Queue: "q", MaxAttempts: 1, HandlerTimeout: time.Second,
		Handler: func(context.Context, amqp.Delivery) error { return ErrPermanent },
		Park:    func(context.Context, amqp.Delivery, error) error { return errors.New("dead exchange unreachable") },
	}
	if err := c.Dispatch(t.Context(), delivery(a, 1, 0)); err == nil {
		t.Fatal("expected the park error to be reported")
	}
	if got := a.last(); got != "nack-requeue" {
		t.Fatalf("settled with %q, want nack-requeue", got)
	}
}

func TestFailuresReadsXDeath(t *testing.T) {
	h := amqp.Table{"x-death": []interface{}{
		amqp.Table{"queue": "q", "reason": "rejected", "count": int64(2)},
		amqp.Table{"queue": "q", "reason": "expired", "count": int64(5)}, // the TTL hop does not count
		amqp.Table{"queue": "other", "reason": "rejected", "count": int64(9)},
	}}
	if n := Failures(h, "q"); n != 2 {
		t.Fatalf("Failures = %d, want 2", n)
	}
	if n := Failures(nil, "q"); n != 0 {
		t.Fatalf("Failures(nil) = %d", n)
	}
}

// ---- graceful drain ----------------------------------------------------

func TestRunDrainsInFlightWorkOnShutdown(t *testing.T) {
	var parked atomic.Int32
	started := make(chan struct{})
	release := make(chan struct{})
	var handled atomic.Int32
	c := newConsumer(func(ctx context.Context, d amqp.Delivery) error {
		handled.Add(1)
		close(started)
		<-release // in-flight work that is still running when shutdown starts
		return ctx.Err()
	}, &parked)

	deliveries := make(chan amqp.Delivery, 2)
	a := &fakeAck{}
	deliveries <- delivery(a, 1, 0)

	ctx, stop := context.WithCancel(t.Context())
	result := make(chan error, 1)
	go func() { result <- c.Run(ctx, deliveries, 1) }()

	<-started
	stop() // SIGTERM arrives
	deliveries <- delivery(a, 2, 0)

	select {
	case <-result:
		t.Fatal("Run returned while a handler was still in flight")
	case <-time.After(50 * time.Millisecond):
	}
	close(release)
	if err := <-result; err != nil {
		t.Fatal(err)
	}
	if got := handled.Load(); got != 1 {
		t.Fatalf("handled = %d, want 1: the second delivery must stay on the broker", got)
	}
	if got := a.last(); got != "ack" {
		t.Fatalf("in-flight message settled with %q, want ack", got)
	}
}

// ---- emitter -----------------------------------------------------------

type fakeConf struct {
	acked      bool
	err        error
	unroutable bool
}

func (f fakeConf) WaitContext(ctx context.Context) (bool, error) {
	if f.unroutable {
		return true, ErrUnroutable // the broker confirmed AND returned the message
	}
	if f.err != nil {
		<-ctx.Done()
		return false, ctx.Err()
	}
	return f.acked, nil
}

type fakePub struct {
	conf      fakeConf
	err       error
	gotKey    string
	mandatory bool
	msg       amqp.Publishing
}

func (f *fakePub) PublishDeferred(_ context.Context, _, key string, mandatory bool, m amqp.Publishing) (Confirmation, error) {
	f.gotKey, f.mandatory, f.msg = key, mandatory, m
	if f.err != nil {
		return nil, f.err
	}
	return f.conf, nil
}

func testEnvelope(t *testing.T) envelope.Envelope {
	t.Helper()
	env, err := envelope.New("e-1", "orders.created.v1", time.Unix(1_700_000_000, 0), 1, map[string]int{"n": 1})
	if err != nil {
		t.Fatal(err)
	}
	env.CorrelationID = "req-3"
	return env
}

func TestEmitterSetsDurabilityAndMandatory(t *testing.T) {
	p := &fakePub{conf: fakeConf{acked: true}}
	e := &Emitter{Pub: p, Exchange: "orders", ConfirmTimeout: time.Second}
	if err := e.Emit(t.Context(), "orders.created", testEnvelope(t)); err != nil {
		t.Fatal(err)
	}
	if p.gotKey != "orders.created" || !p.mandatory {
		t.Fatalf("key=%q mandatory=%v", p.gotKey, p.mandatory)
	}
	m := p.msg
	if m.DeliveryMode != amqp.Persistent || m.MessageId != "e-1" || m.Type != "orders.created.v1" || m.CorrelationId != "req-3" {
		t.Fatalf("publishing fields wrong: %+v", m)
	}
}

func TestEmitterReportsNackAndTimeout(t *testing.T) {
	nack := &Emitter{Pub: &fakePub{conf: fakeConf{acked: false}}, Exchange: "orders", ConfirmTimeout: time.Second}
	if err := nack.Emit(t.Context(), "k", testEnvelope(t)); !errors.Is(err, ErrNacked) {
		t.Fatalf("err = %v, want ErrNacked", err)
	}
	slow := &Emitter{Pub: &fakePub{conf: fakeConf{err: errors.New("never")}}, Exchange: "orders", ConfirmTimeout: 20 * time.Millisecond}
	if err := slow.Emit(t.Context(), "k", testEnvelope(t)); !errors.Is(err, ErrUnconfirmed) {
		t.Fatalf("err = %v, want ErrUnconfirmed", err)
	}
	down := &Emitter{Pub: &fakePub{err: errors.New("channel closed")}, Exchange: "orders", ConfirmTimeout: time.Second}
	if err := down.Emit(t.Context(), "k", testEnvelope(t)); err == nil {
		t.Fatal("expected a publish error")
	}
}

// ---- topology ----------------------------------------------------------

type recorder struct {
	exchanges map[string]string
	queues    map[string]amqp.Table
	binds     [][3]string
}

func (r *recorder) ExchangeDeclare(name, kind string, _, _, _, _ bool, _ amqp.Table) error {
	r.exchanges[name] = kind
	return nil
}
func (r *recorder) QueueDeclare(name string, durable, _, _, _ bool, args amqp.Table) (amqp.Queue, error) {
	if !durable {
		return amqp.Queue{}, errors.New("queue must be durable")
	}
	r.queues[name] = args
	return amqp.Queue{Name: name}, nil
}
func (r *recorder) QueueBind(name, key, exchange string, _ bool, _ amqp.Table) error {
	r.binds = append(r.binds, [3]string{name, key, exchange})
	return nil
}

func TestTopologyWiresRetryLoopAndParkingLot(t *testing.T) {
	r := &recorder{exchanges: map[string]string{}, queues: map[string]amqp.Table{}}
	top := Topology{Exchange: "orders", RoutingKey: "orders.created", Queue: "orders.created.q", RetryDelay: 5 * time.Second}
	if err := top.Declare(r); err != nil {
		t.Fatal(err)
	}
	if r.exchanges["orders"] != "topic" || r.exchanges["orders.retry"] != "fanout" {
		t.Fatalf("exchanges = %v", r.exchanges)
	}
	if got := r.queues["orders.created.q"]["x-dead-letter-exchange"]; got != "orders.retry" {
		t.Fatalf("work queue dead-letters to %v", got)
	}
	retry := r.queues["orders.created.q.retry"]
	if retry["x-message-ttl"] != int64(5000) || retry["x-dead-letter-exchange"] != "orders" {
		t.Fatalf("retry queue args = %v", retry)
	}
	if len(r.binds) != 3 {
		t.Fatalf("binds = %v", r.binds)
	}
}

// ---- reconnect ---------------------------------------------------------

type fakeSession struct {
	closed chan error
	n      int
}

func (f *fakeSession) Closed() <-chan error { return f.closed }
func (f *fakeSession) Close() error         { return nil }

func TestSuperviseRedialsAfterConnectionLoss(t *testing.T) {
	var dials atomic.Int32
	var served atomic.Int32
	sessions := make(chan *fakeSession, 4)
	dial := func(context.Context) (*fakeSession, error) {
		n := int(dials.Add(1))
		if n == 1 {
			return nil, errors.New("connection refused") // broker not up yet
		}
		s := &fakeSession{closed: make(chan error, 1), n: n}
		sessions <- s
		return s, nil
	}
	serve := func(ctx context.Context, s *fakeSession) error {
		served.Add(1)
		<-ctx.Done()
		return nil
	}

	ctx, cancel := context.WithCancel(t.Context())
	var errCount atomic.Int32
	done := make(chan error, 1)
	b := Backoff{Initial: time.Millisecond, Max: 5 * time.Millisecond}
	go func() { done <- Supervise(ctx, dial, serve, b, func(error) { errCount.Add(1) }) }()

	first := <-sessions
	first.closed <- errors.New("CONNECTION_FORCED") // the broker restarts
	<-sessions                                      // a second session must appear
	cancel()
	if err := <-done; !errors.Is(err, context.Canceled) {
		t.Fatalf("Supervise returned %v", err)
	}
	if served.Load() != 2 {
		t.Fatalf("served = %d, want 2 sessions", served.Load())
	}
	if errCount.Load() < 2 {
		t.Fatalf("errors reported = %d, want the failed dial and the close", errCount.Load())
	}
}

func TestBackoffGrowsAndIsCapped(t *testing.T) {
	b := Backoff{Initial: 100 * time.Millisecond, Max: time.Second}
	for n, hi := range []time.Duration{100, 200, 400, 800, 1000, 1000, 1000} {
		hi *= time.Millisecond
		for range 50 {
			d := b.Delay(n)
			if d < hi/2 || d > hi {
				t.Fatalf("Delay(%d) = %v, want within [%v, %v]", n, d, hi/2, hi)
			}
		}
	}
}

func TestEmitterReportsUnroutableMandatoryPublish(t *testing.T) {
	e := &Emitter{Pub: &fakePub{conf: fakeConf{unroutable: true}}, Exchange: "orders", ConfirmTimeout: time.Second}
	err := e.Emit(t.Context(), "orders.typo", testEnvelope(t))
	if !errors.Is(err, ErrUnroutable) {
		t.Fatalf("err = %v, want ErrUnroutable: a confirmed but returned message was not delivered", err)
	}
}

func TestReturnTrackerMatchesByMessageID(t *testing.T) {
	returns := make(chan amqp.Return, 4)
	returns <- amqp.Return{MessageId: "e-9", ReplyCode: 312, ReplyText: "NO_ROUTE"}
	returns <- amqp.Return{MessageId: "e-10"}
	tr := newReturnTracker(returns)
	if !tr.Take("e-9") || tr.Take("e-9") {
		t.Fatal("e-9 must be reported once")
	}
	if !tr.Take("e-10") || tr.Take("e-11") {
		t.Fatal("matching must be by message ID")
	}
}

func TestWorkQueueUsesAtLeastOnceDeadLettering(t *testing.T) {
	r := &recorder{exchanges: map[string]string{}, queues: map[string]amqp.Table{}}
	top := Topology{Exchange: "orders", RoutingKey: "orders.created", Queue: "orders.created.q", RetryDelay: time.Second}
	if err := top.Declare(r); err != nil {
		t.Fatal(err)
	}
	args := r.queues["orders.created.q"]
	if args["x-dead-letter-strategy"] != "at-least-once" || args["x-overflow"] != "reject-publish" {
		t.Fatalf("work queue args = %v: quorum dead-lettering is at-most-once unless both are set", args)
	}
}

Reconnecting {#reconnect} Important ​

In plain words: Connections to a broker die (restarts, network blips, upgrades). Reconnect handling is a loop that dials again, re-declares everything, and starts consuming again.

Common misunderstanding: "amqp091-go reconnects automatically." Not by default. The client has automatic connection and topology recovery, but it is off unless you set amqp.Config.Recovery: the source says "If Recovery is nil, automatic reconnection and topology recovery are disabled", and marks the feature "Experimental". Without it, a dropped connection closes the channels and the delivery channel, and you listen on conn.NotifyClose(chan *amqp.Error) and rebuild yourself. (Watermill's AMQP Pub/Sub has a ReconnectConfig with exponential backoff: DefaultReconnectConfig() is 500 ms initial, 1.5 multiplier, 60 s cap.)

Definition: two options. (a) The client's own recovery: amqp.DialConfig(url, amqp.Config{Recovery: &amqp.Recovery{}}) (shown as DialAMQPRecovering below) reconnects with DefaultReconnectionConfig (DefaultMaxRetryCount 5 tries, DefaultRetryInterval 5 s) and recovers exchanges, queues, bindings and active consumers (TopologyRecoveryMode controls the scope); unconfirmed publishes and deliveries that were in flight are still lost. (b) A supervisor you own: dial, serve until the session closes or serve returns, wait with capped exponential backoff and jitter, repeat until the context ends. Serve must re-declare topology and re-register consumers because a new connection starts empty, and unconfirmed publishes from the dead channel must be retried.

1  Dial fails (broker down)  -> wait 1s, 2s, 4s ... capped, jittered
2  Dial ok                   -> serve(session)
3  broker restarts           -> session.Closed() fires
4  cancel serve, close, wait -> go to 1
5  ctx canceled              -> return

Real scenario: a RabbitMQ rolling upgrade closes every connection once per node; consumers without a supervisor stay silently idle until someone restarts the pod (the queue grows, nothing errors).

Fix / how to use it: run the supervisor in main, expose "connected" in /readyz, alert on queue depth with zero consumers.

go
package rabbit

import (
	"context"
	"math/rand/v2"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
)

// Session is one live broker connection plus whatever was opened on it.
// Closed receives (at most) one error when the connection dies and is then
// closed. A graceful Close closes it without sending.
type Session interface {
	Closed() <-chan error
	Close() error
}

// Backoff computes capped exponential delays with jitter.
type Backoff struct {
	Initial time.Duration
	Max     time.Duration
}

// Delay returns the wait before attempt n (0-based): min(Max, Initial*2^n),
// then a random value in [d/2, d] so many consumers do not reconnect in lockstep.
func (b Backoff) Delay(n int) time.Duration {
	d := b.Initial
	for i := 0; i < n && d < b.Max; i++ {
		d *= 2
	}
	if d > b.Max {
		d = b.Max
	}
	half := d / 2
	if half <= 0 {
		return d
	}
	return half + rand.N(half+1)
}

// Supervise keeps one session alive until ctx is canceled: dial, serve until the
// session closes or serve returns, wait, dial again. serve must re-declare
// topology and re-register consumers on the new session, because a fresh
// connection starts empty. onError may be nil.
func Supervise[S Session](
	ctx context.Context,
	dial func(context.Context) (S, error),
	serve func(context.Context, S) error,
	b Backoff,
	onError func(error),
) error {
	report := func(err error) {
		if err != nil && onError != nil {
			onError(err)
		}
	}
	attempt := 0
	for {
		if err := ctx.Err(); err != nil {
			return err
		}
		s, err := dial(ctx)
		if err != nil {
			report(err)
			if err := sleep(ctx, b.Delay(attempt)); err != nil {
				return err
			}
			attempt++
			continue
		}
		attempt = 0

		sctx, cancel := context.WithCancel(ctx)
		done := make(chan error, 1)
		go func() { done <- serve(sctx, s) }()

		select {
		case cerr := <-s.Closed():
			report(cerr)
			cancel()
			report(<-done)
		case err := <-done:
			report(err)
			cancel()
		case <-ctx.Done():
			cancel()
			<-done
			_ = s.Close()
			return ctx.Err()
		}
		_ = s.Close()
		if err := sleep(ctx, b.Delay(0)); err != nil {
			return err
		}
	}
}

func sleep(ctx context.Context, d time.Duration) error {
	t := time.NewTimer(d)
	defer t.Stop()
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-t.C:
		return nil
	}
}

// AMQPSession is the real Session: a connection, one channel in confirm mode,
// and a prefetch window.
type AMQPSession struct {
	Conn   *amqp.Connection
	Ch     *amqp.Channel
	closed chan error
}

// DialAMQP connects, opens a channel, switches on publisher confirms and sets
// the consumer prefetch. Expected, not run: it needs a broker.
func DialAMQP(url string, prefetch int) (*AMQPSession, error) {
	conn, err := amqp.DialConfig(url, amqp.Config{Dial: amqp.DefaultDial(5 * time.Second)})
	if err != nil {
		return nil, err
	}
	ch, err := conn.Channel()
	if err != nil {
		_ = conn.Close()
		return nil, err
	}
	if err := ch.Confirm(false); err != nil {
		_ = conn.Close()
		return nil, err
	}
	if err := ch.Qos(prefetch, 0, false); err != nil {
		_ = conn.Close()
		return nil, err
	}
	s := &AMQPSession{Conn: conn, Ch: ch, closed: make(chan error, 1)}
	notify := conn.NotifyClose(make(chan *amqp.Error, 1))
	go func() {
		if e, ok := <-notify; ok && e != nil {
			s.closed <- e
		}
		close(s.closed)
	}()
	return s, nil
}

// Closed implements Session.
func (s *AMQPSession) Closed() <-chan error { return s.closed }

// Close implements Session.
func (s *AMQPSession) Close() error { return s.Conn.Close() }

// DialAMQPRecovering uses the client's own automatic connection and topology
// recovery (amqp.Config.Recovery). In amqp091-go v1.17.0 the field is documented
// as experimental and a nil Recovery means disabled, which is the default. With
// it, the connection, its channels, declared topology and active consumers are
// rebuilt after a network failure; unconfirmed publishes and in-flight
// deliveries are still lost and must be retried by the application.
// Expected, not run: it needs a broker.
func DialAMQPRecovering(url string) (*amqp.Connection, error) {
	return amqp.DialConfig(url, amqp.Config{
		Dial:     amqp.DefaultDial(5 * time.Second),
		Recovery: &amqp.Recovery{}, // zero value: default reconnection (5 tries, 5 s apart) and topology recovery
	})
}

Delayed retry and parking with dead-letter exchanges {#dlx} Must-know ​

In plain words: When a message fails, push it to a waiting room that sends it back after a delay; after enough failures, put it in a box a human looks at.

Common misunderstanding: "Nack with requeue=true is a retry." It puts the message straight back at the head, so a broken message spins at full speed and starves the queue. Dead-letter exchanges give a delay and a counter instead.

Definition: a queue with x-dead-letter-exchange sends rejected, expired, over-length or over-delivery-limit messages to that exchange. RabbitMQ stamps an x-death header. The reason is one of "rejected", "expired", "maxlen" or "delivery_limit". A TTL queue (x-message-ttl) with no consumers and a dead-letter exchange pointing back at the main exchange is the classic delayed retry: the message waits out the TTL and returns. For quorum queues the docs say "at-most-once remains the default dead-letter-strategy", so a message can be lost in transit between the two queues. Switching the source queue to x-dead-letter-strategy=at-least-once makes an internal consumer re-publish dead-lettered messages "with publisher confirms turned on internally", and it requires x-overflow=reject-publish (the default drop-head is not allowed). Topology.Declare sets both on the work queue and on the retry queue, and its test asserts them; the cost of reject-publish is that a full queue refuses new publishes (your emitter then sees a nack).

1  work queue: handler fails        -> Nack(requeue=false)
2  DLX orders.retry (fanout)        -> orders.created.q.retry (x-message-ttl 5000)
3  5 s later TTL expires            -> dead-lettered to exchange "orders", same routing key
4  back in orders.created.q         x-death[rejected].count = 1
5  ... count reaches MaxAttempts    -> consumer parks to orders.dead and acks

Real scenario: a partner API outage: every call fails, messages cycle through the 5 s retry loop, and the parking queue stays empty until the attempts run out; after the incident an operator moves parked messages back (a "shovel" or a small replay tool).

MechanismDelayCounterCaveat
Requeue (Nack(false, true))NoneRedelivered flag onlyHot loop
Retry queue with TTLFixed per queuex-death countOne queue per delay; per-message TTL has head-of-line blocking
Several retry queues (5 s, 1 min, 10 min)Escalatingx-deathMore topology
Quorum queue x-delivery-limitNonex-delivery-countDrops or dead-letters at the limit
Delayed-message pluginPer messageHeaderPlugin, not core
SQS visibility timeoutPer message, adjustableApproximateReceiveCountSee SQS

For retries with backoff in RabbitMQ choose one queue per delay step and select the step from the failure count; Watermill's Retry middleware is the in-process alternative for short blips. The broker-neutral version of the same ideas is in Retry, Backoff & Delayed Delivery and Dead Letter Queues.

Fix / how to use it: the Topology.Declare snippet above builds the loop with the at-least-once strategy; Failures(headers, queue) reads the count. Existing queues cannot change these arguments with a redeclare (406); use a policy or a new queue name.

Idempotent consumers and the inbox table {#inbox} Must-know ​

In plain words: The consumer writes "I processed message X" in the same database transaction as the business change. A second delivery of X finds the row and does nothing.

Common misunderstanding: "Check SELECT ... WHERE id = X first, then insert." Two concurrent deliveries both see "absent" and both proceed. The insert itself must be the check (a primary key plus ON CONFLICT DO NOTHING), and it must share the business transaction so a rollback also removes the inbox row.

Definition: the inbox pattern: INSERT INTO inbox (consumer, message_id) ... ON CONFLICT DO NOTHING; zero rows affected means "seen". The key includes the consumer name so two services can process the same message ID.

sql
CREATE TABLE inbox (
    consumer     text         NOT NULL,
    message_id   text         NOT NULL,
    processed_at timestamptz  NOT NULL DEFAULT now(),
    PRIMARY KEY (consumer, message_id)
);

-- inside the same transaction as the business change
INSERT INTO inbox (consumer, message_id) VALUES ('billing', 'm-1')
ON CONFLICT (consumer, message_id) DO NOTHING;   -- 0 rows: duplicate, skip the work
UPDATE accounts SET balance = balance + 100 WHERE id = 'a1';

-- housekeeping: keep rows longer than the broker's maximum redelivery horizon
DELETE FROM inbox WHERE processed_at < now() - interval '14 days';

Real scenario: wallet credits, stock decrements, e-mail sending with a "sent" row; the pruning window must exceed the longest time a message can sit in a queue or DLQ before redrive.

TechniqueWhen it worksWeakness
Natural idempotency (SET status = 'paid')State transitionsNot for increments
Inbox tableAny DB effectTable growth; needs pruning
Redis SET NX with TTLNon-DB effectsNot atomic with the DB commit
Idempotency key to a downstream APIPaymentsDepends on the partner
Broker deduplication (SQS FIFO)Producer retries within a windowNot for consumer redelivery
go
// Package inbox makes a consumer idempotent with an inbox table: the message
// ID is inserted in the same database transaction as the business change, so
// the two commit or roll back together and a redelivery finds the row.
package inbox

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

// The schema, as it would live in a migration (PostgreSQL).
const Schema = `
CREATE TABLE IF NOT EXISTS inbox (
    consumer     text        NOT NULL,
    message_id   text        NOT NULL,
    processed_at timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (consumer, message_id)
)`

// Claim inserts the message ID; zero rows affected means "seen before".
const Claim = `
INSERT INTO inbox (consumer, message_id) VALUES ($1, $2)
ON CONFLICT (consumer, message_id) DO NOTHING`

// Tx is the part of *sql.Tx the inbox needs.
type Tx interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	Commit() error
	Rollback() error
}

// Beginner starts a transaction. SQLDB adapts *sql.DB.
type Beginner interface {
	Begin(ctx context.Context) (Tx, error)
}

// SQLDB adapts *sql.DB to Beginner.
type SQLDB struct{ DB *sql.DB }

// Begin implements Beginner.
func (s SQLDB) Begin(ctx context.Context) (Tx, error) { return s.DB.BeginTx(ctx, nil) }

// ErrDuplicate is returned when the message was already processed. Callers
// treat it as success and acknowledge the message.
var ErrDuplicate = errors.New("inbox: message already processed")

// Process runs work inside one transaction guarded by the inbox row. If work
// fails, the transaction rolls back and the inbox row disappears with it, so
// the retry is not mistaken for a duplicate.
func Process(ctx context.Context, db Beginner, consumer, messageID string, work func(ctx context.Context, tx Tx) error) error {
	tx, err := db.Begin(ctx)
	if err != nil {
		return fmt.Errorf("inbox: begin: %w", err)
	}
	res, err := tx.ExecContext(ctx, Claim, consumer, messageID)
	if err != nil {
		_ = tx.Rollback()
		return fmt.Errorf("inbox: claim: %w", err)
	}
	if n, err := res.RowsAffected(); err != nil || n == 0 {
		_ = tx.Rollback()
		if err != nil {
			return fmt.Errorf("inbox: rows affected: %w", err)
		}
		return ErrDuplicate
	}
	if err := work(ctx, tx); err != nil {
		_ = tx.Rollback()
		return err
	}
	return tx.Commit()
}
go
package inbox

import (
	"context"
	"database/sql"
	"errors"
	"testing"
)

// memDB is a tiny transactional store: inserts become visible at Commit.
type memDB struct{ rows map[string]bool }

type memTx struct {
	db      *memDB
	pending []string
}

type result int64

func (r result) LastInsertId() (int64, error) { return 0, nil }
func (r result) RowsAffected() (int64, error) { return int64(r), nil }

func (d *memDB) Begin(context.Context) (Tx, error) { return &memTx{db: d}, nil }

func (t *memTx) ExecContext(_ context.Context, _ string, args ...any) (sql.Result, error) {
	key := args[0].(string) + "/" + args[1].(string)
	if t.db.rows[key] {
		return result(0), nil // ON CONFLICT DO NOTHING
	}
	t.pending = append(t.pending, key)
	return result(1), nil
}

func (t *memTx) Commit() error {
	for _, k := range t.pending {
		t.db.rows[k] = true
	}
	return nil
}

func (t *memTx) Rollback() error { t.pending = nil; return nil }

func TestSecondDeliveryIsADuplicate(t *testing.T) {
	db := &memDB{rows: map[string]bool{}}
	applied := 0
	work := func(context.Context, Tx) error { applied++; return nil }

	if err := Process(t.Context(), db, "billing", "m-1", work); err != nil {
		t.Fatal(err)
	}
	if err := Process(t.Context(), db, "billing", "m-1", work); !errors.Is(err, ErrDuplicate) {
		t.Fatalf("err = %v, want ErrDuplicate", err)
	}
	if applied != 1 {
		t.Fatalf("work ran %d times, want 1", applied)
	}
}

func TestFailedWorkRollsBackTheInboxRow(t *testing.T) {
	db := &memDB{rows: map[string]bool{}}
	boom := errors.New("insert failed")
	if err := Process(t.Context(), db, "billing", "m-2", func(context.Context, Tx) error { return boom }); !errors.Is(err, boom) {
		t.Fatalf("err = %v", err)
	}
	// The retry must run the work again, not be skipped as a duplicate.
	ran := false
	if err := Process(t.Context(), db, "billing", "m-2", func(context.Context, Tx) error { ran = true; return nil }); err != nil || !ran {
		t.Fatalf("retry err=%v ran=%v", err, ran)
	}
}

func TestSameIDForAnotherConsumerIsNotADuplicate(t *testing.T) {
	db := &memDB{rows: map[string]bool{}}
	noop := func(context.Context, Tx) error { return nil }
	if err := Process(t.Context(), db, "billing", "m-3", noop); err != nil {
		t.Fatal(err)
	}
	if err := Process(t.Context(), db, "shipping", "m-3", noop); err != nil {
		t.Fatalf("shipping must see its own copy: %v", err)
	}
}

Fix / how to use it: the tests show the three properties: a duplicate is skipped, a failed unit of work rolls the inbox row back so the retry runs, and two consumers keep separate memories. Full pattern: Idempotent Consumer & Inbox.

Outbox publishing from Postgres {#outbox} Must-know ​

In plain words: Do not write to the database and then publish; write the event into an outbox table in the same transaction and let a relay publish it afterwards.

Common misunderstanding: "Publish inside the transaction, before commit, and it is atomic." Two different systems cannot share a transaction: if the publish succeeds and the commit fails the world sees an event for a rollback; if commit succeeds and the publish fails the event is lost. microservices.io's pattern description puts the idea as a database table that stores the business entities and the message outbox. Watermill ships the same idea as the Forwarder component.

Definition: business code calls outbox.Enqueue(ctx, tx, topic, msg) inside its transaction. A relay (outbox.Relay.PollOnce) claims a batch with SELECT ... FOR UPDATE SKIP LOCKED, publishes rows in id order, stops at the first failure, marks the published ones and commits. A crash between publish and commit republishes: at-least-once, which the consumers' inbox absorbs.

sql
CREATE TABLE outbox (
    id           bigserial   PRIMARY KEY,
    message_uuid text        NOT NULL UNIQUE,
    topic        text        NOT NULL,
    payload      bytea       NOT NULL,
    created_at   timestamptz NOT NULL DEFAULT now(),
    metadata     jsonb       NOT NULL DEFAULT '{}',   -- envelope headers: type, schema_version, occurred_at, correlation_id, traceparent
    published_at timestamptz
);
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;

BEGIN;
INSERT INTO orders (id, total_cents) VALUES ('o-9', 4200);
INSERT INTO outbox (message_uuid, topic, payload, metadata)
VALUES ('e-1', 'orders.placed', '\x7b7d', '{"type":"orders.order_placed.v1","schema_version":"1"}');
COMMIT;

-- relay, one batch
BEGIN;
SELECT id, message_uuid, topic, payload, metadata FROM outbox
 WHERE published_at IS NULL ORDER BY id LIMIT 100 FOR UPDATE SKIP LOCKED;
-- publish each row, then:
UPDATE outbox SET published_at = now() WHERE id = 1;
COMMIT;
1  service tx:  INSERT order + INSERT outbox(e-1)  COMMIT
2  relay:       claim batch (rows locked, other relays skip them)
3  relay:       Publish(e-1)  -> broker confirm
4  relay:       UPDATE published_at; COMMIT
5  crash between 3 and 4 -> e-1 published again next poll (same UUID)

Real scenario: an order service that must never confirm an order without emitting OrderPlaced; polling every 200 ms gives sub-second latency; for lower latency use LISTEN/NOTIFY as a wake-up hint (the table stays the source of truth) or logical decoding.

Relay approachLatencyOps costCaveat
Polling with SKIP LOCKEDPoll intervalLowestIndex on unpublished rows; vacuum the table
Polling + LISTEN/NOTIFYNear-instantLowNotify can be missed: still poll
Logical decoding (CDC)Near-instantHighestSlots, schema changes
Watermill Forwarder over the SQL Pub/SubPoll intervalLibrary-managedCouples to Watermill
go
// Package outbox implements the transactional outbox: the service writes the
// event row in the same transaction as its business change, and a relay
// publishes unpublished rows to the broker afterwards. Delivery to the broker
// is at-least-once; the stable message UUID lets consumers deduplicate.
package outbox

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

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

// Schema is the migration for PostgreSQL.
const Schema = `
CREATE TABLE IF NOT EXISTS outbox (
    id           bigserial   PRIMARY KEY,
    message_uuid text        NOT NULL UNIQUE,
    topic        text        NOT NULL,
    payload      bytea       NOT NULL,
    metadata     jsonb       NOT NULL DEFAULT '{}',
    created_at   timestamptz NOT NULL DEFAULT now(),
    published_at timestamptz
);
CREATE INDEX IF NOT EXISTS outbox_unpublished ON outbox (id) WHERE published_at IS NULL`

// Insert is executed on the SAME transaction as the business change.
const Insert = `INSERT INTO outbox (message_uuid, topic, payload, metadata) VALUES ($1, $2, $3, $4)`

// ClaimBatch locks a batch for this relay instance; other relays skip the
// locked rows instead of waiting, so relays can run in parallel.
const ClaimBatch = `
SELECT id, message_uuid, topic, payload, metadata FROM outbox
WHERE published_at IS NULL
ORDER BY id
LIMIT $1
FOR UPDATE SKIP LOCKED`

// MarkPublished stamps one row that was handed to the broker.
const MarkPublished = `UPDATE outbox SET published_at = now() WHERE id = $1`

// Execer is what the business code passes in: its own open transaction.
type Execer interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}

// Enqueue writes one event into the outbox inside the caller's transaction.
func Enqueue(ctx context.Context, tx Execer, topic string, msg *message.Message) error {
	md, err := json.Marshal(map[string]string(msg.Metadata))
	if err != nil {
		return fmt.Errorf("outbox: metadata %s: %w", msg.UUID, err)
	}
	if _, err := tx.ExecContext(ctx, Insert, msg.UUID, topic, []byte(msg.Payload), md); err != nil {
		return fmt.Errorf("outbox: insert %s: %w", msg.UUID, err)
	}
	return nil
}

// Row is one claimed outbox row.
type Row struct {
	ID      int64
	UUID    string
	Topic   string
	Payload []byte
	// Metadata holds the envelope headers (type, schema version, occurred_at,
	// correlation ID, trace context) so the published message is complete.
	Metadata map[string]string
}

// Batch is a set of rows locked inside one transaction.
type Batch interface {
	Rows() []Row
	MarkPublished(ctx context.Context, ids []int64) error
	Commit() error
	Rollback() error
}

// Store claims batches. A PostgreSQL implementation runs ClaimBatch inside a
// transaction; tests use an in-memory one.
type Store interface {
	Claim(ctx context.Context, limit int) (Batch, error)
}

// Relay moves rows from the outbox to the broker.
type Relay struct {
	Store Store
	Pub   message.Publisher
	Limit int
}

// PollOnce claims a batch, publishes rows in id order and stops at the first
// failure, then marks what was published and commits. A crash between publish
// and commit republishes the same rows later: at-least-once, never lost.
// It returns the number of rows published.
func (r *Relay) PollOnce(ctx context.Context) (int, error) {
	batch, err := r.Store.Claim(ctx, r.Limit)
	if err != nil {
		return 0, fmt.Errorf("outbox: claim: %w", err)
	}
	var done []int64
	var pubErr error
	for _, row := range batch.Rows() {
		m := message.NewMessage(row.UUID, row.Payload)
		for k, v := range row.Metadata {
			m.Metadata.Set(k, v)
		}
		if pubErr = r.Pub.Publish(row.Topic, m); pubErr != nil {
			break // keep order: do not skip ahead of a failed row
		}
		done = append(done, row.ID)
	}
	if len(done) > 0 {
		if err := batch.MarkPublished(ctx, done); err != nil {
			_ = batch.Rollback()
			return 0, fmt.Errorf("outbox: mark published: %w", err)
		}
	}
	if err := batch.Commit(); err != nil {
		return 0, fmt.Errorf("outbox: commit: %w", err)
	}
	return len(done), pubErr
}
go
package outbox

import (
	"context"
	"database/sql"
	"encoding/json"
)

// PostgresStore is the database/sql implementation of Store. Expected, not
// run: it needs a PostgreSQL server (the tests use an in-memory Store).
type PostgresStore struct{ DB *sql.DB }

type pgBatch struct {
	tx   *sql.Tx
	rows []Row
}

// Claim opens a transaction and locks up to limit unpublished rows.
func (s PostgresStore) Claim(ctx context.Context, limit int) (Batch, error) {
	tx, err := s.DB.BeginTx(ctx, nil)
	if err != nil {
		return nil, err
	}
	rs, err := tx.QueryContext(ctx, ClaimBatch, limit)
	if err != nil {
		_ = tx.Rollback()
		return nil, err
	}
	defer rs.Close()
	var rows []Row
	for rs.Next() {
		var r Row
		var md []byte
		if err := rs.Scan(&r.ID, &r.UUID, &r.Topic, &r.Payload, &md); err != nil {
			_ = tx.Rollback()
			return nil, err
		}
		if err := json.Unmarshal(md, &r.Metadata); err != nil {
			_ = tx.Rollback()
			return nil, err
		}
		rows = append(rows, r)
	}
	if err := rs.Err(); err != nil {
		_ = tx.Rollback()
		return nil, err
	}
	return &pgBatch{tx: tx, rows: rows}, nil
}

func (b *pgBatch) Rows() []Row { return b.rows }

func (b *pgBatch) MarkPublished(ctx context.Context, ids []int64) error {
	for _, id := range ids {
		if _, err := b.tx.ExecContext(ctx, MarkPublished, id); err != nil {
			return err
		}
	}
	return nil
}

func (b *pgBatch) Commit() error   { return b.tx.Commit() }
func (b *pgBatch) Rollback() error { return b.tx.Rollback() }
go
package outbox

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"sync"
	"testing"
	"time"

	"github.com/ThreeDotsLabs/watermill/message"

	"academy/event-driven-go/envelope"
)

type memStore struct {
	mu   sync.Mutex
	rows []Row
	done map[int64]bool
}

type memBatch struct {
	s    *memStore
	rows []Row
}

func (s *memStore) Claim(_ context.Context, limit int) (Batch, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	var b []Row
	for _, r := range s.rows {
		if !s.done[r.ID] && len(b) < limit {
			b = append(b, r)
		}
	}
	return &memBatch{s: s, rows: b}, nil
}

func (b *memBatch) Rows() []Row { return b.rows }
func (b *memBatch) MarkPublished(_ context.Context, ids []int64) error {
	b.s.mu.Lock()
	defer b.s.mu.Unlock()
	for _, id := range ids {
		b.s.done[id] = true
	}
	return nil
}
func (b *memBatch) Commit() error   { return nil }
func (b *memBatch) Rollback() error { return nil }

type recordingPub struct {
	published []string
	messages  []*message.Message
	failOn    string
}

func (p *recordingPub) Publish(_ string, msgs ...*message.Message) error {
	for _, m := range msgs {
		if m.UUID == p.failOn {
			return errors.New("broker unavailable")
		}
		p.published = append(p.published, m.UUID)
		p.messages = append(p.messages, m)
	}
	return nil
}
func (p *recordingPub) Close() error { return nil }

func newStore() *memStore {
	return &memStore{
		done: map[int64]bool{},
		rows: []Row{{ID: 1, UUID: "u1", Topic: "orders", Payload: []byte("a")}, {ID: 2, UUID: "u2", Topic: "orders", Payload: []byte("b")}, {ID: 3, UUID: "u3", Topic: "orders", Payload: []byte("c")}},
	}
}

func TestRelayStopsAtFirstFailureAndResumes(t *testing.T) {
	store := newStore()
	pub := &recordingPub{failOn: "u2"}
	relay := &Relay{Store: store, Pub: pub, Limit: 10}

	n, err := relay.PollOnce(t.Context())
	if err == nil || n != 1 {
		t.Fatalf("n=%d err=%v, want 1 row published then an error", n, err)
	}
	if !store.done[1] || store.done[2] || store.done[3] {
		t.Fatalf("done = %v: u3 must not jump ahead of the failed u2", store.done)
	}

	pub.failOn = "" // broker is back
	n, err = relay.PollOnce(t.Context())
	if err != nil || n != 2 {
		t.Fatalf("n=%d err=%v", n, err)
	}
	want := []string{"u1", "u2", "u3"}
	for i, id := range want {
		if pub.published[i] != id {
			t.Fatalf("published = %v, want order %v", pub.published, want)
		}
	}
}

type captureTx struct {
	query string
	args  []any
}

func (c *captureTx) ExecContext(_ context.Context, q string, a ...any) (sql.Result, error) {
	c.query, c.args = q, a
	return nil, nil
}

func TestEnqueueUsesTheCallersTransaction(t *testing.T) {
	tx := &captureTx{}
	m := message.NewMessage("u9", []byte(`{"x":1}`))
	if err := Enqueue(t.Context(), tx, "orders", m); err != nil {
		t.Fatal(err)
	}
	if tx.query != Insert || tx.args[0] != "u9" || tx.args[1] != "orders" {
		t.Fatalf("query=%q args=%v", tx.query, tx.args)
	}
}

func TestMetadataSurvivesTheOutbox(t *testing.T) {
	env, err := envelope.New("e-5", "orders.order_placed.v1", time.Unix(1_700_000_000, 0), 1, map[string]int{"n": 1})
	if err != nil {
		t.Fatal(err)
	}
	env.CorrelationID, env.TraceParent = "req-5", "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"

	tx := &captureTx{}
	if err := Enqueue(t.Context(), tx, "orders", env.ToMessage()); err != nil {
		t.Fatal(err)
	}
	if len(tx.args) != 4 {
		t.Fatalf("Enqueue passed %d args, want uuid, topic, payload, metadata", len(tx.args))
	}
	var md map[string]string
	if err := json.Unmarshal(tx.args[3].([]byte), &md); err != nil || md["type"] != env.Type {
		t.Fatalf("metadata arg = %v (%v)", tx.args[3], err)
	}

	// The row the relay reads back carries the same metadata.
	store := &memStore{done: map[int64]bool{}, rows: []Row{{ID: 1, UUID: "e-5", Topic: "orders", Payload: env.Payload, Metadata: md}}}
	pub := &recordingPub{}
	if _, err := (&Relay{Store: store, Pub: pub, Limit: 10}).PollOnce(t.Context()); err != nil {
		t.Fatal(err)
	}
	back, err := envelope.FromMessage(pub.messages[0])
	if err != nil {
		t.Fatalf("FromMessage after the outbox: %v", err)
	}
	if back.CorrelationID != "req-5" || back.TraceParent != env.TraceParent || back.Type != env.Type {
		t.Fatalf("lost header data: %+v", back)
	}
}

Fix / how to use it: the row stores the full Watermill metadata next to the payload (the envelope headers: type, schema version, occurred_at, correlation ID, trace context), and the relay restores it before publishing; the test enqueues env.ToMessage() and shows envelope.FromMessage succeeds on what PollOnce published. The relay test publishes u1, fails on u2, and proves u3 does not jump ahead and that a second poll delivers u2 then u3 in order. Full pattern: Outbox Pattern.

Outbox to broker to idempotent consumersOrder servicehandler + DB txoutbox tablesame tx as the orderRelaypolls, publishesBrokerexchange orders (topic)billing.qBilling serviceshipping.qShipping serviceorders.created.deadparking lotINSERTpublish + confirmreject x NEach consumer keeps an inbox row per message ID: duplicates from at-least-once delivery become no-ops.

Ordering per key {#ordering} Important ​

In plain words: You rarely need global order, only "events of the same order, account or customer in sequence". Route by key so one key always lands on the same worker.

Common misunderstanding: "A queue is FIFO, so my handlers see events in order." With several consumers or several goroutines, handlers finish in any order; a requeue puts a message behind later ones. Order exists per queue only while one consumer handles one message at a time.

Definition: key-based serialization: hash(key) % workers picks a lane; each lane runs jobs sequentially. The broker equivalents: a Kafka partition key, an SQS FIFO MessageGroupId, a RabbitMQ consistent-hash exchange or single active consumer.

1  events: o-1:created, o-2:created, o-1:paid, o-2:paid
2  lane(o-1) = 0, lane(o-2) = 3
3  lane 0 runs: o-1:created, o-1:paid       (in order)
4  lane 3 runs: o-2:created, o-2:paid       (in order, in parallel with lane 0)

Real scenario: order state machines, account ledgers, document edits: out-of-order paid before created corrupts state.

BrokerOrdering unitParallelism
KafkaPartitionOne consumer per partition in a group
SQS FIFOMessage groupMany groups in parallel
RabbitMQQueue (one consumer)Consistent-hash exchange or sharding plugin, or an in-process keyed pool
WatermillWhatever the Pub/Sub givesRouter handlers run concurrently per message
go
// Package ordering preserves order per key while processing different keys in
// parallel: every key is hashed to one fixed worker, and each worker handles
// its queue strictly in sequence. This is what a Kafka partition or an SQS
// FIFO message group gives you from the broker.
package ordering

import (
	"hash/fnv"
	"sync"
)

// Pool runs jobs on a fixed number of workers.
type Pool struct {
	lanes []chan func()
	wg    sync.WaitGroup
}

// New starts workers goroutines, each with a buffered lane.
func New(workers, buffer int) *Pool {
	p := &Pool{lanes: make([]chan func(), workers)}
	for i := range p.lanes {
		lane := make(chan func(), buffer)
		p.lanes[i] = lane
		p.wg.Add(1)
		go func() {
			defer p.wg.Done()
			for job := range lane {
				job()
			}
		}()
	}
	return p
}

// Lane returns the worker index for a key. Same key, same lane, always.
func (p *Pool) Lane(key string) int {
	h := fnv.New32a()
	_, _ = h.Write([]byte(key))
	return int(h.Sum32() % uint32(len(p.lanes)))
}

// Submit queues job on the key's lane. It blocks when the lane is full, which
// is the back-pressure that keeps a slow key from growing memory without bound.
// Submit must not be called after Close.
func (p *Pool) Submit(key string, job func()) { p.lanes[p.Lane(key)] <- job }

// Close stops accepting jobs and waits for every queued job to finish.
func (p *Pool) Close() {
	for _, l := range p.lanes {
		close(l)
	}
	p.wg.Wait()
}
go
package ordering

import (
	"fmt"
	"sync"
	"testing"
)

func TestPerKeyOrderIsPreservedAcrossKeys(t *testing.T) {
	p := New(4, 8)
	var mu sync.Mutex
	seen := map[string][]int{}
	const keys, perKey = 20, 200
	for i := range perKey {
		for k := range keys {
			key := fmt.Sprintf("order-%d", k)
			p.Submit(key, func() {
				mu.Lock()
				seen[key] = append(seen[key], i)
				mu.Unlock()
			})
		}
	}
	p.Close()
	for key, got := range seen {
		if len(got) != perKey {
			t.Fatalf("%s: %d jobs ran, want %d", key, len(got), perKey)
		}
		for i, v := range got {
			if v != i {
				t.Fatalf("%s: position %d holds %d: order broken", key, i, v)
			}
		}
	}
}

func TestSameKeySameLane(t *testing.T) {
	p := New(8, 1)
	defer p.Close()
	if p.Lane("customer-1") != p.Lane("customer-1") {
		t.Fatal("a key moved between lanes")
	}
	lanes := map[int]bool{}
	for k := range 100 {
		lanes[p.Lane(fmt.Sprint("k", k))] = true
	}
	if len(lanes) < 2 {
		t.Fatal("all keys landed on one lane: no parallelism")
	}
}

Fix / how to use it: a hot key serializes everything behind it; the bounded lane gives back-pressure instead of unbounded memory. For worker pool shapes see Worker Pools & Pipelines.

AWS SQS with aws-sdk-go-v2 {#sqs} Must-know ​

In plain words: SQS is a managed queue. You ask for messages (long polling), they become invisible to other consumers for a while, you delete them when done, and if you do not they reappear.

Common misunderstanding: "Receiving a message removes it." It only hides it for the visibility timeout; DeleteMessage removes it. The SQS guide: "The default visibility timeout for a queue is 30 seconds", and "the visibility timeout has a maximum limit of 12 hours from when the message is first received." If you forget to delete, you will process it again and again, and the receive count climbs towards the DLQ threshold.

Definition: with github.com/aws/aws-sdk-go-v2/service/sqs: ReceiveMessage (WaitTimeSeconds up to 20 for long polling, MaxNumberOfMessages up to 10, VisibilityTimeout, MessageSystemAttributeNames including ApproximateReceiveCount), DeleteMessage (by ReceiptHandle), ChangeMessageVisibility (extend or shorten for one message), SendMessage. The guide says "The maximum long polling wait time is 20 seconds"; long polling cuts empty responses and cost. Standard queues are at-least-once; FIFO queues add MessageGroupId (ordering unit) and MessageDeduplicationId (producer retries inside the deduplication interval are accepted but not delivered twice).

1  ReceiveMessage(WaitTimeSeconds=20)  -> m (ReceiveCount=1), hidden 30 s
2  handler ok     -> DeleteMessage(receipt)           gone
3  handler fails  -> ChangeMessageVisibility(10 s)    visible again later, ReceiveCount=2
4  ... receive count exceeds maxReceiveCount -> moved to the DLQ

Real scenario: an image-processing worker that extends visibility while a long job runs; an SQS-backed consumer in Lambda or on ECS that backs off failing messages by raising the visibility timeout with the receive count.

SettingMeaningGotcha
Visibility timeoutHow long a received message is hiddenShorter than the handler's runtime means duplicates
WaitTimeSeconds 1..20Long polling0 is short polling: more empty receives
maxReceiveCount (redrive policy)Receives before the DLQSet high enough to allow the retries you want
FIFO MessageGroupIdOrdering and concurrency unit; one receive can return up to 10 messages of the same groupThe poller runs a group's messages sequentially and stops the group at the first failure; one slow message blocks its group
FIFO MessageDeduplicationIdProducer-side dedupNot consumer idempotency
Message retentionHow long unprocessed messages liveDLQ retention should be longer than the source queue's
go
// Package sqsq is a long-polling SQS consumer built on aws-sdk-go-v2. The
// decisions (when to delete, how long to hide a failed message) live in plain
// code over a small API interface, so tests use a fake queue.
package sqsq

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"strconv"
	"sync"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/sqs"
	"github.com/aws/aws-sdk-go-v2/service/sqs/types"
)

// API is the subset of *sqs.Client the consumer uses.
type API interface {
	ReceiveMessage(ctx context.Context, in *sqs.ReceiveMessageInput, opts ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error)
	DeleteMessage(ctx context.Context, in *sqs.DeleteMessageInput, opts ...func(*sqs.Options)) (*sqs.DeleteMessageOutput, error)
	ChangeMessageVisibility(ctx context.Context, in *sqs.ChangeMessageVisibilityInput, opts ...func(*sqs.Options)) (*sqs.ChangeMessageVisibilityOutput, error)
	SendMessage(ctx context.Context, in *sqs.SendMessageInput, opts ...func(*sqs.Options)) (*sqs.SendMessageOutput, error)
}

var _ API = (*sqs.Client)(nil)

// NewClient loads the default credential chain and region. Expected, not run.
func NewClient(ctx context.Context) (*sqs.Client, error) {
	cfg, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		return nil, fmt.Errorf("sqsq: load aws config: %w", err)
	}
	return sqs.NewFromConfig(cfg), nil
}

// Poller receives batches with long polling and settles each message.
type Poller struct {
	API      API
	QueueURL string
	Handler  func(ctx context.Context, m types.Message) error

	Workers        int           // parallel handlers per batch
	BatchSize      int32         // MaxNumberOfMessages, 1..10
	WaitSeconds    int32         // long polling: 1..20, 0 would be short polling
	DrainTimeout   time.Duration // how long running handlers get after shutdown starts
	BaseRetryDelay time.Duration // first hide time after a failure
	MaxRetryDelay  time.Duration // cap (SQS allows at most 12 hours)
}

// RetryDelay is the visibility timeout to set after the nth receive failed:
// base * 2^(n-1), capped. SQS counts receives itself (ApproximateReceiveCount),
// so the consumer needs no state and a restart does not reset the schedule.
func RetryDelay(receiveCount int, base, max time.Duration) time.Duration {
	d := base
	for i := 1; i < receiveCount && d < max; i++ {
		d *= 2
	}
	return min(d, max)
}

// Run polls until ctx is canceled. Handlers that are already running get
// DrainTimeout to finish; their settle calls use a context that is not canceled,
// so finished work is deleted instead of becoming a redelivery.
func (p *Poller) Run(ctx context.Context) error {
	for {
		out, err := p.API.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{
			QueueUrl:            aws.String(p.QueueURL),
			MaxNumberOfMessages: p.BatchSize,
			WaitTimeSeconds:     p.WaitSeconds,
			MessageSystemAttributeNames: []types.MessageSystemAttributeName{
				types.MessageSystemAttributeNameApproximateReceiveCount,
				types.MessageSystemAttributeNameMessageGroupId,
			},
			MessageAttributeNames: []string{"All"},
		})
		if err != nil {
			if ctx.Err() != nil {
				return ctx.Err()
			}
			return fmt.Errorf("sqsq: receive: %w", err)
		}
		p.handleBatch(ctx, out.Messages)
		if ctx.Err() != nil {
			return ctx.Err()
		}
	}
}

// handleBatch runs one batch. Messages of the same FIFO message group go to one
// goroutine and run strictly in order (a receive may return up to 10 messages of
// one group); different groups run in parallel up to Workers. Messages without a
// group each get their own goroutine.
//
// Shutdown: handlers get a context that is not canceled when ctx is, but ends
// DrainTimeout after ctx ends. No handler starts after ctx ended; unstarted
// messages simply reappear when their visibility timeout expires.
func (p *Poller) handleBatch(ctx context.Context, msgs []types.Message) {
	settle := context.WithoutCancel(ctx)
	hctx, cancelHandlers := context.WithCancel(settle)
	defer cancelHandlers()
	stop := context.AfterFunc(ctx, func() { time.AfterFunc(p.DrainTimeout, cancelHandlers) })
	defer stop()

	var order []string
	lanes := map[string][]types.Message{}
	for i, m := range msgs {
		key := m.Attributes[string(types.MessageSystemAttributeNameMessageGroupId)]
		if key == "" {
			key = fmt.Sprintf("\x00single-%d", i)
		}
		if _, ok := lanes[key]; !ok {
			order = append(order, key)
		}
		lanes[key] = append(lanes[key], m)
	}

	sem := make(chan struct{}, max(p.Workers, 1))
	var wg sync.WaitGroup
	for _, key := range order {
		lane := lanes[key]
		sem <- struct{}{}
		wg.Add(1)
		go func() {
			defer wg.Done()
			defer func() { <-sem }()
			for _, m := range lane {
				if ctx.Err() != nil {
					return // shutting down: do not start more work
				}
				if err := p.Handler(hctx, m); err != nil {
					p.fail(settle, m)
					return // keep order: later messages of this group wait
				}
				// Delete only after success. If this call fails the message
				// reappears when the visibility timeout ends: at-least-once.
				_, _ = p.API.DeleteMessage(settle, &sqs.DeleteMessageInput{
					QueueUrl:      aws.String(p.QueueURL),
					ReceiptHandle: m.ReceiptHandle,
				})
			}
		}()
	}
	wg.Wait()
}

// fail leaves the message in the queue and sets how long it stays hidden.
func (p *Poller) fail(ctx context.Context, m types.Message) {
	n, _ := strconv.Atoi(m.Attributes[string(types.MessageSystemAttributeNameApproximateReceiveCount)])
	d := RetryDelay(n, p.BaseRetryDelay, p.MaxRetryDelay)
	_, _ = p.API.ChangeMessageVisibility(ctx, &sqs.ChangeMessageVisibilityInput{
		QueueUrl:          aws.String(p.QueueURL),
		ReceiptHandle:     m.ReceiptHandle,
		VisibilityTimeout: int32(d / time.Second),
	})
}

// SendFIFO sends to a FIFO queue. Messages with the same groupID are delivered
// in order (one receive can return several of them, so the consumer must also
// process them in order, as handleBatch does); different groupIDs run in parallel.
// dedupID makes a resend within the deduplication interval a no-op.
func SendFIFO(ctx context.Context, api API, queueURL, groupID, dedupID, body string) error {
	_, err := api.SendMessage(ctx, &sqs.SendMessageInput{
		QueueUrl:               aws.String(queueURL),
		MessageBody:            aws.String(body),
		MessageGroupId:         aws.String(groupID),
		MessageDeduplicationId: aws.String(dedupID),
	})
	if err != nil {
		return fmt.Errorf("sqsq: send fifo: %w", err)
	}
	return nil
}

// RedrivePolicy is the value of the RedrivePolicy queue attribute that sends a
// message to the dead-letter queue after maxReceiveCount failed receives.
func RedrivePolicy(dlqARN string, maxReceiveCount int) (string, error) {
	if dlqARN == "" || maxReceiveCount < 1 {
		return "", errors.New("sqsq: need a DLQ ARN and maxReceiveCount >= 1")
	}
	b, err := json.Marshal(map[string]any{"deadLetterTargetArn": dlqARN, "maxReceiveCount": maxReceiveCount})
	return string(b), err
}
go
package sqsq

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

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sqs"
	"github.com/aws/aws-sdk-go-v2/service/sqs/types"
)

type fakeSQS struct {
	mu        sync.Mutex
	batches   [][]types.Message
	deleted   []string
	hidden    map[string]int32
	lastRecv  *sqs.ReceiveMessageInput
	cancelAll context.CancelFunc
}

func (f *fakeSQS) ReceiveMessage(ctx context.Context, in *sqs.ReceiveMessageInput, _ ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) {
	f.mu.Lock()
	defer f.mu.Unlock()
	f.lastRecv = in
	if len(f.batches) == 0 {
		f.cancelAll() // queue drained: stop the poller
		return &sqs.ReceiveMessageOutput{}, nil
	}
	b := f.batches[0]
	f.batches = f.batches[1:]
	return &sqs.ReceiveMessageOutput{Messages: b}, nil
}

func (f *fakeSQS) DeleteMessage(_ context.Context, in *sqs.DeleteMessageInput, _ ...func(*sqs.Options)) (*sqs.DeleteMessageOutput, error) {
	f.mu.Lock()
	defer f.mu.Unlock()
	f.deleted = append(f.deleted, *in.ReceiptHandle)
	return &sqs.DeleteMessageOutput{}, nil
}

func (f *fakeSQS) ChangeMessageVisibility(_ context.Context, in *sqs.ChangeMessageVisibilityInput, _ ...func(*sqs.Options)) (*sqs.ChangeMessageVisibilityOutput, error) {
	f.mu.Lock()
	defer f.mu.Unlock()
	f.hidden[*in.ReceiptHandle] = in.VisibilityTimeout
	return &sqs.ChangeMessageVisibilityOutput{}, nil
}

func (f *fakeSQS) SendMessage(_ context.Context, in *sqs.SendMessageInput, _ ...func(*sqs.Options)) (*sqs.SendMessageOutput, error) {
	f.mu.Lock()
	defer f.mu.Unlock()
	f.deleted = append(f.deleted, *in.MessageGroupId+"/"+*in.MessageDeduplicationId)
	return &sqs.SendMessageOutput{}, nil
}

func grouped(handle, group string) types.Message {
	m := msg(handle, handle, "1")
	m.Attributes["MessageGroupId"] = group
	return m
}

func msg(handle, body, receives string) types.Message {
	return types.Message{
		ReceiptHandle: aws.String(handle), Body: aws.String(body), MessageId: aws.String("id-" + handle),
		Attributes: map[string]string{"ApproximateReceiveCount": receives},
	}
}

func TestPollerDeletesOnSuccessAndHidesOnFailure(t *testing.T) {
	ctx, cancel := context.WithCancel(t.Context())
	f := &fakeSQS{hidden: map[string]int32{}, cancelAll: cancel, batches: [][]types.Message{
		{msg("h-ok", "good", "1"), msg("h-bad-1", "bad", "1"), msg("h-bad-3", "bad", "3")},
	}}
	p := &Poller{
		API: f, QueueURL: "https://sqs.eu-west-1.amazonaws.com/123456789012/orders", Workers: 3, BatchSize: 10, WaitSeconds: 20,
		BaseRetryDelay: 10 * time.Second, MaxRetryDelay: 15 * time.Minute,
		Handler: func(_ context.Context, m types.Message) error {
			if *m.Body == "bad" {
				return errors.New("downstream 503")
			}
			return nil
		},
	}
	if err := p.Run(ctx); !errors.Is(err, context.Canceled) {
		t.Fatalf("Run = %v", err)
	}
	if len(f.deleted) != 1 || f.deleted[0] != "h-ok" {
		t.Fatalf("deleted = %v, want only h-ok", f.deleted)
	}
	if f.hidden["h-bad-1"] != 10 || f.hidden["h-bad-3"] != 40 {
		t.Fatalf("hidden = %v, want 10 s after receive 1 and 40 s after receive 3", f.hidden)
	}
	if f.lastRecv.WaitTimeSeconds != 20 || f.lastRecv.MaxNumberOfMessages != 10 {
		t.Fatalf("receive params = %+v", f.lastRecv)
	}
}

func TestRetryDelayDoublesAndCaps(t *testing.T) {
	base, max := 10*time.Second, time.Minute
	want := map[int]time.Duration{1: 10 * time.Second, 2: 20 * time.Second, 3: 40 * time.Second, 4: time.Minute, 9: time.Minute}
	for n, w := range want {
		if got := RetryDelay(n, base, max); got != w {
			t.Fatalf("RetryDelay(%d) = %v, want %v", n, got, w)
		}
	}
}

func TestSendFIFOSetsGroupAndDedupIDs(t *testing.T) {
	f := &fakeSQS{hidden: map[string]int32{}}
	if err := SendFIFO(t.Context(), f, "q", "customer-7", "evt-1", "{}"); err != nil {
		t.Fatal(err)
	}
	if f.deleted[0] != "customer-7/evt-1" {
		t.Fatalf("got %v", f.deleted)
	}
}

func TestRedrivePolicyJSON(t *testing.T) {
	got, err := RedrivePolicy("arn:aws:sqs:eu-west-1:123456789012:orders-dlq", 5)
	if err != nil {
		t.Fatal(err)
	}
	want := `{"deadLetterTargetArn":"arn:aws:sqs:eu-west-1:123456789012:orders-dlq","maxReceiveCount":5}`
	if got != want {
		t.Fatalf("got %s", got)
	}
	if _, err := RedrivePolicy("", 5); err == nil {
		t.Fatal("empty ARN accepted")
	}
}

func TestSameGroupMessagesAreHandledInOrder(t *testing.T) {
	ctx, cancel := context.WithCancel(t.Context())
	f := &fakeSQS{hidden: map[string]int32{}, cancelAll: cancel, batches: [][]types.Message{
		{grouped("g1-a", "g1"), grouped("g1-b", "g1"), grouped("g2-a", "g2")},
	}}
	var mu sync.Mutex
	var order []string
	p := &Poller{API: f, QueueURL: "q", Workers: 4, BatchSize: 10, WaitSeconds: 20, BaseRetryDelay: time.Second, MaxRetryDelay: time.Minute,
		Handler: func(_ context.Context, m types.Message) error {
			if *m.Body == "g1-a" {
				time.Sleep(60 * time.Millisecond) // the first message is slow
			}
			mu.Lock()
			order = append(order, *m.Body)
			mu.Unlock()
			return nil
		}}
	_ = p.Run(ctx)
	pos := map[string]int{}
	for i, id := range order {
		pos[id] = i
	}
	if len(order) != 3 || pos["g1-a"] > pos["g1-b"] {
		t.Fatalf("order = %v: g1-b overtook g1-a inside one message group", order)
	}
	if pos["g2-a"] > pos["g1-a"] {
		t.Fatalf("order = %v: another group should not wait behind g1", order)
	}
}

func TestFailedMessageHoldsBackItsGroup(t *testing.T) {
	ctx, cancel := context.WithCancel(t.Context())
	f := &fakeSQS{hidden: map[string]int32{}, cancelAll: cancel, batches: [][]types.Message{
		{grouped("g1-a", "g1"), grouped("g1-b", "g1")},
	}}
	var started []string
	var mu sync.Mutex
	p := &Poller{API: f, QueueURL: "q", Workers: 2, BatchSize: 10, WaitSeconds: 20, BaseRetryDelay: time.Second, MaxRetryDelay: time.Minute,
		Handler: func(_ context.Context, m types.Message) error {
			mu.Lock()
			started = append(started, *m.Body)
			mu.Unlock()
			return errors.New("boom")
		}}
	_ = p.Run(ctx)
	if len(started) != 1 || len(f.deleted) != 0 {
		t.Fatalf("started=%v deleted=%v: g1-b must not run after g1-a failed", started, f.deleted)
	}
}

func TestShutdownIsBoundedByDrainTimeout(t *testing.T) {
	ctx, cancel := context.WithCancel(t.Context())
	f := &fakeSQS{hidden: map[string]int32{}, cancelAll: cancel, batches: [][]types.Message{{msg("h1", "stuck", "1")}}}
	p := &Poller{API: f, QueueURL: "q", Workers: 1, BatchSize: 10, WaitSeconds: 20, BaseRetryDelay: time.Second, MaxRetryDelay: time.Minute,
		DrainTimeout: 50 * time.Millisecond,
		Handler: func(hctx context.Context, m types.Message) error {
			cancel() // SIGTERM arrives while the handler is running
			<-hctx.Done()
			return hctx.Err()
		}}
	done := make(chan struct{})
	go func() { _ = p.Run(ctx); close(done) }()
	select {
	case <-done:
	case <-time.After(2 * time.Second):
		t.Fatal("Run did not return: the handler context never ended")
	}
}

func TestNoNewHandlerStartsAfterShutdown(t *testing.T) {
	ctx, cancel := context.WithCancel(t.Context())
	f := &fakeSQS{hidden: map[string]int32{}, cancelAll: cancel, batches: [][]types.Message{
		{msg("a", "a", "1"), msg("b", "b", "1"), msg("c", "c", "1")},
	}}
	var started atomic.Int32
	p := &Poller{API: f, QueueURL: "q", Workers: 1, BatchSize: 10, WaitSeconds: 20, BaseRetryDelay: time.Second, MaxRetryDelay: time.Minute,
		DrainTimeout: time.Second,
		Handler:      func(context.Context, types.Message) error { started.Add(1); cancel(); return nil }}
	_ = p.Run(ctx)
	if n := started.Load(); n != 1 {
		t.Fatalf("%d handlers started, want 1: the rest of the batch must wait for the visibility timeout", n)
	}
}
SQS visibility timeout and redriveQueuedvisible to consumersIn flighthidden for VisibilityTimeoutDeletedDeleteMessageVisible againReceiveCount + 1Dead-letter queuereceives > maxReceiveCountReceiveMessagehandler oktimeout / failurenext receiveredriveLong polling: WaitTimeSeconds up to 20 holds the call open until a message arrives.

Fix / how to use it: on FIFO queues group the batch by MessageGroupId (requested as a system attribute) and process each group in order on one goroutine, as Poller.handleBatch does (the test makes the first message slow and asserts the second does not overtake it); delete only after success, derive the retry delay from ApproximateReceiveCount (the test shows 10 s after receive 1 and 40 s after receive 3, doubling), keep handlers idempotent, and give the client a narrow interface so tests use a fake queue. NewClient calls config.LoadDefaultConfig, the standard credential chain; it is compiled, not run.

SNS fan-out and DLQ redrive {#sns} Important ​

In plain words: Publish once to an SNS topic and several SQS queues each get a copy: pub/sub on AWS. When messages land in a dead-letter queue you can redrive them back to the source after the bug is fixed.

Common misunderstanding: "A DLQ fixes failures." A DLQ stores them. The queue depth alarm and the redrive procedure are the fix. And a FIFO queue needs a FIFO DLQ (standard with standard).

Definition: an SQS queue subscribes to an SNS topic (the SNS guide: "Amazon SQS ... as a subscriber"); each subscribed queue is an independent consumer with its own retries and DLQ. The redrive policy is a JSON attribute on the source queue: {"deadLetterTargetArn":"...","maxReceiveCount":5}. DLQ redrive (the SQS console and API offer it; see the redrive page in the references) moves messages from the DLQ to the source queue or another destination.

1  producer -> SNS topic orders-events
2  SNS -> billing-queue, shipping-queue, search-queue   (one copy each)
3  billing-queue message fails 5 times -> billing-dlq
4  fix deployed -> redrive billing-dlq -> billing-queue

Real scenario: an OrderPlaced event consumed by billing, shipping and analytics at different speeds, each with a DLQ and an alarm on ApproximateNumberOfMessagesVisible.

AWS pieceRoleRabbitMQ analogue
SNS topicFan-outFanout or topic exchange
SQS queuePer-consumer bufferQueue bound to the exchange
Redrive policyFailure thresholdx-delivery-limit plus DLX
DLQ redriveReplay after a fixShovel or replay tool
FIFO topic + FIFO queueOrdered fan-outConsistent-hash exchange

Fix / how to use it: sqsq.RedrivePolicy builds the attribute value and rejects an empty ARN or a count below one; sqsq.SendFIFO shows the two FIFO attributes. Cross-broker background: Other Brokers.

RPC between services over messaging {#rpc} Important ​

In plain words: Sometimes you need an answer, not just a notification. The caller sends a request that says "reply here, and this is my ticket number", and waits for a reply with that ticket number.

Common misunderstanding: "A timeout means the request failed." It means no reply arrived; the server may still process it later. Requests over messaging need idempotent handlers for the same reason as events, and the late reply must be dropped, not delivered to a different caller.

Definition: the EIP patterns Request-Reply and Correlation Identifier. Request carries reply_to (a private reply queue or topic) and correlation_id; the server publishes the answer to reply_to with the same correlation_id; the caller keeps a map from correlation ID to a waiting channel. In RabbitMQ the AMQP properties ReplyTo and CorrelationId exist for this, and the RPC tutorial uses an exclusive callback queue. The implementation here uses Watermill metadata over any Pub/Sub.

1  caller: pending[c-1] = chan; publish request {correlation_id=c-1, reply_to=replies.client-1}
2  server: consume request, compute
3  server: publish reply to replies.client-1 {correlation_id=c-1}
4  caller: dispatcher reads reply, pending[c-1] <- payload
5  caller: Call returns; or ctx deadline -> delete pending[c-1], late reply dropped

Real scenario: a pricing quote, a permissions lookup, or a long job where the HTTP request fans out to a worker and waits a few seconds.

go
// Package rpc implements request-reply over messaging: the caller publishes a
// request carrying a correlation ID and the name of its private reply topic,
// the server answers on that topic with the same correlation ID, and the
// caller matches the reply to the waiting call.
package rpc

import (
	"context"
	"errors"
	"sync"

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

// Metadata keys.
const (
	KeyCorrelationID = "correlation_id"
	KeyReplyTo       = "reply_to"
)

// Client sends requests and waits for matching replies.
type Client struct {
	pub        message.Publisher
	replyTopic string

	mu      sync.Mutex
	pending map[string]chan []byte
}

// NewClient subscribes to its own reply topic (unique per instance) and starts
// dispatching replies until ctx ends.
func NewClient(ctx context.Context, pub message.Publisher, sub message.Subscriber, replyTopic string) (*Client, error) {
	replies, err := sub.Subscribe(ctx, replyTopic)
	if err != nil {
		return nil, err
	}
	c := &Client{pub: pub, replyTopic: replyTopic, pending: map[string]chan []byte{}}
	go func() {
		for m := range replies {
			c.mu.Lock()
			ch, ok := c.pending[m.Metadata.Get(KeyCorrelationID)]
			c.mu.Unlock()
			if ok {
				select {
				case ch <- m.Payload:
				default: // a duplicate reply for a call that already has its answer: drop it
				}
			} // else: a late reply for a call that already gave up; drop it
			m.Ack()
		}
	}()
	return c, nil
}

// ErrNoReply is returned when ctx ends before a reply arrives. The request may
// still be processed: a timeout does not mean "it did not happen".
var ErrNoReply = errors.New("rpc: no reply before the deadline")

// Call publishes the request and waits for the reply or ctx.
func (c *Client) Call(ctx context.Context, topic string, payload []byte) ([]byte, error) {
	id := watermill.NewUUID()
	ch := make(chan []byte, 1)
	c.mu.Lock()
	c.pending[id] = ch
	c.mu.Unlock()
	defer func() {
		c.mu.Lock()
		delete(c.pending, id)
		c.mu.Unlock()
	}()

	req := message.NewMessage(watermill.NewUUID(), payload)
	req.SetContext(ctx) // publishers that honour the message context stop with the call
	req.Metadata.Set(KeyCorrelationID, id)
	req.Metadata.Set(KeyReplyTo, c.replyTopic)

	// Publish has no context parameter and may block (waiting for a broker
	// confirm, for example), so the deadline is enforced around it. A blocked
	// Publish goroutine ends when the publisher gives up; the buffered channel
	// keeps it from leaking on the way out.
	pubErr := make(chan error, 1)
	go func() { pubErr <- c.pub.Publish(topic, req) }()
	select {
	case err := <-pubErr:
		if err != nil {
			return nil, err
		}
	case <-ctx.Done():
		return nil, errors.Join(ErrNoReply, ctx.Err())
	}
	select {
	case reply := <-ch:
		return reply, nil
	case <-ctx.Done():
		return nil, errors.Join(ErrNoReply, ctx.Err())
	}
}

// Serve answers every request on topic with fn's result. If the reply cannot be
// published the request is nacked, so the broker redelivers it and fn must be
// idempotent. Run it as a goroutine or wrap the logic in a router handler.
func Serve(ctx context.Context, pub message.Publisher, sub message.Subscriber, topic string, fn func([]byte) []byte) error {
	reqs, err := sub.Subscribe(ctx, topic)
	if err != nil {
		return err
	}
	go func() {
		for m := range reqs {
			reply := message.NewMessage(watermill.NewUUID(), fn(m.Payload))
			reply.Metadata.Set(KeyCorrelationID, m.Metadata.Get(KeyCorrelationID))
			if to := m.Metadata.Get(KeyReplyTo); to != "" {
				if err := pub.Publish(to, reply); err != nil {
					m.Nack() // the reply is lost unless the request is redelivered
					continue
				}
			}
			m.Ack()
		}
	}()
	return nil
}
go
package rpc

import (
	"context"
	"errors"
	"fmt"
	"sync"
	"sync/atomic"
	"testing"
	"time"

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

func newBus() *gochannel.GoChannel {
	return gochannel.NewGoChannel(gochannel.Config{}, watermill.NopLogger{})
}

func TestConcurrentCallsGetTheirOwnReplies(t *testing.T) {
	bus := newBus()
	if err := Serve(t.Context(), bus, bus, "pricing.quote", func(b []byte) []byte { return append([]byte("quote:"), b...) }); err != nil {
		t.Fatal(err)
	}
	c, err := NewClient(t.Context(), bus, bus, "replies.client-1")
	if err != nil {
		t.Fatal(err)
	}
	var wg sync.WaitGroup
	for i := range 20 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
			defer cancel()
			want := fmt.Sprintf("quote:item-%d", i)
			got, err := c.Call(ctx, "pricing.quote", []byte(fmt.Sprintf("item-%d", i)))
			if err != nil || string(got) != want {
				t.Errorf("call %d: got %q err %v, want %q", i, got, err, want)
			}
		}()
	}
	wg.Wait()
}

func TestTimeoutWhenNobodyServesAndLateReplyIsDropped(t *testing.T) {
	bus := newBus()
	c, err := NewClient(t.Context(), bus, bus, "replies.client-2")
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(t.Context(), 30*time.Millisecond)
	defer cancel()
	if _, err := c.Call(ctx, "nobody.listens", []byte("x")); !errors.Is(err, ErrNoReply) || !errors.Is(err, context.DeadlineExceeded) {
		t.Fatalf("err = %v", err)
	}
	c.mu.Lock()
	n := len(c.pending)
	c.mu.Unlock()
	if n != 0 {
		t.Fatalf("pending = %d: the call leaked its slot", n)
	}
}

// failingFirstReply fails the first publish to a reply topic.
type failingFirstReply struct {
	message.Publisher
	failed atomic.Bool
}

func (f *failingFirstReply) Publish(topic string, msgs ...*message.Message) error {
	if !f.failed.Swap(true) {
		return errors.New("broker unavailable")
	}
	return f.Publisher.Publish(topic, msgs...)
}

func TestFailedReplyPublishIsNotAckedSoTheRequestIsRedelivered(t *testing.T) {
	bus := newBus()
	var handled atomic.Int32
	pub := &failingFirstReply{Publisher: bus}
	if err := Serve(t.Context(), pub, bus, "pricing.quote", func(b []byte) []byte { handled.Add(1); return b }); err != nil {
		t.Fatal(err)
	}
	c, err := NewClient(t.Context(), bus, bus, "replies.client-3")
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
	defer cancel()
	got, err := c.Call(ctx, "pricing.quote", []byte("x"))
	if err != nil || string(got) != "x" {
		t.Fatalf("got %q err %v: the lost reply was not retried", got, err)
	}
	if handled.Load() != 2 {
		t.Fatalf("handler ran %d times, want 2 (the request was nacked and redelivered)", handled.Load())
	}
}

func TestDuplicateRepliesNeverBlockTheDispatcher(t *testing.T) {
	bus := newBus()
	c, err := NewClient(t.Context(), bus, bus, "replies.client-4")
	if err != nil {
		t.Fatal(err)
	}
	// Two registered calls; nobody is reading the first one's channel.
	stuck, other := make(chan []byte, 1), make(chan []byte, 1)
	c.mu.Lock()
	c.pending["dup"], c.pending["other"] = stuck, other
	c.mu.Unlock()

	reply := func(id, body string) {
		m := message.NewMessage(watermill.NewUUID(), []byte(body))
		m.Metadata.Set(KeyCorrelationID, id)
		if err := bus.Publish("replies.client-4", m); err != nil {
			t.Error(err)
		}
	}
	go func() { reply("dup", "first"); reply("dup", "second"); reply("other", "ok") }()
	select {
	case b := <-other:
		if string(b) != "ok" {
			t.Fatalf("other = %q", b)
		}
	case <-time.After(2 * time.Second):
		t.Fatal("a duplicate reply blocked the dispatcher: unrelated replies stopped")
	}
}

type blockingPub struct{ release chan struct{} }

func (b blockingPub) Publish(string, ...*message.Message) error { <-b.release; return nil }
func (b blockingPub) Close() error                              { return nil }

func TestCallDeadlineCoversPublish(t *testing.T) {
	bus := newBus()
	bp := blockingPub{release: make(chan struct{})}
	t.Cleanup(func() { close(bp.release) })
	c, err := NewClient(t.Context(), bp, bus, "replies.client-5")
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)
	defer cancel()
	done := make(chan error, 1)
	go func() { _, err := c.Call(ctx, "slow", []byte("x")); done <- err }()
	select {
	case err := <-done:
		if !errors.Is(err, ErrNoReply) {
			t.Fatalf("err = %v", err)
		}
	case <-time.After(time.Second):
		t.Fatal("Call ignored its deadline while Publish was blocked")
	}
}
RPC over messaging with a correlation IDCallerpending[corr-1]requests topiccorrelation_id, reply_toreplies.client-1private reply topicServerhandler computes1 publish2 consume3 reply, same id4 match by idIf the deadline passes first, the caller deletes pending[corr-1]; a late reply is dropped.

Fix / how to use it: one reply queue per client instance (not per call), a deadline on every Call, and unknown correlation IDs ignored. The plain version above shows the mechanism that any request-reply component implements. Three details the tests pin down: the server nacks the request when the reply cannot be published (so the broker redelivers it and the handler must be idempotent), the dispatcher never blocks on a duplicate reply (a second reply for the same ID is dropped), and the call deadline covers Publish too (the request carries the caller's context, and Call returns at the deadline even if the publisher is blocked). See Request-Reply over REST and AMQP.

When to use gRPC instead {#grpc} Must-know ​

In plain words: If the caller cannot proceed without the answer and needs it in milliseconds, call the service directly. Use messaging when the work can happen later or by many.

Common misunderstanding: "RPC over a broker is more reliable than gRPC." It is more durable (the request survives a consumer outage) and slower, with an extra hop and a queue to operate. It also hides the dependency: the caller still fails if nobody answers.

SituationPreferReason
Interactive query, p99 under 100 msgRPCOne hop, deadlines propagate (deadline propagation)
Streaming resultsgRPCNative streaming
Command that may take minutesMessaging + statusDurable, retryable
Notify N services of a factEventsFan-out, decoupling
Caller and callee deploy independently, burstsMessagingBuffering
Needs strict schema and codegengRPC.proto contract; see gRPC & Protobuf in Go

Fix / how to use it: a common mix is gRPC for queries, events for facts, and a messaging request-reply only where a worker pool behind a queue does the work.

Graceful shutdown of consumers {#shutdown} Must-know ​

In plain words: On SIGTERM stop taking new messages, finish the ones in progress, settle them, then exit.

Common misunderstanding: "Cancel the context and the handler stops safely." Canceling a handler mid-write leaves half-done work and a redelivery. For drain you let in-flight handlers finish (bounded by a timeout) and only stop pulling new work. Giving handlers a context that the shutdown signal does not cancel (context.WithoutCancel, Go 1.21) is how the rabbit.Consumer.Run and sqsq.Poller implement that. "Finish" must stay bounded: WithoutCancel also drops deadlines, so the SQS poller derives the handler context with its own DrainTimeout that starts when shutdown starts, and it starts no new handler once the context is canceled (both are tested); the RabbitMQ consumer bounds each handler with HandlerTimeout.

Definition: signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) gives a context canceled on the signal; Watermill's Router.Run(ctx) closes the router when the context ends, and Router.Close() waits for running handlers up to RouterConfig.CloseTimeout. Kubernetes sends SIGTERM, waits terminationGracePeriodSeconds, then SIGKILL, so the drain timeout must be shorter than the grace period.

1  SIGTERM -> ctx canceled
2  stop subscribing: no new deliveries      (readiness already failing)
3  handler A (in flight) keeps running      -> finishes -> ack
4  router.Close() returns when A is done (or CloseTimeout error)
5  process exits 0;  unacked deliveries return to the queue

Real scenario: rolling deploys that used to duplicate a payment each time because a handler was killed between commit and ack.

go
// Package shutdown runs a Watermill router until a signal arrives and then
// drains: no new messages are taken, handlers that are already running finish
// and are acknowledged, and only then does Serve return.
package shutdown

import (
	"context"
	"errors"
	"os"
	"os/signal"
	"syscall"

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

// Serve starts the router and blocks until ctx is canceled and the router has
// closed (Router.Close waits up to RouterConfig.CloseTimeout for handlers).
func Serve(ctx context.Context, r *message.Router) error {
	runErr := make(chan error, 1)
	go func() { runErr <- r.Run(ctx) }()

	select {
	case <-r.Running():
	case err := <-runErr:
		return err
	}

	select {
	case <-ctx.Done():
	case err := <-runErr:
		return err
	}
	closeErr := r.Close() // bounded by CloseTimeout; returns an error if handlers overrun
	return errors.Join(closeErr, <-runErr)
}

// Main shows the wiring in a real binary: SIGINT (Ctrl-C) and SIGTERM
// (Kubernetes, systemd) cancel the context.
func Main(r *message.Router) error {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	return Serve(ctx, r)
}
go
package shutdown

import (
	"context"
	"sync/atomic"
	"testing"
	"time"

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

func TestServeWaitsForInFlightHandlerAndAcksIt(t *testing.T) {
	ps := gochannel.NewGoChannel(gochannel.Config{BlockPublishUntilSubscriberAck: true}, watermill.NopLogger{})
	r, err := message.NewRouter(message.RouterConfig{CloseTimeout: 5 * time.Second}, watermill.NopLogger{})
	if err != nil {
		t.Fatal(err)
	}
	started := make(chan struct{})
	release := make(chan struct{})
	var finished atomic.Bool
	r.AddConsumerHandler("slow", "jobs", ps, func(m *message.Message) error {
		close(started)
		<-release
		finished.Store(true)
		return nil
	})

	ctx, stop := context.WithCancel(t.Context())
	served := make(chan error, 1)
	go func() { served <- Serve(ctx, r) }()
	<-r.Running()

	acked := make(chan struct{})
	go func() {
		m := message.NewMessage("j-1", []byte("x"))
		_ = ps.Publish("jobs", m) // blocks until the handler acked
		close(acked)
	}()
	<-started
	stop() // SIGTERM while the handler is mid-flight

	select {
	case <-served:
		t.Fatal("Serve returned before the in-flight handler finished")
	case <-time.After(100 * time.Millisecond):
	}
	close(release)
	select {
	case err := <-served:
		if err != nil {
			t.Fatalf("Serve = %v", err)
		}
	case <-time.After(3 * time.Second):
		t.Fatal("Serve did not return after the handler finished")
	}
	if !finished.Load() {
		t.Fatal("handler did not run to completion")
	}
	select {
	case <-acked:
	case <-time.After(time.Second):
		t.Fatal("the in-flight message was never acknowledged")
	}
}

Fix / how to use it: fail /readyz first, then drain, and set the grace period above handler timeout plus drain. The rabbit test TestRunDrainsInFlightWorkOnShutdown proves the same for the raw consumer: the second delivery stays on the broker, the in-flight one is acked. More on signals: OS Processes, Signals & Graceful Shutdown.

Observability: OpenTelemetry messaging spans, metrics, logs {#observability} Important ​

In plain words: A trace that dies at the broker is useless. Put the trace ID in the message so the consumer's span is a child of the publisher's span, and count queue depth, lag, retries and parked messages.

Common misunderstanding: "HTTP tracing middleware covers messaging." The trace context travels in HTTP headers, not through a queue; you inject it into message metadata yourself. The OpenTelemetry messaging conventions describe producer ("send"), consumer ("process") and "settle" spans, and recommend the span name {messaging.operation.name} {destination}.

Definition: a producer span of kind Producer injects W3C traceparent into the metadata; the consumer middleware extracts it and starts a Consumer span as its child with attributes messaging.system.name, messaging.destination.name, messaging.message.id and messaging.operation.type. Watermill also ships Prometheus metrics (PrometheusMetricsBuilder) that wrap publishers, subscribers and handlers.

1  HTTP request, trace T, span S0
2  StartSend: span "publish orders" (child of S0), inject traceparent into metadata
3  broker carries metadata
4  Middleware: Extract -> span "process orders" (child of the publish span, same trace T)
5  handler error -> RecordError, status Error

Real scenario: a slow checkout traced across the API, the outbox relay, the broker and the billing consumer in one trace.

SignalWhat to recordAlert on
MetricQueue depth, oldest message age, consumers per queueDepth and age rising; zero consumers
MetricHandler duration, retries, nacks, parkedParked greater than 0
TracePublish and process spans linkedMissing links
LogMessage ID, correlation ID, attempt, topicPoison reasons
go
// Package tracing links a producer span and a consumer span across a broker:
// the publisher injects the W3C trace context into message metadata, the
// consumer middleware extracts it and starts a "process" span as its child.
package tracing

import (
	"context"

	"github.com/ThreeDotsLabs/watermill/message"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/codes"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/trace"
)

// carrier lets the propagator read and write Watermill metadata.
type carrier message.Metadata

func (c carrier) Get(k string) string { return message.Metadata(c).Get(k) }
func (c carrier) Set(k, v string)     { message.Metadata(c).Set(k, v) }
func (c carrier) Keys() []string {
	keys := make([]string, 0, len(c))
	for k := range c {
		keys = append(keys, k)
	}
	return keys
}

var prop = propagation.TraceContext{}

// attrs follow the OpenTelemetry messaging semantic conventions.
func attrs(system, topic, id, op string) []attribute.KeyValue {
	return []attribute.KeyValue{
		attribute.String("messaging.system.name", system),
		attribute.String("messaging.destination.name", topic),
		attribute.String("messaging.message.id", id),
		attribute.String("messaging.operation.type", op),
	}
}

// StartSend starts the producer span and injects its context into msg. End the
// returned span after Publish returns.
func StartSend(ctx context.Context, tr trace.Tracer, system, topic string, msg *message.Message) (context.Context, trace.Span) {
	ctx, span := tr.Start(ctx, "publish "+topic,
		trace.WithSpanKind(trace.SpanKindProducer),
		trace.WithAttributes(attrs(system, topic, msg.UUID, "send")...))
	prop.Inject(ctx, carrier(msg.Metadata))
	return ctx, span
}

// Middleware starts a consumer span per message, parented on the producer
// span found in the metadata, and records handler errors on it.
func Middleware(tr trace.Tracer, system string) message.HandlerMiddleware {
	return func(h message.HandlerFunc) message.HandlerFunc {
		return func(msg *message.Message) ([]*message.Message, error) {
			topic := message.SubscribeTopicFromCtx(msg.Context())
			parent := prop.Extract(msg.Context(), carrier(msg.Metadata))
			ctx, span := tr.Start(parent, "process "+topic,
				trace.WithSpanKind(trace.SpanKindConsumer),
				trace.WithAttributes(attrs(system, topic, msg.UUID, "process")...))
			defer span.End()
			msg.SetContext(ctx)

			out, err := h(msg)
			if err != nil {
				span.RecordError(err)
				span.SetStatus(codes.Error, err.Error())
			}
			return out, err
		}
	}
}
go
package tracing

import (
	"errors"
	"sync/atomic"
	"testing"
	"time"

	"github.com/ThreeDotsLabs/watermill"
	"github.com/ThreeDotsLabs/watermill/message"
	"github.com/ThreeDotsLabs/watermill/pubsub/gochannel"
	"go.opentelemetry.io/otel/codes"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	"go.opentelemetry.io/otel/sdk/trace/tracetest"
)

func TestConsumerSpanIsChildOfProducerSpan(t *testing.T) {
	exp := tracetest.NewInMemoryExporter()
	tp := sdktrace.NewTracerProvider(sdktrace.WithSyncer(exp))
	tr := tp.Tracer("test")

	ps := gochannel.NewGoChannel(gochannel.Config{}, watermill.NopLogger{})
	router, err := message.NewRouter(message.RouterConfig{}, watermill.NopLogger{})
	if err != nil {
		t.Fatal(err)
	}
	router.AddMiddleware(Middleware(tr, "gochannel"))
	done := make(chan struct{})
	var calls atomic.Int32
	router.AddConsumerHandler("h", "orders", ps, func(*message.Message) error {
		if calls.Add(1) == 1 {
			return errors.New("boom") // first delivery fails and is redelivered
		}
		close(done)
		return nil
	})
	go func() { _ = router.Run(t.Context()) }()
	<-router.Running()
	t.Cleanup(func() { _ = router.Close() })

	msg := message.NewMessage("m-1", []byte("x"))
	_, prod := StartSend(t.Context(), tr, "gochannel", "orders", msg)
	if err := ps.Publish("orders", msg); err != nil {
		t.Fatal(err)
	}
	prod.End()
	<-done
	// the consumer span ends right after the handler returns
	deadline := time.Now().Add(2 * time.Second)
	for len(exp.GetSpans()) < 3 && time.Now().Before(deadline) {
		time.Sleep(5 * time.Millisecond)
	}

	var send tracetest.SpanStub
	var processes []tracetest.SpanStub
	for _, s := range exp.GetSpans() {
		switch s.Name {
		case "publish orders":
			send = s
		case "process orders":
			processes = append(processes, s)
		}
	}
	if send.Name == "" || len(processes) != 2 {
		t.Fatalf("want 1 send span and 2 process spans, got %v", exp.GetSpans())
	}
	for _, p := range processes {
		if p.Parent.SpanID() != send.SpanContext.SpanID() || p.SpanContext.TraceID() != send.SpanContext.TraceID() {
			t.Fatal("consumer span is not a child of the producer span: the trace broke at the broker")
		}
	}
	if processes[0].Status.Code != codes.Error || processes[1].Status.Code != codes.Unset {
		t.Fatalf("statuses = %v, %v; want Error then Unset", processes[0].Status.Code, processes[1].Status.Code)
	}
}

Fix / how to use it: log the message ID and correlation ID on every line; the test asserts both consumer spans (the first delivery fails, the redelivery succeeds) share the producer's trace and parent. Metric and trace pipelines are covered in Observability and Messaging Observability.

Testing with GoChannel pub/sub and fakes {#testing} Must-know ​

In plain words: You can test almost every consumer decision without a broker: use Watermill's in-memory Pub/Sub for flows, a small fake for acknowledgements, and an in-memory store for the database.

Common misunderstanding: "Without RabbitMQ the tests are not real." The risky logic (ack or park, retry counts, dedup, drain, order) is plain Go. What needs a real broker is the thin adapter (amqp.Channel calls), which is also the part you cannot get wrong in a way a unit test would catch.

TechniqueUsed forExample here
GoChannelRouter flows, middleware, CQRSafter, cqrsdemo, rpc, shutdown
amqp.Delivery{Acknowledger: fake}Settle decisionsrabbit.Dispatch table test
Interface + fakeConfirmations, SQS clientfakeConf, fakeSQS
In-memory transactional storeInbox, outboxmemDB, memStore
BlockPublishUntilSubscriberAckDeterministic ack timingshutdown test
middleware.DuplicatorProve idempotencyAdd to the router in a test
Tracetest exporterSpan relationstracing

Fix / how to use it: wait on channels and router.Running(), never time.Sleep as a synchronisation tool (the tests use short sleeps only to prove that something did not happen). Run with -race.

Mechanics ​

Exact errors, codes and knobs Must-know ​

WhereText or nameMeaningWhat to do
AMQP406 PRECONDITION_FAILEDRedeclare with different argumentsNew queue name or policy
AMQP404 NOT_FOUND on publish to a missing exchangeChannel closed by the brokerDeclare first; recreate the channel
AMQPamqp.ErrClosed (reason "channel/connection is not open", code ChannelError)Operation on a closed connection or channelRebuild the session (reconnect)
AMQPbasic.return (via NotifyReturn)Mandatory message was unroutableAlert; fix binding
amqp091-go*DeferredConfirmation.WaitContext returns (false, nil)Broker nackErrNacked, retry
amqp091-goWaitContext returns a context errorNo confirm in timeErrUnconfirmed, retry with the same ID
Watermillrouter close timeoutHandlers outlived CloseTimeoutRaise it or shorten handlers
WatermillDuplicateHandlerNameError (panic)Two handlers, one nameUnique names
Watermillreason_poisoned metadataWhy a message reached the poison topicRead it first when triaging
SQSOverLimit for in-flight messagesToo many received but not deletedDelete promptly; fewer pollers
SQSFIFO send without MessageGroupIdFIFO queues need a group ID on every sendSet it (see SendFIFO)

amqp.ErrClosed and its text come from amqp091-go types.go, OverLimit from the SQS visibility-timeout page, the dead-letter reasons and x-delivery-count from the RabbitMQ docs. The AMQP codes 406 and 404 are standard AMQP 0-9-1 reply codes not taken from a saved page.

KnobDefault or rangeNotes
AMQP prefetch (Qos)Unlimited unless set; Watermill AMQP default 1Start near handler concurrency times 2
AMQP DeliveryModeTransient unless amqp.PersistentPair with a durable queue
RabbitMQ dead-letter reasonsrejected, expired, maxlen, delivery_limitIn x-death
Quorum queue delivery limitx-delivery-limit; count in x-delivery-countSince RabbitMQ 4.3 based on delivery count, per the quorum queue doc
SQS visibility timeout30 s default, 12 h maximumExtend per message with ChangeMessageVisibility
SQS long pollingWaitTimeSeconds 1..20Set on the queue or per call
SQS batchMaxNumberOfMessages 1..10Per receive
Watermill RetryMaxRetries N means N+1 callsSee the test
Watermill GoChannelOutputChannelBuffer, Persistent, BlockPublishUntilSubscriberAckTests only

What each product really does {#products} Important ​

BehaviourRabbitMQSQS standardSQS FIFOKafkaNATS JetStreamRedis Streams
Consumer acknowledgementAck/Nack/RejectDeleteMessageDeleteMessageOffset commitMessage ackStream entry ack
Retry delayTTL queue + DLXVisibility timeoutVisibility timeoutRetry topicDelayed redeliveryRe-claim idle entries
Dead letterDLX, delivery limitRedrive to DLQRedrive to FIFO DLQDead-letter topic by conventionAdvisory + own streamOwn stream
Ordering unitQueueNoneMessage groupPartitionStreamStream
ReplayStreams onlyNoNoYes (offsets)YesYes
Fan-outExchange to many queuesSNS to many queuesSNS FIFOConsumer groupsConsumersConsumer groups

(The Kafka, NATS and Redis Streams columns are a summary, not taken from pages saved for this chapter; for details see Other Brokers and Kafka; this page deals with them only through Watermill's Pub/Sub interface.)

Solving the classic problems ​

ProblemSolutionHowCost
Lost message after crashAck after commit; durable + confirmsDispatch, EmitterDuplicates become possible
Duplicate effectIdempotent consumerInbox row or natural keyTable + pruning
Event lost between DB and brokerOutboxSame-transaction insert + relayRelay to run
Poison message blocks the queueRetry cap + parkingRetry, PoisonQueue, DLXSomeone must look at the parking lot
Retry storm hammers a failing dependencyBackoff with jitter, ThrottleBackoff.Delay, RetryDelayLatency
Silent idle consumer after a broker restartSupervisorSuperviseRe-declare logic
Order violatedKey lanes or broker groupsordering.PoolHot key bottleneck
Deploy duplicates workDrainRun, ServeGrace period
Trace breaks at the brokerInject/extracttracingMetadata field

Retry and failure handling {#retry-table} Important ​

ErrorMeaningRetry?
Bad payload, unknown type, schema version too newPermanentNo: park
Business rule violated (insufficient funds)Permanent for this messageNo: park or emit a failure event
Timeout, 503, deadlock, connection resetTransientYes, with backoff
context.Canceled from shutdownNot the message's faultRequeue, uncounted
Parking itself failedInfrastructureRequeue, alert

Rules: classify errors where they happen (wrap permanent ones in ErrPermanent), cap attempts, add jitter (Backoff.Delay picks a random value in the upper half of the exponential step so consumers do not retry in lockstep), keep a per-attempt time budget below the broker's timeout, and always record why a message was parked.

Choosing ​

SituationRecommendationExtra techniqueReason
New Go service, broker not decidedWatermill + GoChannel in testsSwap the Pub/Sub laterHandlers stay the same
Need exact RabbitMQ control (TTL, DLX, priorities)Raw amqp091-goTopology, ConsumerEvery knob is visible
AWS-native, no serversSQS (+ SNS)Visibility-based backoff, DLQManaged
Strict per-entity order at scaleKafka partitions or SQS FIFO groupsKeyed lanesBroker ordering unit
Need an answer within 100 msgRPCDeadlinesSee gRPC
Fan-out to many servicesTopic or SNSOwn queue per serviceIndependent failure
Event must follow a DB writeOutboxInbox on the consumerAtomic with the data
Sequence of steps across servicesSagaSaga PatternCompensations
Simple background jobs in one appA queue library or Go channelsWorker PoolsNo broker needed

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

An in-process event bus (Watermill GoChannel, or a plain channel) decouples modules inside one binary: orders publishes OrderPlaced, billing handles it. Because everything dies together, losing an in-flight event on a crash is the risk; a Postgres outbox plus a relay in the same process removes it without any broker. Keep handlers idempotent from day one: moving to a real broker later should not change their contract.

Modular monolith and multiple databases ​

Each module owns its tables and an outbox; modules consume each other's events through a queue per consumer. The first real broker usually arrives here (RabbitMQ or SQS). The module that owns a queue declares it. Consumers keep their own inbox table, scoped by consumer name, so two modules can process the same ID.

Microservices ​

A flow across services: orders commits the order and an outbox row; the relay publishes orders.placed with confirms; billing and shipping each have a queue bound to the exchange, an inbox, retries through a TTL queue and a parking lot; billing replies to a stock-reservation request through a reply queue with a correlation ID.

1  orders:   BEGIN; INSERT order; INSERT outbox(e-1); COMMIT
2  relay:    publish e-1 to exchange orders (key orders.placed), wait confirm
3  billing:  deliver e-1 -> inbox insert -> charge -> ack
4  shipping: deliver e-1 -> inbox insert -> create label -> ack
5  billing:  charge fails (503) -> nack -> retry queue 5 s -> deliver again (inbox row rolled back) -> ok
6  shipping: payload version 2 unknown -> ErrPermanent -> parked -> ack

What survives a service boundary: the message ID, the correlation ID, the trace context, the schema version. What does not: transactions (use sagas and compensations), ordering across keys, and "exactly once" (use inbox tables).

Distributed data: replicas, caches, sharded databases, multi-region ​

A consumer that reads a replica right after an event may not see the committed row (replica lag): read from the primary or retry on "not found yet". Caches invalidated by events need ordering per key and idempotent invalidation. Cross-region: one broker per region and replicate events, or a single global queue with higher latency; quorum queues and Kafka replicate within a cluster, not across oceans, without a shovel or mirror tool. Dead-letter and parking queues must live where operators can reach them.

Scaling path: 1×, 10×, 100× ​

LoadShapeWhat changes
1× (hundreds of events per minute)One consumer per queue, prefetch 1 to 10Nothing special; outbox polling every second
10×Several consumers per queue, prefetch tuned, keyed lanes where order mattersCompeting consumers; watch queue age
100×Partitioned topics or sharded queues, batch confirms, CDC for the outbox, autoscaling on lagPer-key hot spots, larger inbox pruning, partition planning

Lab ​

1. Run the tests (real) ​

cd docs/snippets/go/event-driven-go/go
export PATH=/opt/homebrew/bin:$PATH
gofmt -l .            # no output
go vet ./...
go test -race -count=1 ./...
# ok  academy/event-driven-go/after       1.505s
# ok  academy/event-driven-go/before      1.350s
# ok  academy/event-driven-go/cqrsdemo    1.360s
# ok  academy/event-driven-go/envelope    1.432s
# ok  academy/event-driven-go/inbox       1.413s
# ok  academy/event-driven-go/ordering    1.423s
# ok  academy/event-driven-go/outbox      1.419s
# ok  academy/event-driven-go/rabbit      1.430s
# ok  academy/event-driven-go/rpc         1.676s
# ok  academy/event-driven-go/shutdown    2.080s
# ok  academy/event-driven-go/sqsq        1.934s
# ok  academy/event-driven-go/tracing     1.367s

2. Prove a duplicate is harmless (real) ​

go test -race -count=1 -run 'TestDuplicateDeliveryIsAppliedOnce|TestRedeliveryCreditsTwice' -v ./after ./before
# --- PASS: TestRedeliveryCreditsTwice          (the "before" consumer credits 200)
# --- PASS: TestDuplicateDeliveryIsAppliedOnce  (the "after" router credits 100)

3. Break the retry and read the poison reason (real) ​

go test -race -count=1 -run TestExhaustedRetriesGoToPoisonQueue -v ./after
# the test asserts Apply ran 4 times and metadata reason_poisoned == "permanent failure"

4. RabbitMQ against a real broker (expected, not run) ​

The entry point is cmd/rabbitdemo/main.go. Nothing below was run on the build machine (no broker installed).

# 1  start a broker (terminal A)
docker run -d --name rmq -p 5672:5672 -p 15672:15672 rabbitmq:4-management
export AMQP_URL=amqp://guest:guest@localhost:5672/
cd docs/snippets/go/event-driven-go/go

# 2  consume: declares exchange orders, queues orders.created.q, .retry (TTL 5000 ms) and .dead (terminal B)
go run ./cmd/rabbitdemo consume
#    management UI http://localhost:15672 (guest/guest): three quorum queues; the work queue shows
#    x-dead-letter-strategy=at-least-once and x-overflow=reject-publish in its arguments

# 3  emit a good message (terminal C)
go run ./cmd/rabbitdemo emit orders.created '{"n":1}'
#    expected output: confirmed id=demo-... key=orders.created      consumer log: handled id=demo-...

# 4  emit to a routing key nothing is bound to
go run ./cmd/rabbitdemo emit orders.typo '{"n":1}'
#    expected: exit status 1 with err containing "rabbit: mandatory publish matched no queue"

# 5  emit a message whose handler always fails
go run ./cmd/rabbitdemo emit orders.created '{"fail":true}'
#    expected consumer log: the message comes back about every 5 s from the retry queue and
#    x-death count grows; after MaxAttempts=3 the log shows  parked id=...  and the message is acked

# 6  stop the consumer with Ctrl-C while a message is being handled: in-flight work finishes first

5. SQS with a DLQ (expected, not run) ​

The entry point is cmd/sqsdemo/main.go. It needs AWS credentials and an account; the traffic is a handful of requests.

export AWS_REGION=eu-west-1
# 1  create the dead-letter queue and read its ARN
DLQ_URL=$(aws sqs create-queue --queue-name orders-dlq --query QueueUrl --output text)
DLQ_ARN=$(aws sqs get-queue-attributes --queue-url "$DLQ_URL" --attribute-names QueueArn --query Attributes.QueueArn --output text)

# 2  create the work queue with the redrive policy (maxReceiveCount 3)
cat > /tmp/orders-attrs.json <<JSON
{"VisibilityTimeout":"30","RedrivePolicy":"{\"deadLetterTargetArn\":\"$DLQ_ARN\",\"maxReceiveCount\":\"3\"}"}
JSON
export QUEUE_URL=$(aws sqs create-queue --queue-name orders --attributes file:///tmp/orders-attrs.json --query QueueUrl --output text)

# 3  send one message and poll with a handler that always fails
cd docs/snippets/go/event-driven-go/go
go run ./cmd/sqsdemo send 1
FAIL=1 go run ./cmd/sqsdemo poll
#    the demo sets BaseRetryDelay=10s and MaxRetryDelay=15m, so after receive 1, 2 and 3 the poller sets
#    the visibility timeout to 10 s, 20 s and 40 s (sqsq.RetryDelay, covered by a unit test). Expected log:
#    received ... receives=1  /  about 10 s later receives=2  /  about 20 s later receives=3
#    after the third failed receive SQS moves the message to orders-dlq

# 4  inspect the DLQ, then redrive after a fix
aws sqs receive-message --queue-url "$DLQ_URL"
#    start a DLQ redrive to the source queue from the SQS console, then run poll without FAIL=1

For PHP/Laravel developers ​

Laravel queues are the closest analogue: a job class is serialised to a queue connection (database, Redis, Amazon SQS and others, per the Laravel 13 queue docs) and a queue:work process runs it. Laravel events and listeners are in-process by default; a listener implementing ShouldQueue becomes a queued job. The differences that matter to a Go developer: Laravel hides the acknowledgement (the worker deletes the job on success, releases it on exception, moves it to failed_jobs after tries), there is no broker-level publish/subscribe fan-out unless you add one, and the unit of work is a job addressed to one handler (a command), not a fact consumed by many.

php
// Laravel: an event whose listener runs on the queue; retries and backoff are properties of the job.
class OrderPlaced { public function __construct(public string $orderId) {} }

class ChargeCustomer implements ShouldQueue
{
    public int $tries = 5;
    public array $backoff = [5, 30, 120];                // seconds between attempts
    public function handle(OrderPlaced $e): void { /* must be idempotent, like any consumer */ }
    public function failed(OrderPlaced $e, \Throwable $x): void { /* the "parking lot" hook */ }
}
LaravelGo with Watermill or AMQP
dispatch(new Job)CommandBus.Send or Emitter.Emit
event(new OrderPlaced) + queued listenerEventBus.Publish + EventProcessor handlers
$tries, $backoffmiddleware.Retry, delay queues
failed_jobs tablePoison topic or parking queue
queue:workRouter.Run or Consumer.Run
--stop-when-empty, queue:restartGraceful drain on SIGTERM
Horizon metricsPrometheus metrics, queue depth alarms
ShouldBeUnique, WithoutOverlappingInbox row, keyed lanes
after_commit / afterCommit (dispatch only after the DB commit)Not an outbox: the docs say Laravel "will wait until the open parent database transactions have been committed before actually dispatching the job" and discards the job on rollback, but a crash between the commit and the dispatch loses it. An outbox stores the pending message inside the transaction

The Laravel queues/events comparison in one line: Laravel gives you the worker, the retries and the failed-jobs table out of the box and hides the broker; in Go you assemble the same pieces and gain control of confirms, topology and exact acknowledgement.

Common misconceptions ​

BeliefReality
The broker guarantees exactly-onceAt-least-once; exactly-once effects come from idempotent handlers
A confirm means the consumer processed itIt means the broker took responsibility
Nack(requeue=true) is a retry strategyIt is a hot loop; use a delay queue
Auto-ack is fine for "unimportant" messagesA crash drops the whole prefetch window
Durable queue means durable messagesMessages also need persistent delivery mode (and confirms)
Watermill topic equals AMQP topic exchangeIt generates exchange, queue and routing key from configuration
MaxRetries: 3 means three attemptsFour calls: one attempt plus three retries
Poison queue deletes bad messagesIt moves them and acks the original
SQS ReceiveMessage removes the messageDeleteMessage does; receive only hides it
FIFO queue means consumer idempotency is unnecessaryDeduplication covers producer retries in a window only
Cancelling the context is a graceful shutdownStop pulling, let in-flight handlers finish, then exit
An outbox makes delivery exactly-onceIt makes publishing reliable (at-least-once)
Messaging RPC is more reliable than gRPCMore durable, slower; it hides dependencies

Cheat sheet ​

TopicWhat to remember
GuaranteeAt-least-once; design for duplicates
AckAfter the effect is committed
PublishConfirms + persistent + mandatory; same message ID on retry
PrefetchPer consumer; roughly 2x concurrency to start
RetryDelay queue or visibility timeout; cap attempts
PoisonPark with the reason; alert; replay after the fix
IdempotencyInbox row in the business transaction
OutboxSame-transaction insert; relay with SKIP LOCKED
OrderingPer key (lane, partition, message group)
Watermill orderCorrelationID, PoisonQueue, Retry, Recoverer, handler
SQSLong poll 20 s; delete on success; visibility from receive count
RPCreply_to + correlation_id; deadline; drop late replies
ShutdownStop pulling, drain, then exit; grace above drain
TracingInject traceparent into metadata; consumer span is the child
TestsGoChannel + fakes + -race

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A consumer finishes its work, and the process dies before the ack. What happens, and how do you make that safe? Must-know ​

Answer

Answer: The broker redelivers the message (Redelivered is true), so the work runs twice. Make the handler idempotent: insert the message ID into an inbox table in the same transaction as the effect (ON CONFLICT DO NOTHING), or use a naturally idempotent update. See Inbox.

2 — What does a publisher confirm tell you, and what does it not? Must-know ​

Answer

Answer: It tells you the broker took responsibility for the message (for a quorum queue, after replication). It says nothing about consumption. Without confirms, a successful Publish call only means the frame was written to the connection. mandatory additionally returns unroutable messages. See the emitter.

3 — Why is Nack with requeue=true a poor retry, and what replaces it in RabbitMQ? Must-know ​

Answer

Answer: It puts the message back immediately, so a failing message spins and starves others, with no delay or counter. Use Nack(false, false) with a dead-letter exchange to a TTL retry queue that dead-letters back, and read x-death to count failures and park after the limit. See delayed retry.

4 — In Watermill, why does PoisonQueue return a nil error, and what is the middleware order? Important ​

Answer

Answer: After publishing the failed message to the poison topic with reason_poisoned metadata it returns nil, so the router acks the original: the failure has been moved. Add middleware outermost first: CorrelationID, PoisonQueue, Retry, Recoverer, so Retry gives up before the poison queue catches the final error and Recoverer turns panics into retryable errors.

5 — Retry{MaxRetries: 3} is configured. How many times does the handler run for a message that always fails? Important ​

Answer

Answer: Four: the first attempt plus three retries, with exponentially growing, jittered waits. The after test asserts exactly four calls before the message reaches the poison topic.

6 — What problem does the transactional outbox solve, and why must the relay tolerate duplicates? Must-know ​

Answer

Answer: A database commit and a broker publish cannot be atomic, so either the event or the state change can be lost. The outbox writes the event row in the same transaction as the state change; a relay publishes later. A crash after publishing but before marking the row republishes it, so the delivery is at-least-once and consumers dedupe on the stable message UUID. See Outbox.

7 — In SQS, you receive a message and your handler takes longer than the visibility timeout. What happens? Important ​

Answer

Answer: The message becomes visible again and another consumer (or you) receives it, a duplicate with a higher ApproximateReceiveCount; your later DeleteMessage with the old receipt handle may fail. Extend the timeout with ChangeMessageVisibility during long work (the 12-hour maximum counts from first receive), shorten the work, and be idempotent.

8 — How do you keep events of one order in sequence while processing many orders in parallel? Important ​

Answer

Answer: Serialise per key: hash the order ID to a fixed lane (worker) in process, or use the broker's ordering unit: a Kafka partition key, an SQS FIFO MessageGroupId. A requeue or several competing consumers on one RabbitMQ queue break order, so plan for it. See Ordering.

9 — How does request-reply over messaging match a reply to the right caller, and what happens on timeout? Important ​

Answer

Answer: The request carries a correlation_id and a reply_to topic unique to the caller instance; the server copies the correlation ID into the reply; the caller's dispatcher looks it up in a pending map. On timeout the caller removes the entry and returns an error; a late reply finds no entry and is dropped. The request may still be processed, so the server handler must be idempotent.

10 — When should you choose gRPC over messaging RPC? Must-know ​

Answer

Answer: When the caller needs the answer now (interactive latency), wants streaming, or wants a strict generated contract and propagated deadlines. Choose messaging when the work can complete later, must survive the callee being down, or many services react to a fact. See When to use gRPC.

11 — How do you shut a consumer down without dropping or duplicating in-flight work? Must-know ​

Answer

Answer: Fail readiness, stop taking new deliveries, let running handlers finish under a context that the signal does not cancel (context.WithoutCancel), settle them, then exit within the orchestrator's grace period. Watermill's Router.Close does the waiting up to CloseTimeout. Unsettled deliveries return to the queue.

12 — How do you connect a producer's trace to the consumer's trace across a broker? Good to know ​

Answer

Answer: Inject the W3C traceparent into the message metadata when publishing (producer span, kind Producer), extract it in consumer middleware and start a Consumer span as the child, with messaging.* attributes. HTTP tracing middleware does not do this for you.

Glossary ​

TermMeaning
At-least-onceDelivery guarantee: one or more times, never silently zero
At-most-onceZero or one delivery; ack before work
Ack / Nack / RejectPositive acknowledgement; negative (can be multiple); negative for one delivery
Prefetch (Qos)Maximum unacknowledged deliveries per consumer
Publisher confirmBroker's basic.ack/basic.nack for a published message
mandatoryPublish flag: return the message if no queue matched
DurableExchange or queue that survives a broker restart
PersistentMessage delivery mode written to disk
ExchangeAMQP routing entity that receives published messages
BindingRule linking an exchange to a queue by key
Quorum queueReplicated RabbitMQ queue type (Raft)
Dead-letter exchange (DLX)Exchange that receives rejected, expired or over-limit messages
x-deathHeader recording each dead-lettering with queue, reason and count
Retry queueTTL queue with no consumers that dead-letters back to the main exchange
Parking lotQueue or table for messages given up on, inspected by a human
Poison messageA message that fails every time it is processed
Idempotent consumerConsumer whose repeated processing has the same effect as once
Inbox tableTable of processed message IDs written in the business transaction
Outbox tableTable of events written in the business transaction, published later
RelayProcess that moves outbox rows to the broker
Message envelopeFixed header (ID, type, occurred_at, trace, correlation) around a payload
Correlation IDIdentifier tying a request, its events and replies
Reply queuePrivate queue or topic where replies to one caller arrive
RouterWatermill component running handlers with middleware
Pub/SubWatermill name for a Publisher plus Subscriber for one broker
GoChannelWatermill's in-memory Pub/Sub
Command bus / event busTyped senders of commands (one handler) and events (many)
Visibility timeoutSQS period a received message is hidden from other consumers
Long pollingSQS receive that waits up to 20 s for messages
FIFO queueSQS queue with ordering per message group and deduplication
MessageGroupIdSQS FIFO ordering and concurrency unit
Redrive policySQS attribute naming the DLQ and maxReceiveCount
SNS fan-outOne SNS topic delivering to many SQS queues
traceparentW3C Trace Context header carrying trace and span IDs
In-flight drainLetting running handlers finish during shutdown

References ​

Built by Morteza Negahi