Skip to main content
The cpubsub package (from gocopper/pkg) allows your packages to publish events without knowing who consumes them. Two backends are included: an in-process local backend, and a Redis backend for when multiple processes need to hear about events. To get started, install the package:

The PubSub Interface

Both backends implement the same small interface:
Choose a backend by adding the corresponding wire module to your app:

Publishing Events

You should define topics as package constants so that subscribers may import them:
If you are publishing as part of a database transaction, you may wish to publish from an OnCommit callback so that the event is only sent once the transaction commits. To learn more, see Transactions.

Subscribing to Topics

It is most common to subscribe in a constructor so that the subscription is in place when the app starts:
Handlers run on managed background goroutines, and subscriptions remain active until the app shuts down.

Payloads Across Backends

The local backend hands your handler the exact Go value you published. The Redis backend, however, serializes payloads as JSON, so handlers receive the decoded form (a map[string]any for structs). If a handler needs the typed struct, you may convert it by marshaling and unmarshaling again:
cpubsub is fire-and-forget: handler errors are logged but not retried, and there are no delivery guarantees or acknowledgments. In addition, the Redis backend broadcasts to every subscribed process. For work that must not be lost, or must run exactly once, consider persisting a job row and letting a worker claim it instead. See Background Work.