outbox

package
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 11 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package outbox publishes messages to a message broker reliably, with the transactional outbox pattern.

It takes three steps:

  • New returns an Outbox for a taskmill.Client.
  • Outbox.Store saves each Message in the same transaction as the business data that produced it, so a message exists if and only if that data was committed.
  • Outbox.AddRelay registers a relay on a worker. The relay publishes the stored messages through a Publisher, which wraps any broker client: Kafka, NATS, RabbitMQ, or another.

Messages with the same topic and key are published one at a time, in the order they were stored. A message that cannot be published is retried for about a month; then it is dead, and its key halts until an operator retries or deletes it, so later messages never overtake it.

Publishing is at least once: a message can be published twice, for example if the worker crashes after the broker accepted it. Every delivery carries an ID that stays the same across retries, so consumers can deduplicate. The receiving side needs no package: a consumer that enqueues a task for each message, with the message ID as taskmill.EnqueueOptions.DedupeKey, creates at most one task per message within the dedupe window.

The outbox guide shows each step with a broker.

Example

This example stores an event with the business change that produced it, and relays stored events to a broker.

package main

import (
	"context"
	"log"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"

	"github.com/code19m/taskmill"
	"github.com/code19m/taskmill/outbox"
)

func main() {
	ctx := context.Background()
	var pool *pgxpool.Pool      // the application's pool
	var client *taskmill.Client // from taskmill.NewClient
	ob := outbox.New(client)

	err := pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
		if _, err := tx.Exec(ctx, "UPDATE orders SET status = 'paid' WHERE id = 42"); err != nil {
			return err
		}
		return ob.Store(ctx, taskmill.Pgx(tx), outbox.Message{
			Topic: "orders",
			Key:   []byte("42"),
			Value: []byte(`{"type": "order.paid", "order_id": 42}`),
		})
	})
	if err != nil {
		log.Fatal(err)
	}

	var handlers taskmill.Handlers
	ob.AddRelay(&handlers, outbox.PublisherFunc(func(_ context.Context, ds []outbox.Delivery) []error {
		errs := make([]error, len(ds)) // nil: published
		for _, d := range ds {
			log.Printf("publish %s to %s with key %s", d.ID, d.Topic, d.Key) // your broker client here
		}
		return errs
	}), nil) // nil: the default RelayOptions
	worker, err := taskmill.NewWorker(client, &taskmill.WorkerConfig{Handlers: &handlers}) // serves outbox.Queue
	if err != nil {
		log.Fatal(err)
	}
	_ = worker.Run(ctx)
}

Index

Examples

Constants

View Source
const Queue = "outbox"

Queue is the taskmill queue that holds stored messages, as tasks of the kind "taskmill.outbox.message". A worker with a relay reads it by default. A published message is deleted right away: it is not kept in the task history.

Variables

This section is empty.

Functions

This section is empty.

Types

type Delivery

type Delivery struct {
	Message

	// ID is unique across services and stays the same when a delivery is
	// retried, so consumers can deduplicate by it. It is a UUIDv7.
	ID string

	// Metadata is the metadata that [taskmill.EnqueueMiddleware] stored with
	// the message, such as the trace context of the transaction that stored
	// it.
	Metadata map[string]string
}

Delivery is a stored message on its way to the broker.

type Message

type Message struct {
	// Topic is the broker destination, such as a Kafka topic. Required.
	Topic string

	// Key orders messages: messages with the same topic and key are
	// published one at a time, in the order they were stored. Messages
	// without a key are published in any order. Default: none.
	Key []byte

	// Value is the message body. The topic, the key, the value, and the
	// headers are stored base64-encoded in one task payload, whose 1 MiB
	// limit allows about 750 KiB of Value. Default: empty.
	Value []byte

	// Headers are passed to the broker with the message. They share the
	// size limit of Value. Default: none.
	Headers map[string][]byte
}

Message is an event to publish. Save it with Outbox.Store.

type Outbox

type Outbox struct {
	// contains filtered or unexported fields
}

Outbox stores messages and relays them to a broker. Create one with New and share it: it is safe for concurrent use.

func New

func New(client *taskmill.Client) *Outbox

New returns an outbox that keeps its messages in client's database. With a nil client, Outbox.Store returns an error that wraps taskmill.ErrInvalidArgument.

func (*Outbox) AddRelay

func (*Outbox) AddRelay(hs *taskmill.Handlers, pub Publisher, opts *RelayOptions)

AddRelay registers the batch handler that publishes stored messages through pub. opts may be nil. A worker with no Queues set reads Queue for it. taskmill.NewWorker reports a nil pub, or options out of range, as an error that wraps taskmill.ErrInvalidArgument.

func (*Outbox) Store

func (o *Outbox) Store(ctx context.Context, tx taskmill.Executor, msgs ...Message) error

Store saves msgs in the outbox inside the caller's transaction, so they are published only if the transaction commits. A message without a topic or over the payload limit (see Message.Value), or a call over the limits of taskmill.Client.EnqueueMany, 10,000 messages and 64 MiB, fails with an error that wraps taskmill.ErrInvalidArgument, and leaves the transaction usable. A call with no messages does nothing.

type Publisher

type Publisher interface {
	Publish(ctx context.Context, deliveries []Delivery) []error
}

Publisher sends deliveries to a broker. It returns one error per delivery, in the same order: nil marks that delivery as published, an error retries it later, and an error wrapped with taskmill.Permanent makes it dead right away. A batch holds at most RelayOptions.BatchSize deliveries. Of the deliveries that have a key, no two in a batch have the same topic and key. Deliveries without a key have no order to keep, so a batch can hold many of one topic. Each call has RelayOptions.Timeout: then its context is canceled, and the deliveries without a nil result are retried.

A delivery without a result is retried, as after an error: Publish returned nil, or fewer errors than deliveries. Nil never means that all were published. So a publisher that ends in "return nil" after it sent its deliveries sends them all again at each retry, until they are dead. When all were published, return make([]error, len(deliveries)).

A failed delivery is retried after 1 second, then after twice as long each time, up to every 5 minutes, with ±10% jitter. After 10,000 tries, about a month, the message is dead.

type PublisherFunc

type PublisherFunc func(ctx context.Context, deliveries []Delivery) []error

PublisherFunc adapts a function to the Publisher interface.

Example

This example shows the contract of a publisher: one error per delivery, in the same order. Nil marks a delivery as published, an error retries it later, and a permanent error makes its message dead right away.

package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/code19m/taskmill"
	"github.com/code19m/taskmill/outbox"
)

func main() {
	pub := outbox.PublisherFunc(func(_ context.Context, ds []outbox.Delivery) []error {
		errs := make([]error, len(ds))
		for i, d := range ds {
			switch {
			case len(d.Value) == 0:
				errs[i] = taskmill.Permanent(errors.New("empty event")) // no retry can fix it
			case d.Topic == "payments":
				errs[i] = errors.New("broker is down") // your broker client's error
			}
		}
		return errs
	})

	// The relay of a worker calls the publisher. This example calls it
	// itself, to show the results.
	errs := pub.Publish(context.Background(), []outbox.Delivery{
		{ID: "1", Message: outbox.Message{Topic: "orders", Value: []byte(`{"order_id": 42}`)}},
		{ID: "2", Message: outbox.Message{Topic: "payments", Value: []byte(`{"order_id": 42}`)}},
		{ID: "3", Message: outbox.Message{Topic: "orders"}},
	})
	for i, err := range errs {
		fmt.Printf("delivery %d: %v\n", i+1, err)
	}
}
Output:
delivery 1: <nil>
delivery 2: broker is down
delivery 3: permanent: empty event

func (PublisherFunc) Publish

func (f PublisherFunc) Publish(ctx context.Context, deliveries []Delivery) []error

Publish calls f(ctx, deliveries).

type RelayOptions added in v0.3.0

type RelayOptions struct {
	// BatchSize is the most deliveries that one call of the publisher
	// receives. It must not be negative. Default: 100. Maximum: 1,000.
	BatchSize int

	// Timeout bounds each call of the publisher. It must not be negative.
	// Default: 1 minute.
	Timeout time.Duration
}

RelayOptions configure a relay. The zero value keeps the defaults.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL