Path: redb-route/redb.Route.Kafka/KafkaEndpointOptions.cs
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/KafkaEndpointOptions.cs
----
using redb.Route.Abstractions;
using Confluent.Kafka;
using redb.Route.Batching;
using redb.Route.Core;
namespace redb.Route.Kafka;
///
/// Typed options for . Bound from URI query parameters via reflection.
///
public sealed class KafkaEndpointOptions : EndpointOptions
{
// ── General ──
/// Comma-separated list of Kafka broker addresses (required).
public string Brokers { get; set; } = string.Empty;
///
/// A registry reference (#name) to an that decides
/// which headers this endpoint carries between the exchange and a record, in place of
/// .
///
[RegistryReference(typeof(IHeaderFilterStrategy))]
public string? HeaderFilterStrategy { get; set; }
/// Security protocol for broker communication.
public string SecurityProtocol { get; set; } = "Plaintext";
/// SASL mechanism (Plain, ScramSha256, ScramSha512, etc.).
public string? SaslMechanism { get; set; }
/// SASL username.
public string? SaslUsername { get; set; }
/// SASL password.
[Sensitive]
public string? SaslPassword { get; set; }
// ── SSL/TLS ──
/// CA certificate file path for SSL.
public string? SslCaLocation { get; set; }
/// Client certificate file path (for mTLS).
public string? SslCertificateLocation { get; set; }
/// Client private key file path (for mTLS).
public string? SslKeyLocation { get; set; }
/// Client private key passphrase.
[Sensitive]
public string? SslKeyPassword { get; set; }
///
/// SSL endpoint identification: "https" verifies the broker hostname against its certificate,
/// "none" (or empty) disables the check; anything else is refused. Unset = librdkafka default
/// (verification on). Was factory-only before, so a URI-configured TLS endpoint could
/// not control hostname verification at all.
///
public string? SslEndpointIdentificationAlgorithm { get; set; }
/// Name of in the route registry.
[RegistryReference(typeof(KafkaConnectionFactory))]
public string? ConnectionFactory { get; set; }
// ── Consumer ──
/// Consumer group identifier (required for consumers).
public string? GroupId { get; set; }
/// Where to start consuming when no committed offset exists.
public string AutoOffsetReset { get; set; } = "Latest";
///
/// When the offset is committed (). Manual (default): inline right after a turn
/// that ended well — at-least-once, as the RabbitMQ consumer's post-process ack. When a Kafka-transactional
/// producer of the same cluster () in the route's .Transacted() block
/// committed the offset in its transaction, the inline commit is skipped: exactly-once within Kafka. Auto:
/// committed on receipt, before the route runs (at-most-once).
/// This is not librdkafka's enable.auto.commit (a background timer that can commit un-processed
/// offsets); the underlying client stays at manual commit always.
///
public AckMode AckMode { get; set; } = AckMode.Manual;
///
protected override string? UnknownParameterHint(string name)
=> name.Equals("enableAutoCommit", StringComparison.OrdinalIgnoreCase)
? "'enableAutoCommit' is replaced by 'ackMode': ackMode=manual (the default) commits after the route, as " +
"enableAutoCommit=true did; ackMode=auto commits on receipt. enableAutoCommit=false never committed at all."
: name.Equals("keyFromHeader", StringComparison.OrdinalIgnoreCase)
? "'keyFromHeader' is gone, as Apache Camel has no such option: the key option wins, else the CamelKafkaKey header is " +
"the key. To send without a key, remove that header (.RemoveHeader(KafkaHeaders.Key))."
: name.Equals("maxPollRecords", StringComparison.OrdinalIgnoreCase)
? "'maxPollRecords' is replaced by 'maxBatchMessages', the batch size of every broker; batch mode is switched " +
"on by batching=true: write batching=true&maxBatchMessages=N."
: null;
///
/// Batch mode (Apache Camel batching): the route gets one exchange whose body is a List<IMessage>
/// of up to records, settled once after the route. No other option switches it on.
///
public bool Batching { get; set; }
/// Largest number of records in a batch (default 500, Camel's maxPollRecords default). Batch mode only.
public int? MaxBatchMessages { get; set; }
///
/// How long one poll waits for a record, in milliseconds (default 1000). In batch mode the idle timeout, as in Camel:
/// a batch with records is sent on once no record came for this long, restarted by every record.
///
public int PollTimeoutMs { get; set; } = 1000;
///
/// Batch mode only: a batch is sent on once this many milliseconds have passed since its first record, however
/// records keep coming (Apache Camel batchingIntervalMs). Unset: no such limit.
///
public int? BatchingIntervalMs { get; set; }
/// The default of .
internal const int DefaultMaxBatchMessages = 500;
/// The batch options of the endpoint, or null in single-record mode. Set by .
internal BatchOptions? Batch { get; private set; }
/// Resolves the batch options; a batch option without batch mode, or a value out of range, fails here.
internal void ResolveBatch(string endpoint)
=> Batch = BatchOptions.Resolve(endpoint, Batching, MaxBatchMessages, PollTimeoutMs, BatchingIntervalMs,
DefaultMaxBatchMessages);
/// Stop batch processing on first error.
public bool BreakOnFirstError { get; set; }
/// Seek to "beginning" or "end" on first start.
public string? SeekTo { get; set; }
/// Interpret topic name as a regex pattern.
public bool TopicIsPattern { get; set; }
/// Static group instance ID. Avoids rebalance storms in K8s rolling deploys.
public string? GroupInstanceId { get; set; }
/// Session timeout in ms. Lower = faster dead-consumer detection.
public int? SessionTimeoutMs { get; set; }
/// Heartbeat interval in ms. Should be < SessionTimeoutMs/3.
public int? HeartbeatIntervalMs { get; set; }
/// Max time between polls in ms. Prevents rebalance during slow processing.
public int? MaxPollIntervalMs { get; set; }
/// Partition assignment strategy: Range, RoundRobin, CooperativeSticky.
public string? PartitionAssignmentStrategy { get; set; }
///
/// Isolation level: ReadUncommitted, ReadCommitted. Unset, librdkafka's default ReadCommitted: records of
/// aborted Kafka transactions ( producers) are not delivered, and records of
/// open ones wait for their commit.
///
public string? IsolationLevel { get; set; }
// ── Producer ──
///
/// Acknowledgment level: None, Leader, All. Default All, as in the Kafka 3 client and Camel 4: a send is confirmed
/// once every in-sync replica has it, which also allows the idempotent producer.
///
public string Acks { get; set; } = "All";
/// Number of retries for failed sends.
public int Retries { get; set; } = 3;
///
/// Idempotent producer (enable.idempotence): the broker does not write a retried send twice. Unset, it follows
/// the effective acks: on with all, off otherwise. true requires acks=all;
/// transacted=true turns it on.
///
public bool? EnableIdempotence { get; set; }
///
/// Producer: put the metadata of what was sent in the header, a list with one
/// per sent record (Apache Camel's recordMetadata, default false as there).
///
public bool RecordMetadata { get; set; }
///
/// Producer: the key of every sent record, a constant or a ${...} expression (Apache Camel's key). It takes
/// precedence over the header, as in Camel; unset, that header is the key.
///
public string? Key { get; set; }
/// The producer is made idempotent by the connector (transacted=true or transactionalIdPrefix).
internal bool IsIdempotentProducer => Transacted == true || TransactionalIdPrefix is not null;
///
/// Consumer: reads this one partition (Assign) instead of joining the group's assignment. A producer refuses it: its
/// partition is .
///
public int? PartitionNumber { get; set; }
///
/// Producer: the partition every record goes to (Apache Camel's partitionKey). It takes precedence over the
/// header, as in Camel; unset, the header decides, and without either Kafka's
/// partitioner places the record by its key. The key is sent with the record in every case.
///
public int? PartitionKey { get; set; }
///
/// Whether the send joins the enclosing transaction block (.Transacted() /
/// .BeginTransaction() ... .CommitTransaction()). Unset, it follows the block: deferred until the
/// database commits inside one, sent at once outside. true requires a block, fails outside one and also
/// makes the producer idempotent; false sends at once even inside a block. On its own this is at-least-once:
/// the deferred sends go out one after the other. Kafka transactions are .
///
public bool? Transacted { get; set; }
///
/// Switches the producer to Kafka transactions (transactional.id + InitTransactions). The sends it
/// defers in a .Transacted() block commit as one Kafka transaction when the block commits — all of them or none
/// — and when the route started from a Kafka consumer of the same cluster, the consumed offset commits in that same
/// transaction (SendOffsetsToTransaction): exactly-once within Kafka. A send outside a block is a transaction
/// of its own. The value is a prefix: the connector appends the machine name, the process id and the producer's
/// number, so every producer gets an id of its own and nodes deploying the same configuration never fence each
/// other. Requires acks=all and idempotence (both turned on); unset, the producer is not transactional.
///
public string? TransactionalIdPrefix { get; set; }
// ── Producer tuning ──
/// Batching delay in ms. Higher = more batching throughput.
public int? LingerMs { get; set; }
/// Max batch size in bytes.
public int? BatchSize { get; set; }
/// Compression: None, Gzip, Snappy, Lz4, Zstd.
public string? CompressionType { get; set; }
/// Total delivery timeout in ms (includes retries).
public int? MessageTimeoutMs { get; set; }
// ── Advanced ──
///
/// Additional librdkafka properties not exposed as typed settings.
/// Applied last — overrides any typed property.
///
public Dictionary AdditionalProperties { get; set; } = new();
///
public override void Validate()
{
if (string.IsNullOrWhiteSpace(Brokers))
throw new ArgumentException("The 'brokers' parameter is required for Kafka endpoints.", nameof(Brokers));
if (PartitionKey is < 0)
throw new ArgumentException($"Kafka partitionKey must be a partition number, 0 or more, not {PartitionKey}.", nameof(PartitionKey));
if (AckMode == AckMode.Auto && BreakOnFirstError)
throw new ArgumentException(
"ackMode=auto commits the offset before the route runs, and breakOnFirstError asks to read a failed " +
"record again: they contradict each other.");
// Every enum-valued option is parsed strictly at endpoint creation. A typo used
// to fall through Enum.TryParse / a silent `_ =>` arm into the default — for
// securityProtocol that meant a PLAINTEXT connection with no credentials.
// Note: SASL protocol without an explicit mechanism stays legal — librdkafka defaults to
// GSSAPI there, which is exactly what a Kerberos cluster wants.
KafkaOptionParsers.ParseOrThrow(SecurityProtocol, "securityProtocol");
if (!string.IsNullOrWhiteSpace(SaslMechanism))
{
var mechanism = KafkaOptionParsers.ParseOrThrow(SaslMechanism, "saslMechanism");
KafkaOptionParsers.RequireSaslCredentials(mechanism, SaslUsername, SaslPassword);
}
KafkaOptionParsers.ParseOrThrow(AutoOffsetReset, "autoOffsetReset");
if (SslEndpointIdentificationAlgorithm is not null)
KafkaOptionParsers.ParseEndpointIdentification(SslEndpointIdentificationAlgorithm);
var acks = KafkaOptionParsers.ParseAcks(Acks);
if (EnableIdempotence == true && acks != Confluent.Kafka.Acks.All)
throw new ArgumentException(
$"'enableIdempotence=true' requires 'acks=all', and acks is '{Acks}': the broker cannot drop a " +
"duplicate it has not confirmed on every replica. Set acks=all, or leave enableIdempotence unset.");
if (Transacted == true && acks != Confluent.Kafka.Acks.All)
throw new ArgumentException(
$"'transacted=true' makes the producer idempotent, which requires 'acks=all', and acks is '{Acks}'. " +
"Set acks=all, or drop transacted=true.");
if (TransactionalIdPrefix is not null)
{
if (string.IsNullOrWhiteSpace(TransactionalIdPrefix))
throw new ArgumentException("'transactionalIdPrefix' is empty: give the producer a name, or leave it unset.");
if (acks != Confluent.Kafka.Acks.All)
throw new ArgumentException(
$"'transactionalIdPrefix' makes the producer transactional, which requires 'acks=all', and acks is " +
$"'{Acks}'. Set acks=all, or drop transactionalIdPrefix.");
if (EnableIdempotence == false)
throw new ArgumentException(
"'transactionalIdPrefix' makes the producer transactional, and a transactional producer is " +
"idempotent: 'enableIdempotence=false' contradicts it.");
}
KafkaOptionParsers.RefuseReservedProperties(AdditionalProperties, "additionalProperties", IsIdempotentProducer);
if (!string.IsNullOrEmpty(IsolationLevel))
KafkaOptionParsers.ParseOrThrow(IsolationLevel, "isolationLevel");
if (!string.IsNullOrEmpty(PartitionAssignmentStrategy))
KafkaOptionParsers.ParseOrThrow(PartitionAssignmentStrategy, "partitionAssignmentStrategy");
if (!string.IsNullOrEmpty(CompressionType))
KafkaOptionParsers.ParseOrThrow(CompressionType, "compressionType");
if (!string.IsNullOrWhiteSpace(SeekTo))
KafkaOptionParsers.ParseSeekTo(SeekTo);
// A regex subscription and an explicit partition assignment contradict each other:
// Subscribe(pattern) joins the group, Assign(partition) bypasses it.
if (TopicIsPattern && PartitionNumber.HasValue)
throw new ArgumentException(
"'topicIsPattern' cannot be combined with 'partitionNumber': a regex subscription " +
"goes through the consumer group, an explicit partition bypasses it.");
if (PollTimeoutMs < 0)
throw new ArgumentOutOfRangeException(nameof(PollTimeoutMs), PollTimeoutMs, "PollTimeoutMs cannot be negative.");
if (Retries < 0)
throw new ArgumentOutOfRangeException(nameof(Retries), Retries, "Retries cannot be negative.");
}
// ── Config builders (internal) ──
///
/// Builds a from the options, optionally using a named factory as
/// the base. The family precedence rule — a parameter the URI actually supplied
/// ( = raw URI parameters) wins over the factory, everything else
/// keeps the factory's value. The old code was asymmetric: URI brokers were honored, URI
/// SASL/SSL silently swallowed, and endpoint DEFAULTS stomped explicit factory settings.
///
internal ConsumerConfig BuildConsumerConfig(KafkaConnectionFactory? factory = null,
IReadOnlyDictionary? supplied = null)
{
if (factory is not null)
{
var config = factory.BuildConsumerConfig(GroupId);
if (!string.IsNullOrWhiteSpace(Brokers)) config.BootstrapServers = Brokers;
if (WasSupplied(supplied, nameof(AutoOffsetReset)))
config.AutoOffsetReset = ParseAutoOffsetReset();
ApplySecurityOverrides(config, supplied);
ApplyConsumerTuning(config);
ApplyAdditionalProperties(config);
return config;
}
var cfg = new ConsumerConfig
{
BootstrapServers = Brokers,
GroupId = GroupId,
AutoOffsetReset = ParseAutoOffsetReset(),
EnableAutoCommit = false, // always manual commit for transactional safety
};
ApplySecurity(cfg);
ApplySsl(cfg);
ApplyConsumerTuning(cfg);
ApplyAdditionalProperties(cfg);
return cfg;
}
/// Builds a from the options, optionally using a named factory as base.
/// Same precedence rule as .
internal ProducerConfig BuildProducerConfig(KafkaConnectionFactory? factory = null,
IReadOnlyDictionary? supplied = null)
{
ProducerConfig config;
if (factory is not null)
{
config = factory.BuildProducerConfig();
if (!string.IsNullOrWhiteSpace(Brokers)) config.BootstrapServers = Brokers;
if (WasSupplied(supplied, nameof(Retries)))
config.MessageSendMaxRetries = Retries;
if (WasSupplied(supplied, nameof(Acks)))
config.Acks = ParseAcks();
ApplySecurityOverrides(config, supplied);
}
else
{
config = new ProducerConfig
{
BootstrapServers = Brokers,
Acks = ParseAcks(),
MessageSendMaxRetries = Retries,
};
ApplySecurity(config);
ApplySsl(config);
}
// Idempotence follows the effective acks unless the endpoint says otherwise (acks=all, the default, turns it on,
// as in the Kafka 3 client). Set before the tuning, so additionalProperties still has the last word.
config.EnableIdempotence = EnableIdempotence ?? config.Acks == Confluent.Kafka.Acks.All;
// Validate() sees the endpoint's acks only; the effective one may come from the connection factory. Said here in
// the connector's words, not left to librdkafka refusing the client.
if (EnableIdempotence == true && config.Acks != Confluent.Kafka.Acks.All)
throw new ArgumentException(
$"'enableIdempotence=true' requires 'acks=all', and the connection factory '{ConnectionFactory}' sets acks " +
$"to '{config.Acks}': the broker cannot drop a duplicate it has not confirmed on every replica. Set acks=all " +
"on the endpoint or the factory, or leave enableIdempotence unset.");
ApplyProducerTuning(config);
if (Transacted == true || TransactionalIdPrefix is not null)
{
// `transacted=true` is an idempotent producer whose send is deferred to the route's transaction boundary.
// The transactional.id of a Kafka-transactional producer is set by the producer itself (KafkaProducer),
// which appends its own identity to TransactionalIdPrefix: every producer instance needs an id of its own.
config.EnableIdempotence = true;
config.Acks = Confluent.Kafka.Acks.All; // required for the idempotent producer
}
return config;
}
private Confluent.Kafka.AutoOffsetReset ParseAutoOffsetReset() =>
KafkaOptionParsers.ParseOrThrow(AutoOffsetReset, "autoOffsetReset");
private Confluent.Kafka.Acks ParseAcks() => KafkaOptionParsers.ParseAcks(Acks);
private void ApplySecurity(ClientConfig config)
{
config.SecurityProtocol =
KafkaOptionParsers.ParseOrThrow(SecurityProtocol, "securityProtocol");
if (!string.IsNullOrWhiteSpace(SaslMechanism))
{
var mechanism = KafkaOptionParsers.ParseOrThrow(SaslMechanism, "saslMechanism");
KafkaOptionParsers.RequireSaslCredentials(mechanism, SaslUsername, SaslPassword);
config.SaslMechanism = mechanism;
config.SaslUsername = SaslUsername;
config.SaslPassword = SaslPassword;
}
}
private void ApplySsl(ClientConfig config)
{
if (!string.IsNullOrEmpty(SslCaLocation)) config.SslCaLocation = SslCaLocation;
if (!string.IsNullOrEmpty(SslCertificateLocation)) config.SslCertificateLocation = SslCertificateLocation;
if (!string.IsNullOrEmpty(SslKeyLocation)) config.SslKeyLocation = SslKeyLocation;
if (!string.IsNullOrEmpty(SslKeyPassword)) config.SslKeyPassword = SslKeyPassword;
ApplySslEndpointIdentification(config);
}
private void ApplySslEndpointIdentification(ClientConfig config)
{
if (SslEndpointIdentificationAlgorithm is null) return;
config.SslEndpointIdentificationAlgorithm =
KafkaOptionParsers.ParseEndpointIdentification(SslEndpointIdentificationAlgorithm);
}
/// Admin/metadata client config carrying the endpoint's own security.
internal AdminClientConfig BuildAdminConfig()
{
var config = new AdminClientConfig { BootstrapServers = Brokers };
ApplySecurity(config);
ApplySsl(config);
return config;
}
private static bool WasSupplied(IReadOnlyDictionary? supplied, string name)
=> supplied is not null && supplied.Keys.Any(k => string.Equals(k, name, StringComparison.OrdinalIgnoreCase));
///
/// URI-supplied security/SSL parameters applied over the factory base, key by key: a hybrid
/// like "mechanism from the factory, password from the URI" resolves the way it reads.
///
private void ApplySecurityOverrides(ClientConfig config, IReadOnlyDictionary? supplied)
{
if (WasSupplied(supplied, nameof(SecurityProtocol)))
config.SecurityProtocol =
KafkaOptionParsers.ParseOrThrow(SecurityProtocol, "securityProtocol");
if (WasSupplied(supplied, nameof(SaslMechanism)) && !string.IsNullOrWhiteSpace(SaslMechanism))
config.SaslMechanism =
KafkaOptionParsers.ParseOrThrow(SaslMechanism, "saslMechanism");
if (WasSupplied(supplied, nameof(SaslUsername))) config.SaslUsername = SaslUsername;
if (WasSupplied(supplied, nameof(SaslPassword))) config.SaslPassword = SaslPassword;
if (WasSupplied(supplied, nameof(SslCaLocation))) config.SslCaLocation = SslCaLocation;
if (WasSupplied(supplied, nameof(SslCertificateLocation))) config.SslCertificateLocation = SslCertificateLocation;
if (WasSupplied(supplied, nameof(SslKeyLocation))) config.SslKeyLocation = SslKeyLocation;
if (WasSupplied(supplied, nameof(SslKeyPassword))) config.SslKeyPassword = SslKeyPassword;
if (WasSupplied(supplied, nameof(SslEndpointIdentificationAlgorithm)))
ApplySslEndpointIdentification(config);
}
private void ApplyConsumerTuning(ConsumerConfig config)
{
if (!string.IsNullOrEmpty(GroupInstanceId)) config.GroupInstanceId = GroupInstanceId;
if (SessionTimeoutMs.HasValue) config.SessionTimeoutMs = SessionTimeoutMs.Value;
if (HeartbeatIntervalMs.HasValue) config.HeartbeatIntervalMs = HeartbeatIntervalMs.Value;
if (MaxPollIntervalMs.HasValue) config.MaxPollIntervalMs = MaxPollIntervalMs.Value;
if (!string.IsNullOrEmpty(PartitionAssignmentStrategy))
config.PartitionAssignmentStrategy = KafkaOptionParsers.ParseOrThrow(
PartitionAssignmentStrategy, "partitionAssignmentStrategy");
if (!string.IsNullOrEmpty(IsolationLevel))
config.IsolationLevel = KafkaOptionParsers.ParseOrThrow(
IsolationLevel, "isolationLevel");
}
private void ApplyProducerTuning(ProducerConfig config)
{
if (LingerMs.HasValue) config.LingerMs = LingerMs.Value;
if (BatchSize.HasValue) config.BatchSize = BatchSize.Value;
if (MessageTimeoutMs.HasValue) config.MessageTimeoutMs = MessageTimeoutMs.Value;
if (!string.IsNullOrEmpty(CompressionType))
config.CompressionType = KafkaOptionParsers.ParseOrThrow(
CompressionType, "compressionType");
ApplyAdditionalProperties(config);
}
private void ApplyAdditionalProperties(ClientConfig config)
{
foreach (var kvp in AdditionalProperties)
config.Set(kvp.Key, kvp.Value);
}
}