Table of Contents

Kafka Transport

The Kafka transport (BareWire.Transport.Kafka) lets BareWire publish and consume over Apache Kafka. It keeps BareWire's core principles — manual topology, raw-first payloads, bounded flow control — and maps them onto Kafka concepts: an idempotent producer, consumer groups with partition assignment, and an opt-in retry-topic + DLQ-topic pattern (Kafka has no native dead letter queue).

It is built on top of Confluent.Kafka. The transport defaults to SecurityProtocol=Plaintext (SASL/SSL is not yet wired up), so do not point it at a production broker until the secure-config layer is in place.

Registration

As with every BareWire transport, you register the core engine and the Kafka transport together. There are two ways to do it (see Configuration for the full rationale).

The BareWire.Kafka bundle depends on both the core and the transport and exposes one method, AddBareWireWithKafka:

using BareWire.Kafka;
using BareWire.Transport.Kafka;
using Confluent.Kafka;
using Microsoft.Extensions.DependencyInjection;

builder.Services.AddBareWireWithKafka(
    transport =>
    {
        transport.BootstrapServers("localhost:9092");
        transport.ConsumerGroup("order-processing");
        transport.ConsumerAutoOffsetReset(AutoOffsetReset.Earliest);
        transport.ConsumerPartitionAssignmentStrategy(KafkaPartitionAssignmentStrategy.CooperativeSticky);
    },
    bus =>
    {
        // middleware, serializers...
    });

The bus delegate is optional — omit it when transport defaults are enough:

builder.Services.AddBareWireWithKafka(transport => transport.BootstrapServers("localhost:9092"));

2. Two calls — core and transport registered separately

AddBareWireWithKafka is sugar over the explicit pair. Use the two-call form when you reference the core and transport packages separately:

builder.Services.AddBareWireKafka(kafka => kafka.BootstrapServers("localhost:9092"));
builder.Services.AddBareWire(bus => { /* middleware, serializer mappings... */ });

AddBareWireKafka registers the Kafka ITransportAdapter and AddBareWire the core engine. At minimum, BootstrapServers must be called.

Producer

The produce path runs with an idempotent producer by default, giving exactly-once delivery semantics within a single producer session. Ordering is preserved by mapping each message key to a partition, so messages that share a key keep their relative order. No producer-side tuning is required beyond BootstrapServers.

Receive endpoints

A receive endpoint binds one or more consumers to a Kafka topic. The endpoint name is the topic name:

builder.Services.AddBareWireWithKafka(
    transport =>
    {
        transport.BootstrapServers("localhost:9092");
        transport.ConsumerGroup("order-processing");

        transport.ReceiveEndpoint("orders", e =>
        {
            e.PrefetchCount = 32;           // in-flight credit limit enforced by the BareWire core
            e.ConcurrentMessageLimit = 8;   // concurrent handler invocations
            e.RetryCount = 3;
            e.RetryInterval = TimeSpan.FromSeconds(1);

            e.Consumer<OrderCreatedConsumer, OrderCreated>();
        });
    });

builder.Services.AddTransient<OrderCreatedConsumer>();

Consumers are resolved from the container, so register each consumer type (for example services.AddTransient<OrderCreatedConsumer>()). ConsumerGroup is required as soon as an endpoint is declared; the configuration fails fast otherwise. The topic must already exist — topology is manual, so provision it out of band (with your usual Kafka tooling) before the bus starts. An endpoint can also host a raw consumer (e.RawConsumer<T>()), a saga state machine (e.StateMachineSaga<T>()), several typed consumers, and per-key ordering; see Publishing and Consuming.

Things to know:

  • PrefetchCount is not a broker setting. It is the credit limit the BareWire core uses to bound unsettled messages for the endpoint (on Kafka it also caps the tracked, unsettled messages per consumer).

  • All endpoints share the transport-wide consumer group. Each endpoint runs its own Kafka consumer client, so every endpoint start or stop triggers a group rebalance. Prefer few endpoints, and CooperativeSticky assignment to keep rebalances incremental.

  • Poison messages: without ConfigureRetryDlq, a rejected message is committed (with a logged warning) and a Nack/Requeue pins the partition's commit position, so the message is redelivered after a restart. Enable the retry-topic and DLQ-topic pattern to get a bounded number of attempts and a dead-letter topic.

  • With ConfigureRetryDlq enabled, retries are only processed if you also declare a separate endpoint on the retry topic, because each endpoint subscribes to exactly one topic:

    transport.ReceiveEndpoint("orders", e => e.Consumer<OrderCreatedConsumer, OrderCreated>());
    transport.ReceiveEndpoint("orders.retry", e => e.Consumer<OrderCreatedConsumer, OrderCreated>());
    
  • Access control: an endpoint on a .retry or .DLQ topic keeps the retry-tracking headers of the messages it reads (the trust decision is based on the topic name suffix). Restrict write access to those topics with broker ACLs so that only trusted producers (the BareWire transport itself) can publish to them.

  • IBus.ConnectReceiveEndpoint (adding an endpoint at runtime) is not supported yet; declare every endpoint in the transport delegate.

  • Only one transport can be registered per service collection: registering a second, different transport throws BareWireConfigurationException, and support for hosting several transports in one service collection is planned.

  • Calling AddBareWireKafka a second time on one service collection also throws BareWireConfigurationException; declare every receive endpoint in a single call.

Consumer groups

Consuming uses Kafka consumer groups. Every receive endpoint consumes its topic as a member of the transport-wide ConsumerGroup, so all endpoints (and all application instances) that share the group id coordinate partition assignment and offset commits through the Kafka group coordinator. A group id is required to consume. Each endpoint uses its own Kafka consumer client, so starting or stopping an endpoint causes a group rebalance.

builder.Services.AddBareWireKafka(kafka =>
{
    kafka.BootstrapServers("localhost:9092");
    kafka.ConsumerGroup("order-processing");
    kafka.ConsumerAutoOffsetReset(AutoOffsetReset.Earliest);
    kafka.ConsumerPartitionAssignmentStrategy(KafkaPartitionAssignmentStrategy.CooperativeSticky);
});
  • ConsumerAutoOffsetReset controls where a group starts when it has no committed offset (or the committed offset is out of range). Defaults to AutoOffsetReset.Earliest.
  • ConsumerPartitionAssignmentStrategy selects the rebalancing strategy. Defaults to KafkaPartitionAssignmentStrategy.CooperativeSticky, which rebalances incrementally and minimises stop-the-world pauses. The other values are Range and RoundRobin.

Offsets are committed only after a message is settled successfully, giving at-least-once delivery.

The committed position of a partition advances only over a contiguous prefix of settled messages, so acknowledging a later message never commits past one that was returned:

  • Requeue, and Nack when the retry/DLQ pattern is disabled, hold the partition's commit position at that message's offset until the consumer restarts. The message is then delivered again together with the later messages of that partition (a CooperativeSticky rebalance normally does not take away a partition that stays assigned). There is no immediate redelivery within the same session, and delivery is at-least-once, so consumers must be idempotent. Enable the retry/DLQ pattern for topics fed by untrusted producers: a single poison message otherwise pins the commit position in every session.
  • Reject without the retry/DLQ pattern commits the offset and logs a warning.
  • With the retry/DLQ pattern enabled, a Nack is republished to the retry-topic as one more attempt and reaches the DLQ-topic after MaxRetries attempts.
  • When too many messages of one partition are unsettled, that partition is paused briefly and resumed once settlements catch up (back-pressure).

Retry-topic and DLQ-topic pattern

Kafka has no native dead letter queue, so BareWire emulates one. The pattern is opt-in: enable it inside ConfigureRetryDlq. When it is not enabled, deferring a message is not supported and a rejected message is committed with a logged warning.

builder.Services.AddBareWireKafka(kafka =>
{
    kafka.BootstrapServers("localhost:9092");
    kafka.ConsumerGroup("order-processing");
    kafka.ConfigureRetryDlq(retry =>
    {
        retry.Enable();
        retry.MaxRetries(5);
        retry.Backoff(TimeSpan.FromSeconds(1), multiplier: 2.0, TimeSpan.FromMinutes(1));
    });
});

A failed message is republished to a retry-topic (with exponential backoff) and, once retries are exhausted or the message is rejected, to a DLQ-topic. The retry-topic and DLQ-topic names are derived from the source topic by appending a suffix. A message dead-lettered while being consumed from the retry-topic lands on the retry-topic's own DLQ (<source>.retry.DLQ), because the suffix is appended idempotently.

Method Purpose Default
Enable() Activates the pattern (required to opt in) disabled
MaxRetries(int) Retry attempts before dead-lettering 3
RetryTopicSuffix(string) Suffix appended to form the retry-topic name .retry
DlqTopicSuffix(string) Suffix appended to form the DLQ-topic name .DLQ
Backoff(TimeSpan, double, TimeSpan) Base delay, multiplier, and max-delay cap for retry backoff 1s, 2.0, 5m

Topology

BareWire uses manual topology by default. In Kafka, the only actionable declaration is a topic — Kafka has no exchange/binding concept, so exchange and binding declarations are accepted (to satisfy the shared topology contract) but are silently ignored at deploy time.

Because the standard RabbitMQ-flavoured queue arguments (dead-letter, TTL, and so on) have no native Kafka equivalent, Kafka-specific topic parameters use the bw.kafka.* argument convention, supplied through the queue configurator's Argument escape hatch:

topology.DeclareQueue("orders", durable: true, autoDelete: false, configure: q =>
{
    q.Argument("bw.kafka.partitions", 6)
     .Argument("bw.kafka.replication-factor", 3)
     .Argument("bw.kafka.retention.ms", 604_800_000); // 7 days
});

A bw.kafka.config.<x> key is forwarded to the topic's broker-side Configs["<x>"].

Configuration reference

Method (IKafkaConfigurator) Purpose Default
BootstrapServers(string) Comma-separated host:port broker list required
ConsumerGroup(string) Consumer group id required to consume
ReceiveEndpoint(string, Action<IReceiveEndpointConfigurator>) Binds consumers to a topic (endpoint name = topic name) none
ConsumerAutoOffsetReset(AutoOffsetReset) Offset reset policy when no committed offset exists Earliest
ConsumerPartitionAssignmentStrategy(KafkaPartitionAssignmentStrategy) Partition assignment / rebalance strategy CooperativeSticky
ConfigureRetryDlq(Action<IKafkaRetryDlqConfigurator>) Retry-topic + DLQ-topic pattern disabled (opt-in)

See also