Path: redb-route/redb.Route.Kafka/README.md Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Kafka/README.md ---- # redb.Route.Kafka > Documentation and articles: Apache Kafka transport for redb.Route. Consumer (subscribe), producer (publish), consumer groups, deferred-commit routing (idempotent producer), Kafka transactions with exactly-once consume-process-produce (`transactionalIdPrefix`), and full Confluent.Kafka configuration. [![NuGet](https://img.shields.io/nuget/v/redb.Route.Kafka?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.Kafka) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../LICENSE) ## Installation ```bash dotnet add package redb.Route.Kafka ``` ## Usage ### URI Format ``` kafka://topic-name?brokers=host:port&groupId=my-group&autoOffsetReset=earliest ``` ### Fluent DSL ```csharp using redb.Route.Kafka; // Consumer From(Kafka.Topic("orders") .Brokers("broker1:9092,broker2:9092") .GroupId("order-service") .AutoOffsetReset("Earliest") .Batching() .MaxBatchMessages(500)) .Log("Received: ${body}") .To("direct://process"); // Producer From("direct://outbound") .To(Kafka.Topic("events") .Brokers("broker1:9092") .Acks("All") .Key("order-key") .Compression("Lz4")); // Inside a transacted block the send joins the transaction: it goes out once the database has // committed. The builder's .Transacted() also makes the producer idempotent and requires the block. From("direct://critical") .Transacted() .To(Kafka.Topic("audit") .Brokers("localhost:9092") .Transacted()) .To(Kafka.Topic("alerts") .Brokers("localhost:9092") .Transacted(false)) // goes out at once, even if the block rolls back .End(); ``` ### Transactions: `.Transacted()` and Kafka transactions Inside a route's `.Transacted()` block a Kafka send **joins the transaction**: the message is published after the database commits and discarded when the block rolls back. The `transacted` parameter states the exceptions: `false` sends at once, outside the transaction; `true` also makes the producer idempotent and fails the step outside a block. On its own this is **at-least-once**: the deferred sends go out one after the other, and the consumer commits its offset after the route. **Kafka transactions** are a separate switch, `transactionalIdPrefix`: ```csharp From(Kafka.Topic("orders").Brokers("b1:9092,b2:9092").GroupId("billing")) .Transacted() .IdempotentConsumer(Header("orderId"), "billing-inbound") // the database work .Process(/* ... */) .EndIdempotentConsumer() .To(Kafka.Topic("invoices").Brokers("b1:9092,b2:9092") .TransactionalIdPrefix("billing")) .End(); ``` - The sends such a producer defers in a block commit as **one Kafka transaction** when the block commits (after the database): all of them or none. `read_committed` readers, librdkafka's default, never see an aborted one. - When the route started from a Kafka consumer of the **same cluster** (the same brokers), the consumed offset commits **in that transaction** (`SendOffsetsToTransaction`) and the consumer does not commit it itself: the output and the offset move together — exactly-once within Kafka. With `ackMode=auto` the offset is committed on receipt, before the route runs (at-most-once), so it does not ride in the transaction. - "The same cluster" is decided by the cluster id the brokers report, however the brokers are listed on the two endpoints. From another cluster, the consumer commits the offset itself and the route is at-least-once; the producer logs a warning naming both cluster ids. - A consumer that loses its partition while its route runs (a rebalance, or `maxPollIntervalMs` exceeded) cannot commit through the transaction: the broker refuses its old group generation, the transaction aborts, and the consumer that took the partition over reads the record again. - A commit that does not answer has an unknown outcome: the producer does not abort it, it is rebuilt before the next transaction, and the exchange fails. If that commit did go through, the record is written again only when the consumer reads it again (`breakOnFirstError`). - Keep the block synchronous. An asynchronous step inside it (`.Threads()`, `seda:`) returns the route to the consumer before the transaction commits: the offset no longer rides in the transaction, the consumer commits it when the route returns, ahead of the work, and the producer logs a warning. - A send outside a block (`transacted=false`, or no block) is a transaction of its own, a little slower than a plain send. - The prefix names the producer; the connector appends the machine name, the process id and the producer's number, so nodes deploying the same configuration never fence each other. - Two transactional producers in one block commit two transactions, one after the other: atomic per producer, as for IBM MQ and RabbitMQ. The database and Kafka still do not commit as one: the database commits first, and a failure between the two is covered by the redelivery and the idempotent consumer. A raw `transactional.id` in `additionalProperties` is refused: it would put the client into transactional mode with nobody opening transactions. So is `enable.auto.commit=true` (a timer would commit records read but not yet processed, whatever `ackMode` says), and, for a `transacted=true` or `transactionalIdPrefix` producer, an `enable.idempotence` or `acks` that contradicts it. The rule holds for the endpoint's `additionalProperties` and for those of a named connection factory alike. The decisions and their reasons are in docs/KAFKA_EOS_2026_09_19.md. A parameter the endpoint cannot read — a misspelt option, or a value of the wrong type — is refused by name when the endpoint is created: a misspelt `transactionalIdPrefix` would otherwise leave the producer without transactions. ### Delivery defaults A producer defaults to `acks=all` and an **idempotent producer**, as the Kafka 3 client and Camel 4 do: a send is confirmed once every in-sync replica has it, and a retried send is not written twice. `enableIdempotence` left unset follows the effective `acks` (on with `all`, off otherwise); `enableIdempotence=true` with another `acks`, or `transacted=true` or `transactionalIdPrefix` with an explicit `acks` other than `all`, is refused when the endpoint is created. A route that wants the lower latency of `acks=leader` sets it explicitly and gets a non-idempotent producer. ### Failed messages An exception that escapes the route on a consumed message is counted in endpoint statistics and, by default, the consumer **moves on** — the failed record's offset is covered by the next successful commit (Camel's default too). `.BreakOnFirstError()` flips that: the consumer seeks back to the failed record and retries it instead of advancing, so a permanently poisoned record blocks its partition — pair it with a route error handler that dead-letters. ### Batch mode `batching=true` (`.Batching()`) makes the consumer hand the route one exchange per batch, as camel-kafka's `batching` does, by the batch contract every broker of redb.Route follows: - `maxBatchMessages` (default 500) caps the batch; `pollTimeoutMs` (default 1000) sends it on once no record came for that long, restarted by every record; `batchingIntervalMs` sends it on once that long has passed since its first record, however records keep coming. `maxBatchMessages` or `batchingIntervalMs` without `batching=true` fails the start, as does a value out of range. - The body is a `List`, one message per record with its own body and headers (`CamelKafkaTopic`, `.Partition`, `.Offset`, `.Timestamp`, `.Key`, the record's headers), even for a batch of one. The size is `body.Count` (`${body.size}`). `CamelKafkaTopic` and `CamelKafkaPartition` are set on the batch message when every record agrees. The exchange is InOnly. - `Split` over the body gives each part its record's body and headers, with `CamelSplitIndex` and the other split metadata as exchange properties. - The batch is committed once, after the route: the last offset of each partition it touched. A transactional route takes the batch's offsets into its Kafka transaction; a part of a `Split` never does. With `ackMode=auto` the offsets are committed on receipt, before the route. - A failed batch follows `breakOnFirstError`, the rule of a failed record: by default the consumer moves on; with `breakOnFirstError=true` every partition of the batch is sought back to its first offset and the whole batch comes again. - A batch half collected when the consumer stops is not run; its offsets are not committed, so the group delivers its records again. ### The partition of a record As in Apache Camel's camel-kafka, the partition of a sent record is chosen by one rule: | Set | The record goes to | |---|---| | the endpoint's `partitionKey` (`.PartitionKey(n)`) | that partition, for every record; it takes precedence over the header | | else the `CamelKafkaPartitionKey` header on the message (`KafkaHeaders.PartitionKey`), an integer or a whole-number text | that partition, per message | | neither | the partition Kafka's partitioner picks from the key (`key`, else `CamelKafkaKey`) | - The key is sent with the record in every case: an explicit partition does not drop it, as in Camel. - `partitionKey` is Camel's name for the producer. `partitionNumber` is the consumer's (it reads that one partition): a producer refuses `partitionNumber`, a consumer refuses `partitionKey`, each naming the other. - A list of `IMessage` takes each element's own header (the parent's headers are not copied); a plain list, the exchange's. Inside a `.Transacted()` block or a Kafka transaction the partition goes with the record. - A header that is not a partition number (negative, a fraction, other text) fails the step before anything is sent; a partition the topic does not have fails it with `Kafka topic '...' has no partition n`. Nothing goes to partition 0, or to the partitioner, in their place. - `CamelKafkaPartitionKey` is read by the producer only and, like every `CamelKafka*` header, never goes on the wire. ```csharp .SetHeader(KafkaHeaders.PartitionKey, Expr("${header.region}")) .To(Kafka.Topic("orders").Brokers("b1:9092")) ``` ### The topic and timestamp of a record Two headers change one sent record, as camel-kafka's `KafkaConstants.OVERRIDE_TOPIC` and `OVERRIDE_TIMESTAMP` do: | Header | Type | Effect | |---|---|---| | `CamelKafkaOverrideTopic` (`KafkaHeaders.OverrideTopic`) | `string` | the record goes to this topic instead of the endpoint's | | `CamelKafkaOverrideTimestamp` (`KafkaHeaders.OverrideTimestamp`) | `long` milliseconds since the Unix epoch, a whole-number text, `DateTimeOffset` or `DateTime` | the record's timestamp (a local or unspecified `DateTime` is read as local time) | - The producer removes both from the message before the send, as Camel does, so a later step does not send to the same topic by accident. The partition and the key are chosen as for any record. - The override is per message: the endpoint's topic stays the producer's own (its name, its logs and its trace span). Inside a `.Transacted()` block or a Kafka transaction the record goes with its topic and timestamp; one transaction may write to several topics. - A value that is not a topic name (not a text, or an empty one) or not a timestamp (negative, a fraction, other text) fails the step before anything is sent. A topic the brokers do not have is created or refused by them as for any topic (`auto.create.topics.enable`). - The broker keeps a record by its timestamp: one older than the topic's `retention.ms` is deleted at the next retention check, soon after it is written. - In a list body the exchange's `CamelKafkaOverrideTopic` is read once and is the topic of every element; an `IMessage` element's own override topic and timestamp win and are removed from that element. The exchange's `CamelKafkaOverrideTimestamp` is not read for a list, as in Camel. ```csharp .SetHeader(KafkaHeaders.OverrideTopic, Expr("orders-${header.region}")) .To(Kafka.Topic("orders").Brokers("b1:9092")) ``` ### A list body A body that is a list is sent element by element, each element its own record, as camel-kafka sends an `Iterable`: - a list of `IMessage` (a batch consumer's body, for one): each element with its own value, headers and key (`CamelKafkaKey`) and partition (`CamelKafkaPartitionKey`), none of the exchange's headers; the same key goes to the same partition unless the element names one; - any other list without a text form of its own: each value is a record under the exchange's headers and key. Unlike camel-kafka, which gives such an element no partition and only the `key` option, each value takes the endpoint's `partitionKey` (else the exchange's `CamelKafkaPartitionKey`) and the `key` option (else the exchange's `CamelKafkaKey`), because an endpoint that names a partition means it for every record it sends. Inside a `.Transacted()` block the records join its Kafka transaction; outside one they are sent one after the other, and a failure stops the list with the records before it sent. With `recordMetadata=true` `CamelKafkaRecordMeta` holds one entry per element. ## Fluent Builder API | Category | Methods | |----------|---------| | **Connection** | `.Brokers()`, `.SecurityProtocol()`, `.Sasl(mechanism, user, pass)`, `.SslCa()`, `.SslCert()`, `.SslVerifyHostname()`, `.ConnectionFactory()` | | **Consumer** | `.GroupId()`, `.AutoOffsetReset()`, `.Batching()`, `.MaxBatchMessages()`, `.BatchingIntervalMs()`, `.PollTimeout()`, `.SeekTo()`, `.TopicIsPattern()`, `.BreakOnFirstError()`, `.SessionTimeout()`, `.HeartbeatInterval()`, `.MaxPollInterval()`, `.PartitionAssignmentStrategy()`, `.IsolationLevel()`, `.PartitionNumber()` | | **Producer** | `.Acks()`, `.EnableIdempotence()`, `.Key()`, `.PartitionKey()`, `.Transacted()`, `.TransactionalIdPrefix()`, `.Linger()`, `.BatchSize()`, `.Compression()`, `.MessageTimeout()`, `.Retries()`, `.RecordMetadata()` | > Most builder methods accept both constant values and `IExpression` for runtime resolution via the expression engine. ## Encryption and authentication The connection is plaintext unless `securityProtocol` says otherwise: `Ssl` (TLS), `SaslSsl` (TLS plus SASL), `SaslPlaintext` (SASL without TLS). The same options work on the URI and on a named connection factory, the URI winning by name; the consumer's metadata client uses them too. | Option | Meaning | |---|---| | `sslCaLocation` | PEM file of the CA that signed the brokers' certificates; unset, the system store | | `sslCertificateLocation`, `sslKeyLocation`, `sslKeyPassword` | client certificate and key, for brokers that require one (mutual TLS) | | `sslEndpointIdentificationAlgorithm` | `https` verifies the broker's hostname against its certificate, `none` does not; unset, librdkafka verifies it | | `saslMechanism` | `Plain`, `ScramSha256`, `ScramSha512` (need `saslUsername`/`saslPassword`), `Gssapi` (Kerberos), `OAuthBearer` | ```csharp .To(Kafka.Topic("orders").Brokers("b1:9093,b2:9093") .SecurityProtocol("SaslSsl") .Sasl("ScramSha512", userExpression, passwordExpression) .SslCa("/etc/kafka/ca.pem")) ``` - The hostname is checked against the name the client connects by: the bootstrap brokers first, then the names the brokers advertise. A certificate must carry both. - `Plain` over `SaslPlaintext` sends the password unencrypted; the connector logs a warning. SCRAM does not send the password, but the traffic is still unencrypted. - `OAuthBearer` has no token callback in the connector: use librdkafka's own OIDC client through `additionalProperties` (`sasl.oauthbearer.method=oidc`, `sasl.oauthbearer.client.id`, ...). - Certificates held in memory (`ssl.ca.pem`, `ssl.certificate.pem`, `ssl.key.pem`) or a PKCS#12 keystore (`ssl.keystore.location`) go through `additionalProperties` too, set from code: they cannot come from a URI, and the connector does not log them. - `saslPassword` and `sslKeyPassword` are secrets: redacted wherever the endpoint URI is shown. ## Headers The headers of a consumed record become message headers, and message headers become the headers of a sent record. `content-type` also sets and is set from `Message.ContentType`. The component's own headers have Apache Camel's names and types (`KafkaConstants` of camel-kafka; the constants of `KafkaHeaders`), so a route written for Camel reads and sets them unchanged: | Header | Set by | Type | Meaning | |---|---|---|---| | `CamelKafkaTopic` | consumer | `string` | topic of the consumed record | | `CamelKafkaPartition` | consumer | `int` | partition it was stored in | | `CamelKafkaOffset` | consumer | `long` | its offset | | `CamelKafkaTimestamp` | consumer | `long` | its timestamp, milliseconds since the Unix epoch (absent when the record has none) | | `CamelKafkaHeaders` | consumer | `Confluent.Kafka.Headers` | the record's headers with their raw bytes | | `CamelKafkaKey` | consumer; read by the producer | `string` | the record's key; a sent record's key when the `key` option is not set | | `CamelKafkaPartitionKey` | read by the producer | `int` or whole-number text | a sent record's partition (see above) | | `CamelKafkaOverrideTopic` | read and removed by the producer | `string` | a sent record's topic instead of the endpoint's (see above) | | `CamelKafkaOverrideTimestamp` | read and removed by the producer | `long`, whole-number text, `DateTimeOffset`, `DateTime` | a sent record's timestamp (see above) | | `CamelKafkaRecordMeta` | producer, with `recordMetadata=true` | `List` | one entry per sent record (`Topic`, `Partition`, `Offset`, `Timestamp`), a list body one per element | - They are set in single and batch mode alike, and none of them goes on the wire (the filter strategy below). - The key of a sent record is the `key` option, which takes precedence, else `CamelKafkaKey`: a route passing consumed records on keeps their keys (their partition and compaction), as camel-kafka does. To send without a key, remove that header. The key goes with the record whatever its partition. - Not set, and why: Camel's `CamelKafkaLastRecordBeforeCommit` and `CamelKafkaLastPollRecord` describe the records of one poll before a commit, which this consumer does not batch that way (it commits per record, or per batch in batch mode); `CamelKafkaManualCommit` belongs to Camel's `allowManualCommit`, which this component does not have. ### Header filter strategy `headerFilterStrategy=#name` names an `IHeaderFilterStrategy` in the registry that decides which headers the endpoint carries, as in Apache Camel: on a producer, which exchange headers go into the record; on a consumer, which record headers come into the exchange. It replaces the default, `KafkaHeaderFilterStrategy` (Camel's: headers whose name starts with `Camel`, `camel`, `org.apache.camel.` or `kafka.` neither go out nor come in; everything else does), entirely; derive from that class to add to it. `content-type` and the consumer's `CamelKafka*` metadata are set whatever the strategy says. ```csharp ctx.AddToRegistry("correlationOnly", new DefaultHeaderFilterStrategy { OutFilter = ["Correlation-ID"], FilterOnMatch = false, // a whitelist: only the listed headers go out }); // kafka:orders?brokers=localhost:9092&headerFilterStrategy=#correlationOnly ``` ## A lost connection The Kafka client reconnects to the brokers by itself; the consumer keeps reading where the group's committed offsets are once they answer again. When no broker is left (librdkafka's `_ALL_BROKERS_DOWN`; one broker of several going away is not a loss), the endpoint's health is `Warning`, then `Critical` once a check of the brokers failed, and `Healthy` when they are back; a Warning is logged when it is lost and an Information when it is back, and `Reconnects` counts each return. The client gives no event when the brokers are back, so while the connection is lost the consumer asks them for the topic's metadata on the `RedbRoute:Reconnect` schedule, over the client's own connections (each check is bounded to 5 s and ends with the route's stop); the next record restores it too, whichever comes first. A loss is not counted in `Errors`. A fatal client error (for example a static member, `group.instance.id`, fenced by another member with the same id) ends the client for good. The consumer then builds a new client on the same schedule and reads on; the route stays `Started` and the endpoint's health shows the loss until the new client reaches the brokers. Records read but not yet committed when the error came are delivered again (at least once). ## Tracing The connector traces on the shared `redb.Route` activity source, through the core's transport contract (`RouteTelemetryExtensions`); `RouteEngineOptions.EnableTelemetry = false` opens no Kafka span. - **Send**: a `Producer` span `{topic} publish`. Its W3C context (`traceparent`, `tracestate`) and the baggage go into the record's headers as UTF-8, replacing a value copied from a consumed record. A send that fails within the call (an immediate one, or a Kafka transaction of its own) marks the span an error; a send deferred to a `.Transacted()` block fails at the block's commit, on the route's span. - **Receive, one record**: a `Consumer` span `{topic} receive` whose parent is the context in the record's headers (header names compared without case). Without one it is a root, never a child of the poll thread's ambient activity. The sender's baggage comes back on it, and the route runs under it. - **Receive, a batch** (`batching=true`): the records come from different senders and traces, so none of them is the parent. The batch span is a root of its own with a link to the context of every record that carries one, and `messaging.batch.message_count`. In a tracing backend the batch opens its own trace, and each link leads to the send of one record. Both spans carry `messaging.system=kafka`, `messaging.destination.name`, `messaging.operation` and `redb.route.endpoint`; a receive span also carries `messaging.kafka.consumer.group`, and a single record's span its partition, offset and key. ## Part of [redb.Route](../README.md) — ESB & EIP Framework for .NET ## Named connection factory Keep credentials out of the route URI: register a factory in the context registry and reference it by name. A set-but-unknown name fails loud at startup — a typo can never silently fall back to inline URI parameters. ```csharp context.AddToRegistry("prod", new KafkaConnectionFactory { Brokers = "b1:9092,b2:9092", SaslUsername = "svc", SaslPassword = secrets.KafkaPassword, }); // kafka://orders?connectionFactory=prod ```