Reliability & governance helpers
Last updated:
Beyond produce/consume, the Go core ships optional, stdlib-only subpackages that
mechanise the reliability and governance contracts the wire spec defines. None touch the
frozen envelope (schema_version: 1); each is a tooling layer over the codec. They are the
Go face of the cross-SDK spec — follow the linked spec page for the full contract.
Idempotency
idempotency.Wrap(store, handler) makes a handler run at most once per meta.id, even
on at-least-once redelivery.
import "github.com/babelqueue/babelqueue-go/idempotency"
store := idempotency.NewInMemoryStore() // tests / single process
app.Handle("urn:babel:orders:created", idempotency.Wrap(store, handler))
For a fleet, two persistent stores ship as separate submodules (so the core stays
driver-free) — both also expose an atomic Claim(ctx, id) (bool, error) to close the
in-flight race:
import (
idempgres "github.com/babelqueue/babelqueue-go/idempotency-postgres"
idempredis "github.com/babelqueue/babelqueue-go/idempotency-redis"
)
pg, _ := idempgres.New(ctx, "postgres://…", idempgres.WithTTL(24*time.Hour))
_ = pg.Migrate(ctx) // CREATE TABLE IF NOT EXISTS
// or: rd, _ := idempredis.New("redis://…", idempredis.WithPrefix("bq:idemp:"))
See Idempotency and the store deep-dive.
Transactional outbox
The …/outbox subpackage removes the producer dual write: persist the encoded envelope
in the same DB transaction as your business row, then a relay publishes the durable rows
verbatim.
import "github.com/babelqueue/babelqueue-go/outbox"
store := outbox.NewInMemoryStore() // production: a DB-backed outbox.Store
box := outbox.New(store)
// inside YOUR DB transaction, beside the business write — no commit of its own:
env, _ := babelqueue.Make("urn:babel:orders:created", data, babelqueue.WithQueue("orders"))
id, _ := box.Write(env) // encodes via the frozen codec, calls Store.Save
// later, a relay drains the durable rows to the broker:
relay := outbox.NewRelay(transport, store, outbox.Options{})
res, _ := relay.Drain(ctx, 0) // res.Published / res.Failed
outbox.Store is the four-method contract (Save / FetchUnpublished / MarkPublished /
MarkFailed); the transaction boundary is yours. See
Transactional Outbox.
DLQ redrive & replay-bypass
babelqueue.Redrive(ctx, transport, dlq, RedriveOptions{…}) moves dead-lettered messages
back onto a queue — dead_letter removed, attempts reset to 0, everything else preserved
— with DryRun, Select, ToQueue (sandbox) and Bypass. The replay guard skips effects
that already fired:
res, _ := babelqueue.Redrive(ctx, transport, "orders.dlq", babelqueue.RedriveOptions{
ToQueue: "orders.sandbox",
Bypass: true, // stamp bq-replay-bypass (header-carrying transport)
})
app.Handle("urn:babel:orders:created", func(ctx context.Context, env babelqueue.Envelope) error {
saveOrder(env) // idempotent core — always runs
return babelqueue.BypassExternalEffects(ctx, func() error {
return sendEmail(env) // external effect — skipped on replay
})
})
On Kafka, Redrive keeps the DLQ record’s key (null stays null, empty stays empty) on the
write back to the work topic and on every restore write back to the DLQ. A restore write is
acknowledged only after it succeeds; if it fails, the message is not acknowledged, so its offset
is not committed. When the transport implements Rewinder (the Kafka transport does: it drops its group reader, so
the next Pop resumes from the last committed offset), Redrive also hands the record back, because Kafka offset commits are cumulative: a later commit
could otherwise move the group past it and lose it. If the rewind fails too, both errors are
returned together (errors.Join). A new consumer (for example after a restart) resumes from the
record in any case.
See DLQ redrive & replay-bypass.
GDPR field encryption
The …/gdpr subpackage encrypts only the data leaves a schema marks x-gdpr-sensitive, in
place. gdpr.Protect / gdpr.Unprotect are free functions over the schema’s
SensitivePaths(); Cipher is caller-bound and AESGCMCipher is the stdlib reference.
Validate cleartext — protect after validation on produce, unprotect before validation on
consume.
import (
"github.com/babelqueue/babelqueue-go/gdpr"
"github.com/babelqueue/babelqueue-go/schema"
)
cipher, _ := gdpr.NewAESGCMCipher(key) // or bind a KMS to gdpr.Cipher
provider, _ := schema.NewDirProvider("registry/registry.json")
sch, _, _ := provider.Schema("urn:babel:orders:created")
_ = gdpr.Protect(data, sch, cipher) // producer: encrypt marked leaves
if err := gdpr.Unprotect(data, sch, cipher); errors.Is(err, gdpr.ErrDecrypt) {
// wrong key / tampered → retry / dead-letter
}
OpenTelemetry (spans, metrics and traceparent)
The …/otel submodule emits a send <queue> span on publish and a process <queue> span per
handled message, plus the standard metrics, and — on a header-carrying transport —
injects/extracts the W3C traceparent so a consumer span is a true child of the producer span
(degrading to trace_id correlation otherwise). Every Go transport module carries the header on
its broker’s native metadata channel.
Dashboard-breaking change. Spans are now
send <queue>/process <queue>(they werepublish <urn>/process <urn>), and the URN is thebabelqueue.urnattribute. Passsystemsomessaging.systemis the broker. Not passing it is deprecated. The migration table is in Observability.
The options are functional options shared by all three entry points:
| Option | Meaning |
|---|---|
otel.WithSystem("kafka") |
the messaging.system value (the broker) |
otel.WithConsumerGroup("billing") |
messaging.consumer.group.name, consumer span only |
otel.WithMeter(meter) |
a metric.Meter; without it nothing is recorded as a metric |
otel.SemconvVersion (1.44.0) and otel.SchemaURL are public constants: create the tracer
and the meter with the schema URL (tp.Tracer("orders", trace.WithSchemaURL(otel.SchemaURL))).
import (
babelqueue "github.com/babelqueue/babelqueue-go"
bqotel "github.com/babelqueue/babelqueue-go/otel"
)
// dead-letter observer: feeds babelqueue.dlq.messages from the consume runtime
app := babelqueue.NewApp(transport,
babelqueue.WithDeadLetterObserver(bqotel.NewDeadLetterObserver(
bqotel.WithSystem("redis"), bqotel.WithMeter(meter))))
// consumer: "process <queue>" span + consumed / retries / duration metrics
app.Handle("urn:babel:orders:created", bqotel.WrapHandler(tracer, handleOrderCreated,
bqotel.WithSystem("redis"), bqotel.WithMeter(meter)))
// producer: "send <queue>" span + sent metric
pub := bqotel.NewPublisher(tracer, app, bqotel.WithSystem("redis"), bqotel.WithMeter(meter))
id, err := pub.Publish(ctx, "urn:babel:orders:created", map[string]any{"order_id": 1042})
otel.Publish(ctx, tracer, app, urn, data, opts...) keeps its signature but takes
babelqueue.Options, so it cannot carry WithSystem or WithMeter; build a Publisher for
those. Publisher is built once and reused, because its metric instruments are created per
Publisher.
Where the observer is wired. The Go runtime (App) has one dead-letter chokepoint, so
babelqueue.WithDeadLetterObserver covers every Go transport module (Redis, AMQP, SQS, Kafka,
Pulsar, Azure Service Bus, Artemis). An observer that panics is recovered and logged; it never
changes how the message is settled. The Azure Service Bus transport implements
SettleNativeDeadLetter, so its native dead-letters count; the SQS native settle is a no-op and
never counts.
What babelqueue.dlq.messages counts. It counts a dead-letter the SDK itself carried out
and confirmed: a record written to the BabelQueue DLQ, and a native dead-letter the SDK
initiated (on Azure Service Bus, the SDK’s own DeadLetterMessage / deadLetter call made when
the BabelQueue DLQ is off). There is no attribute that tells the two apart. It does not count a
dead-letter the broker makes on its own (MaxDeliveryCount, SQS RedrivePolicy), the SQS
native no-op, a failed DLQ write, or a message dropped because DLQ writing is disabled.
On Azure Service Bus, do not add this counter to the broker’s own dead-letter metric: the
messages the SDK dead-letters natively are in both, so the sum counts them twice.
To put trace_id, meta.id and job on your log lines, see
Log correlation. The span shape, attribute tables, system
values, the migration from the earlier publish <urn> shape and the full metric list are in
Observability.
Per-URN schema validation
schema.Check(provider, urn, data) (producer guard) / schema.Wrap(provider, handler)
(consumer safety net) validate a message’s data against the JSON Schema registered for its
URN, bridged from a babelqueue-registry manifest via schema.NewDirProvider. See
Per-URN schema validation.