Reliability & governance helpers

Last updated:

Beyond produce/consume, the Java 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 Java face of the cross-SDK spec — follow the linked spec page for the full contract.

Idempotency

com.babelqueue.idempotency.Idempotent.wrap(store, handler) makes a handler run at most once per meta.id, even on at-least-once redelivery.

import com.babelqueue.idempotency.Idempotent;
import com.babelqueue.idempotency.InMemoryStore;

Store store = new InMemoryStore(); // tests / single process
Handler guarded = Idempotent.wrap(store, handler);

The in-memory InMemoryStore is the reference; for a fleet, implement the Store interface (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 com.babelqueue.outbox package 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 com.babelqueue.outbox.Outbox;
import com.babelqueue.outbox.OutboxRelay;
import com.babelqueue.outbox.InMemoryOutboxStore;

OutboxStore store = new InMemoryOutboxStore(); // production: a JDBC-backed OutboxStore
Outbox outbox = new Outbox(store);

// inside YOUR DB transaction, beside the business write — no commit of its own:
String id = outbox.write(envelope);            // encodes via EnvelopeCodec, calls store.save()

// later, a relay drains the durable rows to the broker:
OutboxRelayResult res = new OutboxRelay(transport, store).drain(0); // res.published() / res.failed()

OutboxStore is the four-method interface (save / fetchUnpublished / markPublished / markFailed); the relay forwards through OutboxTransport.publish(queue, body). The transaction boundary is yours. See Transactional Outbox.

DLQ redrive & replay-bypass

com.babelqueue.Redrive.redrive(transport, dlq, options) 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 skips effects that already fired on a deliberate replay; the replay flag rides a ThreadLocal scope (Replay.process(headers, …)), so Replay.isReplay() takes no argument:

import com.babelqueue.Replay;

Replay.process(headers, () -> {
    saveOrder(data);                                    // idempotent core — always runs
    Replay.bypassExternalEffects(() -> sendEmail(data)); // external effect — skipped on replay
});

Redrive with bypass(true) stamps the bq-replay-bypass marker through a HeaderPublisher transport. See DLQ redrive & replay-bypass.

GDPR field encryption

com.babelqueue.gdpr.Gdpr.protect() / .unprotect() encrypt only the data leaves a schema marks x-gdpr-sensitive, in place. Cipher is caller-bound; AesGcmCipher (on the JDK’s javax.crypto) is the reference. Validate cleartext — protect after validation on produce, unprotect before validation on consume.

import com.babelqueue.gdpr.Gdpr;
import com.babelqueue.gdpr.AesGcmCipher;

Cipher cipher = new AesGcmCipher(key); // or implement com.babelqueue.gdpr.Cipher over a KMS

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

com.babelqueue.schema.SensitivePaths.of(schema) exposes the marked leaves directly. See GDPR field encryption.

OpenTelemetry (spans, metrics and traceparent)

com.babelqueue.otel.Tracing emits a send <queue> span on publish and a process <queue> span per handled message, and com.babelqueue.otel.Metrics 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). Tracing.publish(…, HeaderSender) injects on produce and the Tracing.wrapHandler(tracer, handler, Supplier<Map<String,String>>) overload extracts on consume. The Spring AMQP, SQS, Redis, Kafka, Pulsar, Artemis and Azure Service Bus transports carry the header. opentelemetry-api is the core’s already-optional dependency, so no new dependency is added.

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 live on an immutable Tracing.Options:

Builder method Meaning
.system("kafka") the messaging.system value (the broker)
.consumerGroup("billing") messaging.consumer.group.name, consumer span only
.meter(meter) an OpenTelemetry Meter; without it nothing is recorded as a metric

Tracing.SEMCONV_VERSION (1.44.0) and Tracing.SCHEMA_URL are public constants; build the tracer and the meter with the schema URL.

Tracing.Options options = Tracing.Options.create()
    .system("aws_sqs").consumerGroup("billing").meter(meter);

// the observer for babelqueue.dlq.messages (core type com.babelqueue.DeadLetterObserver)
DeadLetterObserver dlqObserver = options.metrics().deadLetterObserver(options.resolvedSystem());

// consumer: "process <queue>" span + consumed / retries / duration metrics. The delivered
// message's headers go to the wrapper, so the span is a child of the producer span (ADR-0028).
SqsConsumer consumer = SqsConsumer.builder(sqsClient, queueUrl)
    .handler("urn:babel:orders:created", (envelope, message) ->
        Tracing.wrapHandler(tracer, handler, () -> SqsHeaders.of(message), options).handle(envelope))
    .deadLetterObserver(dlqObserver)
    .build();

// producer: "send <queue>" span + sent metric; the transport writes the traceparent header
String id = Tracing.publish(tracer, "urn:babel:orders:created", data, "orders",
    sqsPublisher::publishWithHeaders, options);

Here handler is a com.babelqueue.idempotency.Handler. Passing null instead of the headers supplier, or a Sender instead of a HeaderSender, drops the traceparent: the consumer span then falls back to the trace_id-derived parent. Each transport has the matching extractor: SqsHeaders.of(message), BabelHandler.headersOf(record) (Kafka, Pulsar, Artemis, Azure Service Bus) and the publishWithHeaders method on its publisher. options.metrics() is null when no meter was given.

Where the observer is wired. The Java core has no consume runtime, so each transport consumer takes the observer on its builder, as deadLetterObserver(DeadLetterObserver): SqsConsumer, RedisConsumer, KafkaConsumer, PulsarConsumer, ArtemisConsumer and AsbConsumer (babelqueue-spring writes none), as in the example above.

It is called once, after the DLQ write (or the Azure Service Bus native deadLetter call) is confirmed, through DeadLetterObserver.notifySafely: a RuntimeException 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 com.babelqueue.schema 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.