Data & infrastructure/PubSub
PubSub
Typed publish/subscribe messaging with broadcast delivery, consumer groups, wildcards, and transactional outbox support.
On this page
github.com/fletchhq/fletch/pubsub is a stdlib-only publish/subscribe package with an in-process memory broker. Production backends live in standalone modules so you only pull in the driver your deployment uses: pubsub/postgres, pubsub/nats, pubsub/sns, and pubsub/redis.
Topics and Publishing
Declare topics once as package-level values parameterized by their payload type. Publishing and subscribing against the same Topic[T] keeps serialization and handler signatures checked by the compiler.
package orders
import (
"context"
"github.com/fletchhq/fletch/pubsub"
)
type OrderCreated struct {
OrderID string `json:"order_id"`
Total int64 `json:"total"`
}
var Created = pubsub.NewTopic[OrderCreated]("orders.created")
func EmitCreated(ctx context.Context, bus *pubsub.Bus, evt OrderCreated) error {
return pubsub.Publish(ctx, bus, Created, evt, pubsub.WithMeta("tenant", "acme"))
}
Handlers use the signature func(ctx context.Context, m *pubsub.Message[T]) error. Returning an error signals a processing failure to the underlying broker or middleware.
Subscribing
pubsub supports three subscription modes: broadcast, consumer groups, and wildcard patterns.
Broadcast
By default, pubsub.Subscribe registers a broadcast subscription. Every running replica receives every message published to the topic, which fits LiveView updates and in-memory cache invalidation.
err := pubsub.Subscribe(ctx, bus, orders.Created, func(ctx context.Context, m *pubsub.Message[orders.OrderCreated]) error {
// Broadcast to every replica.
return nil
})
Consumer Groups
Pass pubsub.WithGroup to run competing durable consumers. Within a named group, only one replica processes each event, while separate groups each receive their own copy.
err := pubsub.Subscribe(
ctx,
bus,
orders.Created,
func(ctx context.Context, m *pubsub.Message[orders.OrderCreated]) error {
// Processed by one replica in the "billing" group.
return nil
},
pubsub.WithGroup("billing"),
)
Wildcard Patterns
Use pubsub.SubscribePattern to subscribe across multiple dot-separated topic names:
*matches a single segment (for example,"orders.*"matches"orders.created"and"orders.cancelled").>matches one or more trailing segments (for example,"orders.>"matches"orders.created"and"orders.line.updated").
err := pubsub.SubscribePattern(ctx, bus, "orders.*", func(ctx context.Context, m *pubsub.Message[any]) error {
return nil
})
Wiring the Bus, Middleware, and Decode Errors
Create a *pubsub.Bus with pubsub.NewBus, attach middleware with pubsub.Use, and register the bus on your Fletch app with fletch.WithPubSub(bus).
bus := pubsub.NewBus(
broker,
pubsub.Use(
pubsub.Recover(),
pubsub.Logger(slog.Default()),
),
)
app := fletch.New(
fletch.WithPubSub(bus),
)
Additional bus options cover tracing, observation, and malformed payloads:
| Option | Purpose |
|---|---|
pubsub.Use(...) |
Wraps handlers with middleware such as pubsub.Recover() and pubsub.Logger(...). |
pubsub.WithTraceInjector(...) |
Injects trace context into outgoing message metadata on publish. |
pubsub.WithTraceExtractor(...) |
Extracts trace context into the handler context.Context on receive. |
pubsub.WithObserver(...) |
Hooks into publish and delivery lifecycle events for metrics or inspection. |
pubsub.WithOnDecodeError(...) |
Custom handler invoked when a message payload fails to decode into T. |
Undecodable messages are never dropped silently. When WithOnDecodeError is not configured, decode failures are logged.
Transactional Publishing and the Outbox
Use pubsub.PublishTx when an event must commit atomically with a database write:
if err := pubsub.PublishTx(ctx, bus, tx, orders.Created, evt); err != nil {
return err
}
pubsub/postgres handles PublishTx natively inside the caller’s transaction. For brokers without native SQL transaction support (such as NATS, SNS, or Redis), attach the SQL outbox to the bus:
bus := pubsub.NewBus(
broker,
pubsub.WithOutbox(
db,
pubsub.WithOutboxInterval(500*time.Millisecond),
pubsub.WithOutboxMaxAttempts(10),
),
)
Generate the outbox table DDL for your SQL dialect with pubsub.OutboxSchemaSQL(dialect). The outbox relay polls committed rows and publishes them to the wrapped broker. Messages that fail relay after WithOutboxMaxAttempts attempts (default 10) are dead-lettered.
Backends
| Backend | Module | Broadcast | Consumer Groups | Wildcards | Native PublishTx |
|---|---|---|---|---|---|
| Memory | pubsub |
Yes | Yes | Yes | No (use WithOutbox) |
| Postgres | pubsub/postgres |
Yes | Yes | Yes | Yes |
| NATS JetStream | pubsub/nats |
Yes | Yes | Native * and > |
No (use WithOutbox) |
| AWS SNS | pubsub/sns |
Webhook (WebhookHandler) |
SNS to SQS fan-out | No | No (use WithOutbox) |
| Redis | pubsub/redis |
Redis Pub/Sub | Redis Streams (XREADGROUP) |
Yes | No (use WithOutbox) |
broker := pubsub.Memory()
bus := pubsub.NewBus(broker)import "github.com/fletchhq/fletch/pubsub/postgres"
broker, err := postgres.New(
dsnOrPool,
postgres.WithTable("fletch_pubsub_messages"),
postgres.WithChannel("fletch_pubsub"),
postgres.WithRetention(24*time.Hour),
postgres.WithPollInterval(2*time.Second),
postgres.WithMaxAttempts(10),
postgres.WithRetryDelay(5*time.Second),
postgres.WithVisibilityTimeout(30*time.Second),
)import "github.com/fletchhq/fletch/pubsub/nats"
broker, err := nats.New(
serverURL,
nats.WithStream("EVENTS"),
nats.WithSubjectPrefix("app"),
nats.WithMaxAge(7*24*time.Hour),
nats.WithAckWait(30*time.Second),
)import "github.com/fletchhq/fletch/pubsub/sns"
broker, err := sns.New(
snsClient,
sns.WithTopicARNs(topicARNs),
sns.WithSQS(sqsClient),
sns.WithGroupQueues(groupQueues),
)import "github.com/fletchhq/fletch/pubsub/redis"
broker, err := redis.New(redisURL)Backend Notes
Memory (pubsub.Memory) runs in-process with support for both consumer groups and wildcard patterns, suited for local development, tests, and single-node deployments.
Postgres (pubsub/postgres) stores messages in a backing table (created via postgres.SchemaSQL()) and uses LISTEN/NOTIFY for wakeup. Each NOTIFY carries a row pointer instead of the full payload, avoiding Postgres’s 8000-byte NOTIFY limit, while sequence catch-up ensures missed notifications are read from the table. PublishTx writes straight into the caller’s Postgres transaction.
NATS JetStream (pubsub/nats) maps topic wildcards directly to NATS * and > subjects. In addition to the options shown above, nats.WithMemoryStorage() switches stream storage to memory for ephemeral or test streams, and nats.WithNATSOptions(...) passes options through to the underlying NATS client.
AWS SNS (pubsub/sns) splits delivery by subscription mode:
- Consumer groups use SNS-to-SQS fan-out configured via
sns.WithSQS,sns.WithGroupQueues, andsns.WithQueueResolver. - Broadcast delivery mounts
broker.WebhookHandler(), which verifies AWS X.509 message signatures and handles subscription confirmation (configured withsns.WithAutoConfirm). - Dynamic topic lookup can be supplied with
sns.WithTopicResolverin place of a staticsns.WithTopicARNsmap. - Wrap the broker with
pubsub.WithOutbox(db)if you needPublishTx.
Redis (pubsub/redis) uses Redis Pub/Sub for broadcast subscriptions and Redis Streams (XREADGROUP) for durable consumer groups.