Reliability & governance helpers

Last updated:

Beyond produce/consume, BabelQueue.Core ships optional, zero-dependency helpers 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 .NET face of the cross-SDK spec — follow the linked spec page for the full contract.

Idempotency

Idempotency.Wrap(store, handler) (namespace BabelQueue) makes a handler run at most once per meta.id, even on at-least-once redelivery. The store contract is synchronous:

using BabelQueue;

IIdempotencyStore store = new InMemoryStore(); // tests / single process
Handler guarded = Idempotency.Wrap(store, handler);

The in-memory InMemoryStore is the reference; for a fleet, implement IIdempotencyStore (Seen / Remember / Forget) over a shared backend (no persistent store ships in core yet — bring your own). See Idempotency and the store deep-dive.

Transactional outbox

The BabelQueue.Outbox namespace 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. It is async throughout (CancellationToken-threaded):

using BabelQueue.Outbox;

IOutboxStore store = new InMemoryOutboxStore(); // production: an ADO.NET-backed IOutboxStore
var outbox = new Outbox(store);

// inside YOUR DB transaction, beside the business write — no commit of its own:
string id = await outbox.WriteAsync(envelope, ct); // encodes via EnvelopeCodec, calls SaveAsync

// later, a relay drains the durable rows to the broker:
OutboxRelayResult res = await new OutboxRelay(publisher, store).DrainAsync(0, ct);
// res.Published / res.Failed

IOutboxStore is the four-method async contract (SaveAsync / FetchUnpublishedAsync / MarkPublishedAsync / MarkFailedAsync); the relay forwards through the OutboxPublisher delegate ((body, queue, ct)). The transaction boundary is yours. (Under using BabelQueue.Outbox; the writer type Outbox is disambiguated from the same-named namespace with a using alias — the standard C# pattern.) See Transactional Outbox.

DLQ redrive & replay-bypass

Redrive.RedriveAsync(transport, dlq, options) (namespace BabelQueue) moves dead-lettered messages back onto a queue — dead_letter removed, attempts reset to 0, everything else preserved — with ToQueue (sandbox), Max, DryRun, Select and Bypass. The Replay guard takes the delivered headers explicitly and skips effects that already fired:

using BabelQueue;

public async Task Handle(IDictionary<string, object?> data, IReadOnlyDictionary<string, string> headers)
{
    SaveOrder(data);                                                  // idempotent core
    await Replay.BypassExternalEffectsAsync(headers, () => SendEmailAsync(data)); // skipped on replay
}

Redrive with Bypass = true stamps the bq-replay-bypass marker through an IHeaderPublisher transport. See DLQ redrive & replay-bypass.

GDPR field encryption

Gdpr.Protect() / Gdpr.Unprotect() (namespace BabelQueue.Gdpr) encrypt only the data leaves a schema marks x-gdpr-sensitive, in place. ICipher is caller-bound; AesGcmCipher (on the in-box System.Security.Cryptography.AesGcm) is the reference. Validate cleartext — protect after validation on produce, unprotect before validation on consume.

using BabelQueue.Gdpr;

ICipher cipher = new AesGcmCipher(key); // or implement ICipher over a KMS

Gdpr.Protect(data, schema, cipher);     // producer: encrypt marked leaves
try
{
    Gdpr.Unprotect(data, schema, cipher); // consumer: inverse
}
catch (ProtectedFieldException)
{
    // wrong key / tampered → retry / dead-letter
}

BabelQueue.Schema.SchemaSensitivity.SensitivePaths(schema) exposes the marked leaves directly. See GDPR field encryption.

OpenTelemetry (spans, metrics and traceparent)

BabelQueue.Tracing.Telemetry emits a send <queue> activity on publish and a process <queue> activity per handled message, and BabelQueue.Tracing.TelemetryMetrics records the standard metrics. On a header-carrying transport the W3C traceparent is injected and extracted, so a consumer span is a true child of the producer span (degrading to trace_id correlation otherwise). Telemetry.Wrap(handler, headers) and the header-aware Telemetry.PublishAsync(…, headers, …) overloads are the entry points; Traceparent.Inject / Traceparent.RemoteParentFromHeaders do the W3C work. It is built only on the in-box System.Diagnostics types, so the core stays zero-dependency. The SQS, Redis, Kafka, Pulsar, Artemis, Azure Service Bus and MassTransit transports carry the header; on the consume side, KafkaTraceHeaders.Extract, PulsarTraceHeaders.Extract, ArtemisTraceHeaders.Extract and AsbTraceHeaders.Extract turn a received message into the headers dictionary.

Dashboard-breaking change. Spans are now send <queue> / process <queue> (they were publish <urn> / process <urn>), and the URN is the babelqueue.urn attribute. Pass system so messaging.system is the broker. Not passing it is deprecated. The migration table is in Observability.

The options are optional parameters:

Parameter Applies to Meaning
system: Telemetry.Systems.Kafka Telemetry.Wrap, Telemetry.PublishAsync, MetricsDeadLetterObserver the messaging.system value (the broker); Telemetry.Systems has a constant per broker
consumerGroup: "billing" Telemetry.Wrap messaging.consumer.group.name, consumer activity only

There is no meter option: the instruments live in a static Meter("BabelQueue") next to the ActivitySource("BabelQueue"), and a listener collects them only when you subscribe. With the OpenTelemetry .NET SDK, add TelemetryMetrics.MeterName to the meter provider and Telemetry.ActivitySourceName to the tracer provider. Telemetry.SemconvVersion (1.44.0) and Telemetry.SchemaUrl are public constants.

using BabelQueue.Tracing;

// consumer: "process <queue>" activity + consumed / retries / duration metrics.
// The transport extractor turns the received record into the headers dictionary, so the
// activity is a child of the producer span (ADR-0028). Shown for Kafka.
BabelHandler onMessage = (envelope, result, ct) =>
    Telemetry.Wrap(handler, KafkaTraceHeaders.Extract(result.Message.Headers),
        system: Telemetry.Systems.Kafka, consumerGroup: "billing")(envelope);

// producer: "send <queue>" activity + sent metric. The carrier receives the traceparent and
// the transport publisher writes it beside the envelope.
var headers = new Dictionary<string, string>();
await Telemetry.PublishAsync("urn:babel:orders:created", data, headers,
    envelope => publisher.PublishEnvelopeAsync(envelope, headers),
    queue: "orders", system: Telemetry.Systems.Kafka);

PublishEnvelopeAsync(envelope, headers, …) sends the envelope PublishAsync built, exactly as given, so the producer activity’s messaging.message.id is the meta.id that reaches the wire: the ids match. (PublishWithHeadersAsync(urn, data, …) still builds its own envelope; do not use it as the send callback.) PublishEnvelopeAsync does not stamp meta.queue, so pass queue equal to the publisher’s destination — without it meta.queue is "default", the activity is named send default, and a dead-letter record or a redrive points at the wrong queue. Kafka, Pulsar, Artemis, Azure Service Bus, SQS and Redis publishers all have it.

handler is a BabelQueue.Handler (Task Handler(Envelope)). Telemetry.Wrap(handler, headers: null, …) and the PublishAsync overload without a headers argument carry no traceparent: the consumer activity then falls back to the trace_id-derived parent. The matching extractors are KafkaTraceHeaders.Extract, PulsarTraceHeaders.Extract, ArtemisTraceHeaders.Extract and AsbTraceHeaders.Extract; the matching publisher methods are PublishEnvelopeAsync.

Where the observer is wired. The .NET core has no consume runtime, so each transport consumer takes the observer as an option, DeadLetterObserver (an IDeadLetterObserver), on its options class: SqsConsumerOptions, RedisConsumerOptions, KafkaConsumerOptions, PulsarConsumerOptions, ArtemisConsumerOptions and AsbConsumerOptions (BabelQueue.MassTransit writes none). MetricsDeadLetterObserver is the implementation that increments babelqueue.dlq.messages:

var options = new KafkaConsumerOptions
{
    DeadLetterObserver = new MetricsDeadLetterObserver(Telemetry.Systems.Kafka),
};

It is called once, after the DLQ write (or the Azure Service Bus native DeadLetterMessageAsync) is confirmed, through DeadLetterObservers.NotifySafely: an exception from the observer is logged and never changes how the message is settled.

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

The core validator (producer guard + consumer wrap, via MapProvider) validates a message’s data against the JSON Schema registered for its URN. See Per-URN schema validation.