Bundle: redb-route / redb.Route.Kafka (redb.Route.Kafka.txt), 16 files
Snapshot: 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
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/redb.Route.Kafka/AssemblyInfo.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/AssemblyInfo.cs
----
// redb_Route_Kafka - placeholder for build
Path: redb-route/redb.Route.Kafka/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
namespace redb.Route.Kafka;
///
/// Extension methods for registering the Kafka transport in a DI container.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the in the route context so that
/// kafka:// URIs are resolved.
///
///
/// services.AddRedbRoute(route =>
/// {
/// route.Services.AddRedbRouteKafka();
/// route.AddRouteBuilder<MyRoutes>();
/// });
///
///
///
public static IServiceCollection AddRedbRouteKafka(this IServiceCollection services)
{
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteComponent();
return services;
}
}
Path: redb-route/redb.Route.Kafka/Fluent/KafkaDsl.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/Fluent/KafkaDsl.cs
----
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Expressions;
namespace redb.Route.Kafka;
///
/// Fluent API for Kafka endpoints.
///
/// .From(Kafka.Topic("orders").Brokers("broker1:9092").GroupId("order-group").AutoOffsetReset("Earliest"))
/// .To(Kafka.Topic("notifications").Brokers("broker1:9092").Acks("All"))
///
///
public static class Kafka
{
/// Creates a Kafka endpoint for the given topic name.
public static KafkaBuilder Topic(string name) => new(name);
}
///
/// Fluent builder for Kafka endpoint URIs.
///
public sealed class KafkaBuilder
{
private readonly string _topic;
// Connection
private string? _brokers;
private string? _securityProtocol;
private string? _saslMechanism;
private string? _saslUsername;
private string? _saslPassword;
private string? _sslCaLocation;
private string? _sslCertificateLocation;
private string? _sslKeyLocation;
private string? _sslKeyPassword;
private string? _sslEndpointIdentification;
private string? _connectionFactory;
// Consumer
private string? _groupId;
private string? _autoOffsetReset;
private AckMode? _ackMode;
private bool _batching;
private string? _maxBatchMessages;
private string? _batchingIntervalMs;
private string? _pollTimeoutMs;
private bool _breakOnFirstError;
private string? _seekTo;
private bool _topicIsPattern;
private string? _groupInstanceId;
private string? _sessionTimeoutMs;
private string? _heartbeatIntervalMs;
private string? _maxPollIntervalMs;
private string? _partitionAssignmentStrategy;
private string? _isolationLevel;
// Producer
private string? _acks;
private string? _retries;
private bool _recordMetadata;
private string? _key;
private string? _partitionNumber;
private string? _partitionKey;
private bool? _transacted;
private bool? _enableIdempotence;
private string? _transactionalIdPrefix;
private string? _lingerMs;
private string? _batchSize;
private string? _compressionType;
private string? _messageTimeoutMs;
internal KafkaBuilder(string topic)
{
ArgumentException.ThrowIfNullOrWhiteSpace(topic);
_topic = topic;
}
// ── Connection ────────────────────────────────────────────────────
/// Bootstrap servers (comma-separated host:port). e.g. "broker1:9092,broker2:9092".
public KafkaBuilder Brokers(IExpression brokers) { _brokers = brokers.ToTemplateString(); return this; }
/// Bootstrap servers (template string, supports ${...}). e.g. "broker1:9092,broker2:9092".
public KafkaBuilder Brokers(string brokers) { _brokers = brokers; return this; }
/// Security protocol: Plaintext, Ssl, SaslPlaintext, SaslSsl.
public KafkaBuilder SecurityProtocol(string protocol) { _securityProtocol = protocol; return this; }
/// SASL authentication: mechanism + credentials.
public KafkaBuilder Sasl(string mechanism, IExpression username, IExpression password)
{
_saslMechanism = mechanism; _saslUsername = username.ToTemplateString(); _saslPassword = password.ToTemplateString(); return this;
}
/// Path to CA certificate file for SSL.
public KafkaBuilder SslCa(IExpression path) { _sslCaLocation = path.ToTemplateString(); return this; }
/// Path to CA certificate file for SSL (template string, supports ${...}).
public KafkaBuilder SslCa(string path) { _sslCaLocation = path; return this; }
/// Client certificate for mutual TLS.
public KafkaBuilder SslCert(IExpression certPath, IExpression? keyPath = null, IExpression? keyPassword = null)
{
_sslCertificateLocation = certPath.ToTemplateString(); _sslKeyLocation = keyPath?.ToTemplateString(); _sslKeyPassword = keyPassword?.ToTemplateString(); return this;
}
/// Client certificate for mutual TLS (template strings, support ${...}).
public KafkaBuilder SslCert(string certPath, string? keyPath = null, string? keyPassword = null)
{
_sslCertificateLocation = certPath; _sslKeyLocation = keyPath; _sslKeyPassword = keyPassword; return this;
}
///
/// Whether the broker's hostname is verified against its certificate (sslEndpointIdentificationAlgorithm
/// https / none). Unset, librdkafka verifies it.
///
public KafkaBuilder SslVerifyHostname(bool verify = true) { _sslEndpointIdentification = verify ? "https" : "none"; return this; }
/// Use a named connection factory registered in DI.
public KafkaBuilder ConnectionFactory(IExpression name) { _connectionFactory = name.ToTemplateString(); return this; }
/// Use a named connection factory registered in DI (template string, supports ${...}).
public KafkaBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; }
// ── Consumer ──────────────────────────────────────────────────────
/// Consumer group ID.
public KafkaBuilder GroupId(IExpression groupId) { _groupId = groupId.ToTemplateString(); return this; }
/// Consumer group ID (template string, supports ${...}).
public KafkaBuilder GroupId(string groupId) { _groupId = groupId; return this; }
/// Auto offset reset: Latest, Earliest, Error.
public KafkaBuilder AutoOffsetReset(string reset) { _autoOffsetReset = reset; return this; }
///
/// When the offset is committed: after the route (, default; a transactional
/// route's commit takes precedence) or on receipt (, at-most-once).
///
public KafkaBuilder AckMode(AckMode mode) { _ackMode = mode; return this; }
/// Batch mode (batching=true): the route gets the records as a List<IMessage>.
public KafkaBuilder Batching() { _batching = true; return this; }
/// Largest number of records in a batch (maxBatchMessages, default 500). Batch mode only.
public KafkaBuilder MaxBatchMessages(int max) { _maxBatchMessages = max.ToString(); return this; }
/// Largest number of records in a batch from an expression.
public KafkaBuilder MaxBatchMessages(IExpression max) { _maxBatchMessages = max.ToTemplateString(); return this; }
/// Hard limit of a batch in milliseconds from its first record (batchingIntervalMs). Batch mode only.
public KafkaBuilder BatchingIntervalMs(int ms) { _batchingIntervalMs = ms.ToString(); return this; }
/// Hard limit of a batch from an expression.
public KafkaBuilder BatchingIntervalMs(IExpression ms) { _batchingIntervalMs = ms.ToTemplateString(); return this; }
/// Poll timeout in milliseconds, default 1000; in batch mode the idle timeout of a batch.
public KafkaBuilder PollTimeout(int ms) { _pollTimeoutMs = ms.ToString(); return this; }
/// Poll timeout from an expression.
public KafkaBuilder PollTimeout(IExpression ms) { _pollTimeoutMs = ms.ToTemplateString(); return this; }
/// Stop consuming on first error.
public KafkaBuilder BreakOnFirstError() { _breakOnFirstError = true; return this; }
/// Seek each assigned partition once to a position: "beginning" or "end".
public KafkaBuilder SeekTo(string position) { _seekTo = position; return this; }
/// Treat topic name as a regex pattern.
public KafkaBuilder TopicIsPattern() { _topicIsPattern = true; return this; }
/// Consumer: read this one partition (partitionNumber) instead of joining the group's assignment.
public KafkaBuilder PartitionNumber(int partition) { _partitionNumber = partition.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; }
/// Static group instance ID for cooperative rebalancing.
public KafkaBuilder GroupInstanceId(IExpression id) { _groupInstanceId = id.ToTemplateString(); return this; }
/// Static group instance ID for cooperative rebalancing (template string, supports ${...}).
public KafkaBuilder GroupInstanceId(string id) { _groupInstanceId = id; return this; }
/// Session timeout in milliseconds.
public KafkaBuilder SessionTimeout(int ms) { _sessionTimeoutMs = ms.ToString(); return this; }
/// Session timeout from an expression.
public KafkaBuilder SessionTimeout(IExpression ms) { _sessionTimeoutMs = ms.ToTemplateString(); return this; }
/// Heartbeat interval in milliseconds.
public KafkaBuilder HeartbeatInterval(int ms) { _heartbeatIntervalMs = ms.ToString(); return this; }
/// Heartbeat interval from an expression.
public KafkaBuilder HeartbeatInterval(IExpression ms) { _heartbeatIntervalMs = ms.ToTemplateString(); return this; }
/// Max poll interval in milliseconds.
public KafkaBuilder MaxPollInterval(int ms) { _maxPollIntervalMs = ms.ToString(); return this; }
/// Max poll interval from an expression.
public KafkaBuilder MaxPollInterval(IExpression ms) { _maxPollIntervalMs = ms.ToTemplateString(); return this; }
/// Partition assignment strategy.
public KafkaBuilder PartitionAssignmentStrategy(string strategy) { _partitionAssignmentStrategy = strategy; return this; }
/// Isolation level: ReadUncommitted, ReadCommitted.
public KafkaBuilder IsolationLevel(string level) { _isolationLevel = level; return this; }
// ── Producer ──────────────────────────────────────────────────────
/// Acknowledge level: None, Leader, All. Default "All".
public KafkaBuilder Acks(string acks) { _acks = acks; return this; }
/// Number of retries. Default 3.
public KafkaBuilder Retries(int count) { _retries = count.ToString(); return this; }
/// Retries from an expression.
public KafkaBuilder Retries(IExpression count) { _retries = count.ToTemplateString(); return this; }
/// Include record metadata (partition, offset) in the exchange after produce.
public KafkaBuilder RecordMetadata() { _recordMetadata = true; return this; }
/// Message key for partitioning.
public KafkaBuilder Key(IExpression key) { _key = key.ToTemplateString(); return this; }
/// Message key for partitioning (template string, supports ${...}).
public KafkaBuilder Key(string key) { _key = key; return this; }
///
/// Producer: the partition every record goes to (partitionKey, Apache Camel's name); it takes precedence over
/// the per-message header, as in Camel. To choose the partition per message, set
/// that header instead.
///
public KafkaBuilder PartitionKey(int partition) { _partitionKey = partition.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; }
///
/// The send joins the enclosing .Transacted() block (deferred until the database commits) and refuses to run
/// outside one; the producer is idempotent. Kafka transactions are a separate switch,
/// .
///
public KafkaBuilder Transacted() { _transacted = true; return this; }
///
/// Sets transacted explicitly. false sends at once even inside a .Transacted() block, outside its
/// transaction; left unset, a producer follows the block.
///
public KafkaBuilder Transacted(bool value) { _transacted = value; return this; }
///
/// Sets enableIdempotence: the broker does not write a retried send twice. Left unset, it follows acks: on
/// with all (the default), off otherwise.
///
public KafkaBuilder EnableIdempotence(bool value = true) { _enableIdempotence = value; return this; }
///
/// Sets transactionalIdPrefix: the producer uses Kafka transactions. The sends it defers in a
/// .Transacted() block commit as one Kafka transaction when the block commits, together with the offset of the
/// Kafka record the route consumed (exactly-once within Kafka); a send outside a block is a transaction of its own.
/// The prefix names the producer: the connector appends the machine, the process and the producer's number, so nodes
/// sharing the configuration never fence each other.
///
public KafkaBuilder TransactionalIdPrefix(string prefix) { _transactionalIdPrefix = prefix; return this; }
/// Linger time in milliseconds (batch delay).
public KafkaBuilder Linger(int ms) { _lingerMs = ms.ToString(); return this; }
/// Linger from an expression.
public KafkaBuilder Linger(IExpression ms) { _lingerMs = ms.ToTemplateString(); return this; }
/// Batch size in bytes.
public KafkaBuilder BatchSize(int bytes) { _batchSize = bytes.ToString(); return this; }
/// Batch size from an expression.
public KafkaBuilder BatchSize(IExpression bytes) { _batchSize = bytes.ToTemplateString(); return this; }
/// Compression type: none, gzip, snappy, lz4, zstd.
public KafkaBuilder Compression(string type) { _compressionType = type; return this; }
/// Message delivery timeout in milliseconds.
public KafkaBuilder MessageTimeout(int ms) { _messageTimeoutMs = ms.ToString(); return this; }
/// Message timeout from an expression.
public KafkaBuilder MessageTimeout(IExpression ms) { _messageTimeoutMs = ms.ToTemplateString(); return this; }
// ── Build ─────────────────────────────────────────────────────────
/// Builds the Kafka endpoint URI string.
public string Build()
{
var sb = new StringBuilder();
sb.Append("kafka:");
sb.Append(_topic);
var sep = '?';
void Append(string key, string value)
{
sb.Append(sep); sb.Append(key); sb.Append('=');
sb.Append(Uri.EscapeDataString(value)); sep = '&';
}
void AppendIf(string key, string? value) { if (value != null) Append(key, value); }
void AppendBool(string key, bool value) { if (value) Append(key, "true"); }
// Connection
AppendIf("brokers", _brokers);
AppendIf("securityProtocol", _securityProtocol);
AppendIf("saslMechanism", _saslMechanism);
AppendIf("saslUsername", _saslUsername);
AppendIf("saslPassword", _saslPassword);
AppendIf("sslCaLocation", _sslCaLocation);
AppendIf("sslCertificateLocation", _sslCertificateLocation);
AppendIf("sslKeyLocation", _sslKeyLocation);
AppendIf("sslKeyPassword", _sslKeyPassword);
AppendIf("sslEndpointIdentificationAlgorithm", _sslEndpointIdentification);
AppendIf("connectionFactory", _connectionFactory);
// Consumer
AppendIf("groupId", _groupId);
AppendIf("autoOffsetReset", _autoOffsetReset);
AppendIf("ackMode", _ackMode?.ToString().ToLowerInvariant());
if (_batching) Append("batching", "true");
AppendIf("maxBatchMessages", _maxBatchMessages);
AppendIf("batchingIntervalMs", _batchingIntervalMs);
AppendIf("pollTimeoutMs", _pollTimeoutMs);
AppendBool("breakOnFirstError", _breakOnFirstError);
AppendIf("seekTo", _seekTo);
AppendBool("topicIsPattern", _topicIsPattern);
AppendIf("groupInstanceId", _groupInstanceId);
AppendIf("sessionTimeoutMs", _sessionTimeoutMs);
AppendIf("heartbeatIntervalMs", _heartbeatIntervalMs);
AppendIf("maxPollIntervalMs", _maxPollIntervalMs);
AppendIf("partitionAssignmentStrategy", _partitionAssignmentStrategy);
AppendIf("isolationLevel", _isolationLevel);
// Producer
AppendIf("acks", _acks);
AppendIf("retries", _retries);
AppendBool("recordMetadata", _recordMetadata);
AppendIf("key", _key);
AppendIf("partitionNumber", _partitionNumber);
AppendIf("partitionKey", _partitionKey);
if (_transacted is { } transacted) Append("transacted", transacted ? "true" : "false");
if (_enableIdempotence is { } idempotence) Append("enableIdempotence", idempotence ? "true" : "false");
AppendIf("transactionalIdPrefix", _transactionalIdPrefix);
AppendIf("lingerMs", _lingerMs);
AppendIf("batchSize", _batchSize);
AppendIf("compressionType", _compressionType);
AppendIf("messageTimeoutMs", _messageTimeoutMs);
return sb.ToString();
}
/// Implicit conversion to URI string.
public static implicit operator string(KafkaBuilder b) => b.Build();
///
public override string ToString() => Build();
}
Path: redb-route/redb.Route.Kafka/KafkaComponent.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/KafkaComponent.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Extensions;
namespace redb.Route.Kafka;
///
/// Apache Kafka transport component for redb.Route.
/// Scheme: kafka.
///
/// URI format: kafka://topic-name?brokers=host:9092&groupId=group&autoOffsetReset=Earliest
///
///
public sealed partial class KafkaComponent : ComponentBase
{
///
public override string Scheme => "kafka";
/// Structured XML form: <kafka topic="orders"/>.
public override string? StructuredPathSynonym => "topic";
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new KafkaEndpointOptions();
options.BindFromUri(uri.RawParameters);
// Resolve the named ConnectionFactory BEFORE Validate(): the factory may be the only
// source of the brokers. A set-but-unknown name fails loud — a typo must never
// silently fall back to URI parameters.
KafkaConnectionFactory? factory = null;
if (!string.IsNullOrEmpty(options.ConnectionFactory))
{
factory = Context.GetRequiredFromRegistry(options.ConnectionFactory);
if (string.IsNullOrWhiteSpace(options.Brokers))
options.Brokers = factory.Brokers;
// Validate() and the consumer's groupId check see only the
// options, so factory values that act as defaults must land there BEFORE validation -
// otherwise "credentials via a named connectionFactory" (the error text's own advice)
// and the factory's documented default GroupId can never work. URI still wins:
// the copy happens only when the URI supplied nothing.
if (string.IsNullOrWhiteSpace(options.SaslUsername))
options.SaslUsername = factory.SaslUsername;
if (string.IsNullOrWhiteSpace(options.SaslPassword))
options.SaslPassword = factory.SaslPassword;
if (string.IsNullOrWhiteSpace(options.GroupId))
options.GroupId = factory.GroupId;
// The factory's additionalProperties are applied last too: the same properties are refused there.
KafkaOptionParsers.RefuseReservedProperties(factory.AdditionalProperties,
$"the additionalProperties of connection factory '{options.ConnectionFactory}'",
options.IsIdempotentProducer);
}
options.Validate();
options.ResolveBatch(EndpointUri.Sanitize(uri.BaseKey));
return new KafkaEndpoint(uri, this, options, factory);
}
}
Path: redb-route/redb.Route.Kafka/KafkaConnectionFactory.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/KafkaConnectionFactory.cs
----
using Confluent.Kafka;
namespace redb.Route.Kafka;
///
/// Connection factory for Kafka. Register via DI or in the route registry
/// and reference by name in endpoint URIs (connectionFactory=myFactory).
/// Centralises broker addresses and security settings so they can be shared
/// across multiple Kafka endpoints without duplicating URI parameters.
///
public sealed class KafkaConnectionFactory
{
/// Comma-separated list of Kafka broker addresses (e.g., "broker1:9092,broker2:9092").
public string Brokers { get; set; } = "localhost:9092";
// ── Security ──
/// Security protocol: Plaintext, Ssl, SaslPlaintext, SaslSsl.
public string SecurityProtocol { get; set; } = "Plaintext";
/// SASL mechanism: Plain, ScramSha256, ScramSha512, OAuthBearer.
public string? SaslMechanism { get; set; }
/// SASL username.
public string? SaslUsername { get; set; }
/// SASL password.
[redb.Route.Core.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.
[redb.Route.Core.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).
///
public string? SslEndpointIdentificationAlgorithm { get; set; }
// ── Producer defaults ──
/// Default acknowledgment level: None, Leader, All. Default All, as in the Kafka 3 client and Camel 4.
public string Acks { get; set; } = "All";
/// Default number of retries for failed sends.
public int Retries { get; set; } = 3;
// ── Consumer defaults ──
/// Default consumer group ID.
public string? GroupId { get; set; }
/// Default auto-offset reset: Latest, Earliest, Error.
public string AutoOffsetReset { get; set; } = "Latest";
// ── Consumer cluster tuning ──
/// Static group instance ID for consumer. Avoids rebalance storms during rolling deploys (K8s).
public string? GroupInstanceId { get; set; }
/// Consumer session timeout in ms (default: 45000). Lower = faster dead-consumer detection.
public int? SessionTimeoutMs { get; set; }
/// Consumer heartbeat interval in ms (default: 3000). Should be < SessionTimeoutMs/3.
public int? HeartbeatIntervalMs { get; set; }
/// Max time between polls in ms (default: 300000). Prevents endless processing from triggering rebalance.
public int? MaxPollIntervalMs { get; set; }
/// Partition assignment strategy: Range, RoundRobin, CooperativeSticky. CooperativeSticky avoids stop-the-world rebalance.
public string? PartitionAssignmentStrategy { get; set; }
///
/// Isolation level: ReadUncommitted, ReadCommitted. ReadCommitted hides records of aborted
/// transactions, including those of this connector's transactional producers
/// (transactionalIdPrefix).
///
public string? IsolationLevel { get; set; }
// ── Producer tuning ──
/// Batching delay in ms (default: 5). Higher = more batching. 0 = no batching.
public int? LingerMs { get; set; }
/// Max batch size in bytes (default: 1000000).
public int? BatchSize { get; set; }
/// Compression type: None, Gzip, Snappy, Lz4, Zstd.
public string? CompressionType { get; set; }
/// Total delivery timeout in ms (default: 120000). Includes retries.
public int? MessageTimeoutMs { get; set; }
// ── Reconnect ──
/// Reconnect backoff initial in ms (default: 100).
public int? ReconnectBackoffMs { get; set; }
/// Reconnect backoff max in ms (default: 10000).
public int? ReconnectBackoffMaxMs { get; set; }
// ── Advanced ──
/// Client ID for broker identification.
public string ClientId { get; set; } = "redb.Route";
/// Request timeout in ms (default: 30000).
public int RequestTimeoutMs { get; set; } = 30_000;
/// Metadata max age in ms before refresh (default: 300000).
public int MetadataMaxAgeMs { get; set; } = 300_000;
/// Socket timeout in ms (default: 60000).
public int SocketTimeoutMs { get; set; } = 60_000;
/// Max in-flight requests per connection (default: 5). Set to 1 for strict ordering.
public int MaxInFlight { get; set; } = 5;
///
/// Additional librdkafka properties not exposed as typed settings.
/// Keys are librdkafka config names (e.g. "socket.keepalive.enable").
/// Applied last — overrides any typed property.
///
public Dictionary AdditionalProperties { get; set; } = new();
///
/// Builds a with all factory settings.
/// Endpoint-specific overrides (GroupId, AutoOffsetReset, etc.) take precedence when applied afterwards.
///
public ConsumerConfig BuildConsumerConfig(string? groupIdOverride = null)
{
var config = new ConsumerConfig
{
BootstrapServers = Brokers,
GroupId = groupIdOverride ?? GroupId,
AutoOffsetReset = ParseAutoOffsetReset(),
EnableAutoCommit = false,
ClientId = ClientId,
MetadataMaxAgeMs = MetadataMaxAgeMs,
SocketTimeoutMs = SocketTimeoutMs,
MaxInFlight = MaxInFlight,
};
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 (ReconnectBackoffMs.HasValue) config.ReconnectBackoffMs = ReconnectBackoffMs.Value;
if (ReconnectBackoffMaxMs.HasValue) config.ReconnectBackoffMaxMs = ReconnectBackoffMaxMs.Value;
if (!string.IsNullOrEmpty(PartitionAssignmentStrategy))
config.PartitionAssignmentStrategy = ParsePartitionAssignment();
if (!string.IsNullOrEmpty(IsolationLevel))
config.IsolationLevel = ParseIsolationLevel();
ApplySecurity(config);
ApplySsl(config);
ApplyAdditionalProperties(config);
return config;
}
///
/// Builds a with all factory settings.
///
public ProducerConfig BuildProducerConfig()
{
var config = new ProducerConfig
{
BootstrapServers = Brokers,
Acks = ParseAcks(),
MessageSendMaxRetries = Retries,
ClientId = ClientId,
RequestTimeoutMs = RequestTimeoutMs,
MetadataMaxAgeMs = MetadataMaxAgeMs,
SocketTimeoutMs = SocketTimeoutMs,
MaxInFlight = MaxInFlight,
};
if (LingerMs.HasValue) config.LingerMs = LingerMs.Value;
if (BatchSize.HasValue) config.BatchSize = BatchSize.Value;
if (MessageTimeoutMs.HasValue) config.MessageTimeoutMs = MessageTimeoutMs.Value;
if (ReconnectBackoffMs.HasValue) config.ReconnectBackoffMs = ReconnectBackoffMs.Value;
if (ReconnectBackoffMaxMs.HasValue) config.ReconnectBackoffMaxMs = ReconnectBackoffMaxMs.Value;
if (!string.IsNullOrEmpty(CompressionType))
config.CompressionType = ParseCompressionType();
ApplySecurity(config);
ApplySsl(config);
ApplyAdditionalProperties(config);
return config;
}
///
/// Builds an for metadata queries.
///
public AdminClientConfig BuildAdminConfig()
{
var config = new AdminClientConfig
{
BootstrapServers = Brokers,
ClientId = ClientId,
SocketTimeoutMs = SocketTimeoutMs,
};
ApplySecurity(config);
ApplySsl(config);
ApplyAdditionalProperties(config);
return config;
}
// ── Helpers ──
// Strict parses shared with the endpoint options — a typo throws instead of
// silently keeping the default (for securityProtocol the default is plaintext).
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;
if (SslEndpointIdentificationAlgorithm is not null)
config.SslEndpointIdentificationAlgorithm =
KafkaOptionParsers.ParseEndpointIdentification(SslEndpointIdentificationAlgorithm);
}
private void ApplyAdditionalProperties(ClientConfig config)
{
foreach (var kvp in AdditionalProperties)
config.Set(kvp.Key, kvp.Value);
}
private Confluent.Kafka.PartitionAssignmentStrategy ParsePartitionAssignment() =>
KafkaOptionParsers.ParseOrThrow(
PartitionAssignmentStrategy!, "partitionAssignmentStrategy");
private Confluent.Kafka.IsolationLevel ParseIsolationLevel() =>
KafkaOptionParsers.ParseOrThrow(IsolationLevel!, "isolationLevel");
private Confluent.Kafka.CompressionType ParseCompressionType() =>
KafkaOptionParsers.ParseOrThrow(CompressionType!, "compressionType");
}
Path: redb-route/redb.Route.Kafka/KafkaConsumedOffsets.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/KafkaConsumedOffsets.cs
----
using Confluent.Kafka;
using Confluent.Kafka.Admin;
using redb.Route.Abstractions;
namespace redb.Route.Kafka;
///
/// The offsets a Kafka consumer is about to commit for the exchange it handed the route, offered to a Kafka-transactional
/// producer of the same cluster in that route. Committed inside the producer's transaction
/// (SendOffsetsToTransaction), they become visible together with its sends — exactly-once within Kafka — and the
/// consumer does not commit them itself.
///
/// Claimable only while the consumer is still waiting for the route: a copy the route handed on asynchronously (seda,
/// .Threads()) commits after the consumer moved on, with a group generation that may no longer be current, and
/// must not take them. One transaction takes them at most.
///
///
/// Claimable only by the exchange the consumer handed the route. A split part, a multicast branch or any other copy
/// inherits the exchange's properties, this one included, but it is one part of the unit of work: its transaction
/// committing the offsets would commit the whole record or batch before the other parts ran. The consumer commits them
/// once, after the route returned.
///
///
internal sealed class KafkaConsumedOffsets
{
/// Exchange property the consumer offers the offsets under.
internal const string PropertyKey = "KafkaConsumedOffsets";
private const int Open = 0, Claimed = 1, Closed = 2;
private readonly IConsumer _consumer;
private readonly KafkaCommitAction _commit;
private readonly IExchange _owner;
private int _state;
public KafkaConsumedOffsets(IConsumer consumer, KafkaCommitAction commit, string? cluster, IExchange owner)
{
_consumer = consumer;
_commit = commit;
Cluster = cluster;
_owner = owner;
}
/// The consumer's cluster id (); null when the consumer could not read it.
public string? Cluster { get; }
/// The positions to commit: the next offset to read, per partition.
public IReadOnlyList Offsets => _commit.NextOffsets;
/// The consumer's group metadata, read when the transaction commits: it carries the current generation.
public IConsumerGroupMetadata GroupMetadata => _consumer.ConsumerGroupMetadata;
/// Takes the offsets for a transaction; false when another took them or the consumer has finished.
public bool TryClaim() => Interlocked.CompareExchange(ref _state, Claimed, Open) == Open;
/// The transaction that took them did not commit: they are the consumer's again.
public void Release() => Interlocked.CompareExchange(ref _state, Open, Claimed);
/// The transaction committed them: the consumer must not commit them again.
public void MarkCommitted() => _commit.MarkCommitted();
/// The route returned to the consumer: no transaction may take them any more.
public void Close() => Interlocked.CompareExchange(ref _state, Closed, Open);
/// True once the route returned to the consumer: a transaction that did not take them before cannot now.
public bool IsClosed => Volatile.Read(ref _state) == Closed;
///
/// The offsets a Kafka consumer offered on itself, of whatever cluster, if any. Offsets
/// only inherited from the exchange they were offered on are reported through
/// and not returned.
///
public static KafkaConsumedOffsets? OfferedOn(IExchange exchange, out bool inherited)
{
inherited = false;
if (!exchange.Properties.TryGetValue(PropertyKey, out var value) || value is not KafkaConsumedOffsets offsets)
return null;
if (ReferenceEquals(offsets._owner, exchange))
return offsets;
inherited = true;
return null;
}
///
/// A cluster's identity for matching a consumer with a producer: the cluster id its brokers report, read through the
/// client's own connection (). Brokers listed differently on the two ends are still one
/// cluster; a producer of another cluster cannot commit these offsets, they belong to the consumer group of this one.
///
public static async Task ClusterIdOf(Handle handle, TimeSpan timeout)
{
using var admin = new DependentAdminClientBuilder(handle).Build();
var cluster = await admin.DescribeClusterAsync(new DescribeClusterOptions { RequestTimeout = timeout })
.ConfigureAwait(false);
return cluster.ClusterId ?? throw new InvalidOperationException("The Kafka cluster reported no cluster id.");
}
}
Path: redb-route/redb.Route.Kafka/KafkaConsumer.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/KafkaConsumer.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
using Confluent.Kafka;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Batching;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.Kafka;
///
/// Kafka consumer. Polls messages from a Kafka topic and delegates to the processor pipeline.
/// Supports single-message and batch modes, with deferred-commit .
///
public sealed class KafkaConsumer : DrainableConsumer
{
private readonly KafkaEndpoint _endpoint;
private readonly KafkaEndpointOptions _options;
private IConsumer? _consumer;
// The cluster id, read on the first offer of consumed offsets (the consumer is connected by then) and kept.
private string? _cluster;
///
protected override IEndpoint ConsumerEndpoint => _endpoint;
///
protected override string ConsumerName => $"kafka:{_endpoint.TopicName}";
private long _processedCount;
/// Number of messages successfully processed. Thread-safe.
public long ProcessedCount => Interlocked.Read(ref _processedCount);
/// Creates a Kafka consumer.
public KafkaConsumer(KafkaEndpoint endpoint, IProcessor processor, KafkaEndpointOptions options)
: base(processor)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_options = options ?? throw new ArgumentNullException(nameof(options));
_headerFilter = endpoint.HeaderFilterStrategy;
}
private readonly redb.Route.Abstractions.IHeaderFilterStrategy _headerFilter;
///
protected override Task OnStarting(CancellationToken ct)
{
_supervisor = _endpoint.Supervise($"kafka:{_endpoint.TopicName} consumer", Logger);
try
{
_consumer = BuildConsumer();
}
catch
{
_endpoint.Unsupervise(_supervisor);
_supervisor = null;
throw;
}
// Log topic/partition metadata (leaders, replicas, ISR)
LogTopicMetadata();
return Task.CompletedTask;
}
///
/// Builds a client and subscribes it (or assigns its partition): at the start, and again after a fatal error, which
/// leaves a librdkafka instance unusable for good.
///
private IConsumer BuildConsumer()
{
var config = _options.BuildConsumerConfig(_endpoint.ResolvedFactory, _endpoint.Uri.RawParameters);
KafkaOptionParsers.WarnIfPasswordInClear(config, Logger, $"kafka consumer {_endpoint.TopicName}");
var consumer = new ConsumerBuilder(config)
.SetValueDeserializer(Deserializers.ByteArray)
.SetErrorHandler((_, e) =>
{
// Log-only for every error but one: a fatal error also surfaces as a ConsumeException on the poll
// loop's next Consume, which handles it there - recording here too made one fatal event count 2-3
// times. librdkafka reconnects to the brokers by itself; when none is left it reports
// _ALL_BROKERS_DOWN, the loss the supervisor shows in health. The _TRANSPORT of one broker of several
// is not a loss: the others still serve.
if (e.IsFatal)
Logger?.LogError("Kafka consumer fatal error: {Reason} (Code: {Code})", e.Reason, e.Code);
else if (e.Code == ErrorCode.Local_AllBrokersDown)
ReportLost(new KafkaException(e));
else
Logger?.LogWarning("Kafka consumer event: {Reason} (Code: {Code})", e.Reason, e.Code);
})
.SetPartitionsAssignedHandler((c, partitions) =>
{
Logger?.LogInformation("Kafka rebalance: assigned {Count} partitions: [{Partitions}]",
partitions.Count,
string.Join(", ", partitions.Select(p => $"{p.Topic}[{p.Partition}]")));
// seekTo rides the assignment, because right after Subscribe() the
// assignment is empty - the old post-Subscribe seek was a silent no-op for every
// group consumer.
// "Once" is per PARTITION, not per callback. The first callback
// can be empty (more consumers than partitions), and CooperativeSticky delivers
// partitions incrementally across several callbacks - a whole-consumer one-shot
// flag either burned on an empty list or seeked only the first increment. Each
// partition seeks exactly once, on ITS first assignment to this consumer; a
// partition re-assigned by a later rebalance must not replay.
var mapped = partitions
.Select(p => new TopicPartitionOffset(p, SeekOffsetFor(p) ?? Offset.Unset))
.ToList();
var seeked = mapped.Where(m => m.Offset != Offset.Unset).ToList();
if (seeked.Count > 0)
Logger?.LogInformation(
"Kafka consumer: seek to {SeekTo} on first assignment of [{Partitions}]",
_options.SeekTo,
string.Join(", ", seeked.Select(m => $"{m.Topic}[{m.Partition}]")));
return mapped;
})
.SetPartitionsRevokedHandler((c, partitions) =>
{
Logger?.LogInformation("Kafka rebalance: revoked {Count} partitions: [{Partitions}]",
partitions.Count,
string.Join(", ", partitions.Select(p => $"{p.Topic}[{p.Partition}]")));
// NO commit here. Commit(partitions) settles the consumer's
// POSITION, which advances on Consume - not on processing. Rebalance callbacks
// run inside Consume, so during batch collection this handler used to commit
// records that were consumed but never processed: the new owner started past
// them and the record was lost, contradicting the "will be redelivered" log.
// Every processed record is already settled inline (single: per message; batch:
// per partition at batch end), and no Consume happens between processing and
// that settle - so there is nothing legitimate left to commit on revoke.
// Anything consumed-but-unprocessed correctly replays: at-least-once.
})
.SetPartitionsLostHandler((_, partitions) =>
{
Logger?.LogWarning("Kafka rebalance: lost {Count} partitions: [{Partitions}] (involuntary)",
partitions.Count,
string.Join(", ", partitions.Select(p => $"{p.Topic}[{p.Partition}]")));
})
.Build();
try
{
// Subscribe or Assign
if (_options.PartitionNumber.HasValue)
{
var tp = new TopicPartition(_endpoint.TopicName, new Partition(_options.PartitionNumber.Value));
// The assigned handler does not fire for a manual Assign, so the seek offset goes
// directly into the assignment here.
var seek = SeekOffsetFor(tp);
if (seek is null)
consumer.Assign(new[] { tp });
else
consumer.Assign(new[] { new TopicPartitionOffset(tp, seek.Value) });
}
else
{
// librdkafka treats only a "^"-prefixed name as a regex. The flag used
// to be read by nothing, so the only working form was writing the "^" by hand.
var topic = _options.TopicIsPattern && !_endpoint.TopicName.StartsWith('^')
? "^" + _endpoint.TopicName
: _endpoint.TopicName;
consumer.Subscribe(topic);
}
}
catch (Exception ex)
{
Logger?.LogError(ex, "Kafka consumer failed to subscribe to topic {Topic}", _endpoint.TopicName);
consumer.Dispose();
throw;
}
return consumer;
}
///
protected override Task RunAsync(CancellationToken pollCt, CancellationToken processingCt)
{
_pollCt = pollCt;
return Task.Factory.StartNew(
() => PollLoop(pollCt, processingCt),
pollCt,
TaskCreationOptions.LongRunning,
TaskScheduler.Default).Unwrap();
}
///
protected override Task OnStopped()
{
// Under the gate: a probe that is asking the brokers on this client's handle ends (within ProbeTimeout) before
// the client is closed under it.
lock (_clientGate)
{
_consumer?.Close();
_consumer?.Dispose();
_consumer = null;
}
if (_supervisor is { } supervisor)
{
_endpoint.Unsupervise(supervisor);
_supervisor = null;
}
return Task.CompletedTask;
}
// ── Connection supervision ──
// librdkafka reconnects to the brokers by itself and has no "broker back" event, so the supervisor learns of the
// recovery from a probe on its schedule (a metadata request on this client's own connections, never a second
// client) or from the next record, whichever comes first. A fatal error is the one case the consumer rebuilds the
// client: librdkafka cannot use the instance again.
private ConnectionSupervisor? _supervisor;
private readonly object _clientGate = new();
private CancellationToken _pollCt;
private int _probing;
/// How long one probe waits for the brokers' answer.
internal static readonly TimeSpan ProbeTimeout = TimeSpan.FromSeconds(5);
///
/// Reports that no broker is left: the first report shows the loss in health and starts the probe that tells when
/// the brokers answer again. Called on librdkafka's thread, inside Consume: it only starts the probe.
///
private void ReportLost(KafkaException cause)
{
if (_supervisor is not { } supervisor || !supervisor.Lost(cause))
return;
if (Interlocked.CompareExchange(ref _probing, 1, 0) != 0)
return;
var stop = _pollCt;
_ = Task.Run(async () =>
{
try
{
await supervisor.ReconnectAsync(ProbeAsync, stop).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger?.LogDebug(ex, "Kafka consumer on topic {Topic}: the probe of the brokers ended", _endpoint.TopicName);
}
finally
{
Volatile.Write(ref _probing, 0);
}
}, CancellationToken.None);
}
/// Restores the connection on traffic: a record came, so the brokers are there. Cheap while connected.
private void ReportTraffic()
{
if (_supervisor is { State: not ConnectionState.Connected } supervisor)
supervisor.Restored();
}
///
/// One probe: asks the brokers for the metadata of the subscribed topic through this client's own handle, bounded by
/// . Asks nothing once the connection is back (a record restored it meanwhile).
///
private Task ProbeAsync(CancellationToken ct)
{
if (_supervisor is not { State: not ConnectionState.Connected } supervisor)
return Task.CompletedTask;
return supervisor.AttemptAsync(_ => Task.Run(() =>
{
lock (_clientGate)
{
var consumer = _consumer ?? throw new OperationCanceledException("the consumer is stopping");
using var admin = new DependentAdminClientBuilder(consumer.Handle).Build();
// A pattern subscription has no single topic to name: ask for one it was assigned, or for the brokers.
var topic = _options.TopicIsPattern ? consumer.Assignment.FirstOrDefault()?.Topic : _endpoint.TopicName;
var metadata = topic is null ? admin.GetMetadata(ProbeTimeout) : admin.GetMetadata(topic, ProbeTimeout);
if (metadata.Brokers.Count == 0)
throw new KafkaException(ErrorCode.Local_AllBrokersDown);
return true;
}
}, CancellationToken.None), static _ => { }, ct);
}
///
/// Replaces a client a fatal error ended: closes nothing of it (it cannot be used), builds and subscribes a new one,
/// and returns once the brokers answer it. The group then hands it the partitions and their committed offsets; what
/// was read but not committed before the error is delivered again (at least once).
///
private async Task RebuildAsync(CancellationToken ct)
{
lock (_clientGate)
{
var old = _consumer;
_consumer = null;
try { old?.Dispose(); }
catch (Exception ex) { Logger?.LogDebug(ex, "Kafka consumer: error disposing the client a fatal error ended"); }
_consumer = BuildConsumer();
}
await ProbeAsync(ct).ConfigureAwait(false);
}
// ── Poll loop ──
private async Task PollLoop(CancellationToken pollCt, CancellationToken processingCt)
{
while (!pollCt.IsCancellationRequested)
{
try
{
if (_options.Batch is { } batch)
await ProcessBatch(batch, pollCt, processingCt).ConfigureAwait(false);
else
await ProcessSingleMessage(pollCt, processingCt).ConfigureAwait(false);
}
catch (OperationCanceledException) { break; }
catch (KafkaException ex) when (ex.Error.IsFatal && _supervisor is { } supervisor)
{
// A fatal librdkafka error ends this client instance for good: retrying Consume on it is noise
//, and leaving the loop left the route Started and deaf. The supervisor shows the loss and
// builds a new client on its schedule; the route reads on once the brokers answer it.
Logger?.LogError(ex, "Kafka consumer on topic {Topic}: fatal client error; building a new client",
_endpoint.TopicName);
supervisor.Lost(ex);
if (!await supervisor.ReconnectAsync(RebuildAsync, pollCt).ConfigureAwait(false))
break;
}
catch (Exception ex)
{
// Transport-level failure (consume error) - invisible to the core's statistics wrappers, so the
// endpoint records it itself.
_endpoint.RecordError(ex);
Logger?.LogError(ex, "Error in Kafka poll loop for topic {Topic}", _endpoint.TopicName);
try { await Task.Delay(1000, pollCt).ConfigureAwait(false); }
catch (OperationCanceledException) { break; }
}
}
}
private async Task ProcessSingleMessage(CancellationToken pollCt, CancellationToken processingCt)
{
var result = _consumer!.Consume(pollCt);
if (result?.Message is null) return;
ReportTraffic();
using var span = StartReceiveSpan(result);
var exchange = CreateExchange(result);
IncrementInflight();
try
{
// The offset is advanced by this consumer after the unit of work ended well, not by the route
// transaction: the transaction owns the database and the outgoing sends.
var commitAction = new KafkaCommitAction(_consumer, result, Logger);
var offered = await OfferOffsetsAsync(exchange, commitAction).ConfigureAwait(false);
// ackMode=auto: the offset is committed on receipt, before the route runs (at-most-once).
if (_options.AckMode == AckMode.Auto)
commitAction.Commit();
try
{
try
{
await Processor.Process(exchange, processingCt).ConfigureAwait(false);
}
finally
{
offered?.Close();
}
exchange.ThrowIfUnhandledFailure();
}
catch (OperationCanceledException) when (processingCt.IsCancellationRequested)
{
throw; // shutdown, not a processing failure
}
catch (Exception ex)
{
// An unhandled processing failure used to escape to the poll loop, and
// the NEXT successful commit then covered this record's offset - a Kafka commit is
// a position, not a per-record mark - so the message was effectively lost with
// nothing but a log line.
MarkFailed(span, ex);
await HandleProcessingFailure(ex, [result], pollCt).ConfigureAwait(false);
return;
}
Interlocked.Increment(ref _processedCount);
// Auto-commit: settle the offset inline after successful processing — UNLESS a
// transactional route already committed it (commitAction.Committed), in which case
// the transaction owns the commit.
if (_options.AckMode == AckMode.Manual && !commitAction.Committed)
commitAction.Commit();
}
finally
{
await exchange.DisposeAsync().ConfigureAwait(false);
DecrementInflight();
}
}
///
/// The id of the cluster this consumer reads, for a transactional producer to tell whether it may take the offsets.
/// Read once, on the first offer: the consumer has just received a record, so the brokers are there. When it cannot
/// be read, this exchange's offsets are offered without it (a producer then leaves them to the consumer and says so),
/// and the next offer reads again.
///
private async Task ClusterIdAsync()
{
if (_cluster is not null)
return _cluster;
try
{
_cluster = await KafkaConsumedOffsets.ClusterIdOf(_consumer!.Handle, ClusterIdTimeout).ConfigureAwait(false);
}
catch (KafkaException ex)
{
Logger?.LogWarning(ex,
"Kafka consumer on topic {Topic} could not read its cluster id: the offsets of this record cannot ride in a " +
"Kafka transaction (at-least-once for it); it is read again on the next record", _endpoint.TopicName);
}
return _cluster;
}
private static readonly TimeSpan ClusterIdTimeout = TimeSpan.FromSeconds(10);
///
/// Offers the offsets this consumer is about to commit to a Kafka-transactional producer of the same cluster in the
/// route (): committed in its transaction, they leave with its sends. Only with
/// ackMode=manual — with ackMode=auto the offset is already committed on receipt.
///
private async Task OfferOffsetsAsync(IExchange exchange, KafkaCommitAction commitAction)
{
if (_options.AckMode != AckMode.Manual)
return null;
var offered = new KafkaConsumedOffsets(_consumer!, commitAction, await ClusterIdAsync().ConfigureAwait(false), exchange);
exchange.Properties[KafkaConsumedOffsets.PropertyKey] = offered;
return offered;
}
///
/// One place for the two failure policies. breakOnFirstError=true (Camel semantics):
/// seek every partition of the failed delivery back to its first offset, so the same
/// record(s) come again — the route retries instead of losing the message; the poll loop
/// then waits a beat so a permanently poisoned record does not become a hot spin. Default
/// false (also Camel's default): move on, but explicitly — the error lands in
/// endpoint statistics, and the log says the offset will be covered by the next commit.
///
private async Task HandleProcessingFailure(Exception ex, IReadOnlyList> failed, CancellationToken pollCt)
{
// Deliberately NOT RecordError here: in a routed consumer the processor chain is wrapped
// in the core's StatisticsProcessor, which has already recorded this escaping exception
// against the same endpoint - recording again would double-count.
// The connector records only what the core cannot see: transport-level poll errors.
if (_options.BreakOnFirstError)
{
foreach (var group in failed.GroupBy(r => r.TopicPartition))
{
var first = new TopicPartitionOffset(group.Key, group.Min(r => r.Offset.Value));
try
{
_consumer!.Seek(first);
}
catch (KafkaException seekEx)
{
// The partition may have been revoked between consume and seek. The offset is
// not committed, so the record is redelivered to whoever owns the partition now.
Logger?.LogWarning(seekEx,
"Kafka breakOnFirstError: seek back to {Tpo} failed (partition revoked?); " +
"the uncommitted record will be redelivered by the group", first);
}
}
Logger?.LogError(ex,
"Kafka message processing failed: topic={Topic}; breakOnFirstError=true - seeking back and retrying",
_endpoint.TopicName);
// Without a pause a permanently failing record retries in a tight loop.
try { await Task.Delay(1000, pollCt).ConfigureAwait(false); }
catch (OperationCanceledException) { }
return;
}
Logger?.LogError(ex,
"Kafka message processing failed: topic={Topic}; breakOnFirstError=false - moving on. " +
"The failed record's offset will be covered by the next successful commit " +
"(use a route error handler or breakOnFirstError=true to keep it)",
_endpoint.TopicName);
}
// ── Batch mode (the core contract, redb.Route.Batching) ──
private BatchCollector>? _collector;
private BatchDispatcher>? _dispatcher;
private KafkaBatchSettlement? _settlement;
///
/// One batch: collected by the core's collector over this consumer's poll, run through the route once by the core's
/// dispatcher, settled by . A batch half collected when the consumer stops is not
/// run: its offsets are not committed, so the group delivers its records again.
///
private async Task ProcessBatch(BatchOptions batch, CancellationToken pollCt, CancellationToken processingCt)
{
_settlement ??= new KafkaBatchSettlement(this);
_collector ??= new BatchCollector>(batch, Receive);
_dispatcher ??= new BatchDispatcher>(Processor, _settlement, ToMessage,
_endpoint.ScopeFactory, [KafkaHeaders.Topic, KafkaHeaders.Partition]);
var collected = await _collector.CollectAsync(pollCt).ConfigureAwait(false);
if (collected.Items.Count == 0)
return;
if (collected.Interrupted)
{
await _settlement.ReturnAsync(collected.Items, CancellationToken.None).ConfigureAwait(false);
return;
}
var records = collected.Items;
using var span = BatchDispatcher>.StartSpan(
(_endpoint.Component as ComponentBase)?.Context, $"{records[0].Topic} receive", "kafka",
_endpoint.Uri.NormalizedKey, records[0].Topic,
records.Select(r => RouteTelemetryExtensions.ExtractTraceContext(r.Message.Headers, ReadTraceHeader)),
records.Count);
span.Activity?.SetTag("messaging.kafka.consumer.group", _options.GroupId);
_settlement.PollCt = pollCt;
IncrementInflight();
try
{
var outcome = await _dispatcher.DispatchAsync(records, span, processingCt).ConfigureAwait(false);
if (outcome == BatchOutcome.Accepted)
Interlocked.Add(ref _processedCount, records.Count);
}
finally
{
DecrementInflight();
}
}
///
/// The transport's part of collection: waits up to for one record, in slices short enough to
/// notice the consumer's stop. A consume error that is not fatal is recorded and counts as no record.
///
private ValueTask Receive(List> into, int max, TimeSpan wait, CancellationToken ct)
{
var deadline = DateTime.UtcNow + wait;
while (true)
{
ct.ThrowIfCancellationRequested();
var remaining = deadline - DateTime.UtcNow;
if (remaining <= TimeSpan.Zero)
return ValueTask.FromResult(0);
try
{
var result = _consumer!.Consume(remaining < PollSlice ? remaining : PollSlice);
if (result?.Message is not null)
{
ReportTraffic();
into.Add(result);
return ValueTask.FromResult(1);
}
}
catch (ConsumeException ex)
{
Logger?.LogError(ex, "Kafka batch consume error: {Reason}", ex.Error.Reason);
// Fatal rethrows into the poll loop, which records it once.
if (ex.Error.IsFatal) throw;
_endpoint.RecordError(ex);
return ValueTask.FromResult(0);
}
}
}
private static readonly TimeSpan PollSlice = TimeSpan.FromMilliseconds(100);
/// One record into a message, built as a single record's: one topic gives one message shape in both modes.
private IMessage ToMessage(ConsumeResult result, IExchange batch)
{
var message = new Message();
Fill(message, result, batch);
return message;
}
///
/// Kafka's settlement of a batch: by position. The offsets of the batch are offered to the route (a transaction may
/// take them) and committed once after the route, the last offset of each partition covering the earlier ones; a
/// failed batch follows breakOnFirstError, the rule of a failed single record.
///
private sealed class KafkaBatchSettlement(KafkaConsumer owner) : IBatchSettlement>
{
private KafkaCommitAction? _commit;
/// The poll loop's stop token, for the pause after a failed batch under breakOnFirstError.
public CancellationToken PollCt { get; set; }
public async ValueTask BeforeRouteAsync(IExchange batch, IReadOnlyList> items,
CancellationToken ct)
{
// As in the single-record path: the consumer advances the offset, the transaction does not.
_commit = new KafkaCommitAction(owner._consumer!, items, owner.Logger);
var offered = await owner.OfferOffsetsAsync(batch, _commit).ConfigureAwait(false);
// ackMode=auto: the offsets are committed on receipt, before the route runs (at-most-once).
if (owner._options.AckMode == AckMode.Auto)
_commit.Commit();
return offered is null ? null : new CloseOffered(offered);
}
public ValueTask AcceptAsync(IExchange batch, IReadOnlyList> items, CancellationToken ct)
{
// Unless a transactional route already committed them.
if (owner._options.AckMode == AckMode.Manual && _commit is { Committed: false } commit)
commit.Commit();
return ValueTask.CompletedTask;
}
public async ValueTask RejectAsync(IExchange batch, IReadOnlyList> items,
Exception failure, CancellationToken ct)
=> await owner.HandleProcessingFailure(failure, items, PollCt).ConfigureAwait(false);
public ValueTask ReturnAsync(IReadOnlyList> items, CancellationToken ct)
{
// Nothing to send back: the offsets of these records are not committed, so the group delivers them again.
owner.Logger?.LogDebug("Kafka consumer {Consumer} stopped with {Count} record(s) of a batch not run; " +
"their offsets are not committed", owner.ConsumerName, items.Count);
return ValueTask.CompletedTask;
}
private sealed class CloseOffered(KafkaConsumedOffsets offered) : IDisposable
{
public void Dispose() => offered.Close();
}
}
// ── Tracing ──
///
/// Reads a trace field from Kafka headers the way the connector always has: the name compared without case, the
/// value decoded as UTF-8 (an invalid sequence decodes to replacement characters, which the W3C parser refuses).
///
private static readonly TraceHeaderReader ReadTraceHeader = static (headers, name) =>
headers?.FirstOrDefault(h => string.Equals(h.Key, name, StringComparison.OrdinalIgnoreCase)) is { } header
? Encoding.UTF8.GetString(header.GetValueBytes())
: null;
///
/// The receive span of one record: its parent is the sender's context from the record's headers, a root without
/// one (never the poll thread's ambient activity), and the sender's baggage comes back on it. The core contract
/// (), so it honours EnableTelemetry and carries
/// redb.route.endpoint.
///
private TransportSpan StartReceiveSpan(ConsumeResult result)
{
var span = StartSpan(result.Topic, result.Message.Headers, links: null);
if (span.Activity is { IsAllDataRequested: true } activity)
{
activity.SetTag("messaging.kafka.destination.partition", result.Partition.Value);
activity.SetTag("messaging.kafka.message.offset", result.Offset.Value);
if (!string.IsNullOrEmpty(result.Message.Key))
activity.SetTag("messaging.kafka.message.key", result.Message.Key);
}
return span;
}
///
/// Marks the receive span failed by the route. Only the consumer's own cancellation (its stop) is not a failure,
/// and it never gets here: the processing path rethrows it first. Any other cancellation is one, an HttpClient
/// timeout inside the route (a TaskCanceledException) for one.
///
private static void MarkFailed(TransportSpan span, Exception failure) => span.Activity.RecordFailure(failure);
private TransportSpan StartSpan(string topic, Headers? carrier, IEnumerable? links)
{
var span = RouteTelemetryExtensions.StartConsumerSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"{topic} receive", ActivityKind.Consumer,
"messaging.system", "kafka", _endpoint.Uri.NormalizedKey,
carrier, ReadTraceHeader,
destination: topic, operation: "receive", links: links);
span.Activity?.SetTag("messaging.kafka.consumer.group", _options.GroupId);
return span;
}
// ── Exchange creation ──
private Exchange CreateExchange(ConsumeResult result)
{
var message = new Message();
var exchange = Exchange.Create(message, _endpoint.ScopeFactory);
exchange.Pattern = ExchangePattern.InOnly;
Fill(message, result, exchange);
return exchange;
}
///
/// One record into a message: its headers as the header filter strategy lets them,
/// from its content-type header, and the CamelKafka* metadata. The single and the batch path both fill it here, so
/// one topic gives one message shape in single and batch mode alike.
///
private void Fill(Message message, ConsumeResult result, IExchange exchange)
{
message.Body = result.Message.Value;
// Kafka headers into the message, as the header filter strategy lets them
if (result.Message.Headers is not null)
{
foreach (var header in result.Message.Headers)
{
try
{
var headerValue = Encoding.UTF8.GetString(header.GetValueBytes());
// The content type is the record's, whatever the strategy says about the header itself.
if (string.Equals(header.Key, "content-type", StringComparison.OrdinalIgnoreCase))
message.ContentType = headerValue;
if (_headerFilter.FilterIncoming(header.Key, headerValue, exchange)) continue;
message.Headers[header.Key] = headerValue;
}
catch (Exception ex) { Logger?.LogDebug(ex, "Kafka: malformed header '{Key}'", header.Key); }
}
}
// Kafka metadata headers, Camel's names and types (KafkaRecordProcessor.setupExchangeMessage)
message.Headers[KafkaHeaders.Topic] = result.Topic;
message.Headers[KafkaHeaders.Partition] = result.Partition.Value;
message.Headers[KafkaHeaders.Offset] = result.Offset.Value;
if (result.Message.Headers is not null)
message.Headers[KafkaHeaders.Headers] = result.Message.Headers;
if (result.Message.Timestamp.Type != TimestampType.NotAvailable)
message.Headers[KafkaHeaders.Timestamp] = result.Message.Timestamp.UnixTimestampMs;
if (!string.IsNullOrEmpty(result.Message.Key))
message.Headers[KafkaHeaders.Key] = result.Message.Key;
}
// ── Seek ──
private readonly HashSet _seekedPartitions = [];
///
/// The seekTo position, handed out exactly once: the first assignment (or the manual Assign)
/// gets it, every later rebalance resumes from committed offsets like any group member.
///
///
/// The seekTo offset for , or null once it has already been
/// seeked. "On first start" is a per-partition promise: each partition seeks exactly once,
/// on its first assignment to this consumer - never again on a later rebalance.
///
private Offset? SeekOffsetFor(TopicPartition partition)
{
if (string.IsNullOrWhiteSpace(_options.SeekTo)) return null;
lock (_seekedPartitions)
{
if (!_seekedPartitions.Add(partition)) return null;
}
return KafkaOptionParsers.ParseSeekTo(_options.SeekTo);
}
private void LogTopicMetadata()
{
// Purely diagnostic - skip the round-trip entirely unless someone will see it.
if (Logger?.IsEnabled(LogLevel.Information) != true) return;
try
{
// The admin client carries the SAME security as the consumer. It used to
// be built from bare brokers, so on a SASL/SSL cluster every consumer start paid a 5s
// timeout for a log line that never appeared - while the factory's ready
// BuildAdminConfig() sat unused.
var adminConfig = _endpoint.ResolvedFactory?.BuildAdminConfig()
?? _options.BuildAdminConfig();
if (!string.IsNullOrWhiteSpace(_options.Brokers))
adminConfig.BootstrapServers = _options.Brokers;
using var adminClient = new AdminClientBuilder(adminConfig).Build();
var metadata = adminClient.GetMetadata(_endpoint.TopicName, TimeSpan.FromSeconds(5));
var topicMeta = metadata.Topics.FirstOrDefault(t => t.Topic == _endpoint.TopicName);
if (topicMeta is null) return;
// One line per consumer start; per-partition leader/ISR detail is Debug - a
// 100-partition topic used to print a hundred Information lines per start.
Logger?.LogInformation("Kafka topic {Topic}: {PartitionCount} partitions, {BrokerCount} brokers",
_endpoint.TopicName, topicMeta.Partitions.Count, metadata.Brokers.Count);
if (Logger?.IsEnabled(LogLevel.Debug) == true)
{
foreach (var p in topicMeta.Partitions)
{
var leader = metadata.Brokers.FirstOrDefault(b => b.BrokerId == p.Leader);
Logger?.LogDebug(
" Partition [{PartitionId}]: leader=broker#{LeaderId} ({Host}:{Port}), replicas=[{Replicas}], ISR=[{ISR}]",
p.PartitionId, p.Leader,
leader?.Host ?? "?", leader?.Port ?? 0,
string.Join(", ", p.Replicas),
string.Join(", ", p.InSyncReplicas));
}
}
}
catch (Exception ex)
{
Logger?.LogDebug(ex, "Kafka: could not fetch topic metadata for {Topic}", _endpoint.TopicName);
}
}
}
///
/// The position a consumer commits for one exchange (a record, or every partition of a batch). The consumer commits it
/// inline, on receipt with ackMode=auto or after the route with ackMode=manual, unless a Kafka transaction already did
/// (, through ). It is not a transacted action: a route's
/// transaction never commits or rolls it back.
///
internal sealed class KafkaCommitAction
{
private readonly IConsumer _consumer;
private readonly ConsumeResult _result;
private readonly IReadOnlyList? _batchOffsets;
private readonly ILogger? _logger;
private int _committed;
public KafkaCommitAction(IConsumer consumer, ConsumeResult result, ILogger? logger)
{
_consumer = consumer;
_result = result;
_logger = logger;
}
///
/// Batch settle: the position of EVERY partition the batch touched. The single
/// "commit the last result" used to settle one partition only, leaving the rest to the
/// revoked-handler at clean shutdown — a kill -9 replayed far more than needed.
/// A committed position is the NEXT offset to read, hence the +1.
///
public KafkaCommitAction(IConsumer consumer,
IReadOnlyList> batch, ILogger? logger)
{
_consumer = consumer;
_result = batch[^1];
_batchOffsets = batch
.GroupBy(r => r.TopicPartition)
.Select(g => new TopicPartitionOffset(g.Key, g.Max(r => r.Offset.Value) + 1))
.ToList();
_logger = logger;
}
/// True once the offset has been committed (by a transactional route or inline auto-commit).
public bool Committed => Volatile.Read(ref _committed) == 1;
/// The positions this action commits: the next offset to read, per partition.
public IReadOnlyList NextOffsets =>
_batchOffsets ?? [new TopicPartitionOffset(_result.TopicPartition, _result.Offset.Value + 1)];
/// A Kafka transaction committed the offsets (SendOffsetsToTransaction): nothing is left to commit.
public void MarkCommitted() => Interlocked.Exchange(ref _committed, 1);
///
/// Commits the position, once. Synchronous: librdkafka's commit waits for the group coordinator and takes no
/// cancellation, so a stop waits for a commit already under way (bounded by the client's own timeouts).
///
public void Commit()
{
// Once: after a Kafka transaction committed the offsets (MarkCommitted), the inline commit is skipped.
if (Interlocked.Exchange(ref _committed, 1) != 0)
return;
if (_batchOffsets is not null)
{
_consumer.Commit(_batchOffsets);
_logger?.LogDebug("Kafka batch offsets committed: [{Offsets}]",
string.Join(", ", _batchOffsets.Select(o => $"{o.Topic}[{o.Partition.Value}]@{o.Offset.Value}")));
}
else
{
_consumer.Commit(_result);
_logger?.LogDebug("Kafka offset committed: topic={Topic}, partition={Partition}, offset={Offset}",
_result.Topic, _result.Partition.Value, _result.Offset.Value);
}
}
}
Path: redb-route/redb.Route.Kafka/KafkaEndpoint.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/KafkaEndpoint.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Kafka;
///
/// Kafka endpoint. The topic name comes from .
/// Supports both producing and consuming with full transactional semantics.
///
public sealed class KafkaEndpoint : EndpointBase
{
/// Kafka topic name (from URI path).
public string TopicName { get; }
/// Resolved connection factory from the registry (null if not configured).
internal KafkaConnectionFactory? ResolvedFactory { get; }
/// Creates a Kafka endpoint. The factory is resolved by the component
/// BEFORE options validation (it may be the only source of the brokers).
public KafkaEndpoint(EndpointUri uri, KafkaComponent component, KafkaEndpointOptions options,
KafkaConnectionFactory? resolvedFactory = null)
: base(uri, component, options)
{
TopicName = uri.Path;
ResolvedFactory = resolvedFactory;
_headerFilter = new redb.Route.Core.EndpointHeaderFilter(this, options.HeaderFilterStrategy);
}
private readonly redb.Route.Core.EndpointHeaderFilter _headerFilter;
///
/// The header filter strategy of this endpoint: the one headerFilterStrategy=#name names, or
/// . A name the registry does not hold fails when the producer or
/// consumer is built.
///
internal redb.Route.Abstractions.IHeaderFilterStrategy HeaderFilterStrategy => _headerFilter.Or(KafkaHeaderFilterStrategy.Default);
///
public override IProducer CreateProducer()
{
// One name for each thing: a producer's partition is Camel's partitionKey; partitionNumber is a consumer's.
if (Options.PartitionNumber.HasValue)
throw new ArgumentException(
"Kafka producer: 'partitionNumber' names the partition a consumer reads. The partition a producer sends to " +
$"is 'partitionKey' (Apache Camel's name), or the {KafkaHeaders.PartitionKey} header per message.",
nameof(KafkaEndpointOptions.PartitionNumber));
return new KafkaProducer(this, Options);
}
///
public override IConsumer CreateConsumer(IProcessor processor)
{
if (Options.PartitionKey.HasValue)
throw new ArgumentException(
"Kafka consumer: 'partitionKey' names the partition a producer sends to. The partition a consumer reads is " +
"'partitionNumber'.", nameof(KafkaEndpointOptions.PartitionKey));
if (string.IsNullOrWhiteSpace(Options.GroupId))
throw new InvalidOperationException(
$"The 'groupId' parameter is required for Kafka consumer on topic '{TopicName}'.");
return new KafkaConsumer(this, processor, Options);
}
}
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);
}
}
Path: redb-route/redb.Route.Kafka/KafkaHeaderFilterStrategy.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/KafkaHeaderFilterStrategy.cs
----
using redb.Route.Abstractions;
namespace redb.Route.Kafka;
///
/// The default of the Kafka component, Apache Camel's
/// KafkaHeaderFilterStrategy: a header whose name starts with Camel, camel, org.apache.camel.
/// or kafka. is neither sent on a record nor taken from one. An endpoint's headerFilterStrategy=#name
/// replaces it; derive from it to add to it.
///
/// So the component's own (all CamelKafka*) never reach the next hop, and a record
/// that carries such a name cannot set them: the consumer sets them itself, whatever the strategy says. A sent header goes
/// as its text, a null value as an empty one. A record's content-type header is the exchange's content type either
/// way (the producer writes it from the exchange, the consumer reads it into the exchange).
///
///
public class KafkaHeaderFilterStrategy : IHeaderFilterStrategy
{
/// The default strategy of a Kafka endpoint.
public static KafkaHeaderFilterStrategy Default { get; } = new();
/// The prefixes Camel's strategy filters, in and out: its own (CAMEL_FILTER_STARTS_WITH) and kafka..
private static readonly string[] FilteredPrefixes = ["Camel", "camel", "org.apache.camel.", "kafka."];
/// Whether starts with one of the prefixes Camel's strategy filters.
protected static bool IsFiltered(string name)
{
foreach (var prefix in FilteredPrefixes)
if (name.StartsWith(prefix, StringComparison.Ordinal))
return true;
return false;
}
///
public virtual bool FilterOutgoing(string name, object? value, IExchange exchange) => IsFiltered(name);
///
public virtual bool FilterIncoming(string name, object? value, IExchange exchange) => IsFiltered(name);
}
Path: redb-route/redb.Route.Kafka/KafkaHeaders.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/KafkaHeaders.cs
----
namespace redb.Route.Kafka;
///
/// The headers of the Kafka component, with Apache Camel's names and types (KafkaConstants of camel-kafka), so a
/// route written for Camel reads and sets them unchanged. None of them goes on the wire:
/// keeps every Camel* header off a sent record, as Camel's does.
///
public static class KafkaHeaders
{
// ── Set by the consumer on every record (Camel's KafkaRecordProcessor.setupExchangeMessage) ──
/// The topic of the consumed record (KafkaConstants.TOPIC), a .
public const string Topic = "CamelKafkaTopic";
/// The partition the record was stored in (KafkaConstants.PARTITION), an .
public const string Partition = "CamelKafkaPartition";
/// The offset of the record in its partition (KafkaConstants.OFFSET), a .
public const string Offset = "CamelKafkaOffset";
///
/// The record's timestamp (KafkaConstants.TIMESTAMP), a of milliseconds since the Unix epoch,
/// as Kafka and Camel give it. Not set when the record carries none.
///
public const string Timestamp = "CamelKafkaTimestamp";
///
/// The record's headers as Kafka gave them (KafkaConstants.HEADERS): the Confluent.Kafka.Headers of the
/// record, with their raw bytes. The same headers, as text and as the strategy lets them in, are message headers too.
///
public const string Headers = "CamelKafkaHeaders";
// ── Set by the consumer, read by the producer ──
///
/// The key of the record (KafkaConstants.KEY), a . Consumer: the key of the consumed record,
/// when it has one. Producer: the key of the sent record when the endpoint's key option is not set, which takes
/// precedence, as in Camel; a route passing records on keeps their keys.
///
public const string Key = "CamelKafkaKey";
// ── Read by the producer ──
///
/// The partition a sent record goes to, per message (KafkaConstants.PARTITION_KEY): an integer, or a
/// whole-number text. The endpoint's partitionKey option takes precedence over it, as in Camel.
///
public const string PartitionKey = "CamelKafkaPartitionKey";
///
/// The topic a sent record goes to instead of the endpoint's, per message (KafkaConstants.OVERRIDE_TOPIC): a
/// . The producer removes it from the message, so it does not travel further.
///
public const string OverrideTopic = "CamelKafkaOverrideTopic";
///
/// The timestamp of a sent record, per message (KafkaConstants.OVERRIDE_TIMESTAMP): milliseconds since the Unix
/// epoch as a (or a whole-number text), or a or .
/// The producer removes it from the message.
///
public const string OverrideTimestamp = "CamelKafkaOverrideTimestamp";
// ── Set by the producer ──
///
/// With recordMetadata=true, the metadata of what the producer sent (KafkaConstants.KAFKA_RECORD_META): a
/// List<KafkaRecordMetadata>, one entry per sent record (a list body gives one per element), as Camel's
/// list of RecordMetadata.
///
public const string RecordMeta = "CamelKafkaRecordMeta";
}
///
/// The metadata of one sent record, the fields of Kafka's RecordMetadata that Camel puts in
/// : its topic, partition, offset and timestamp (milliseconds since the Unix epoch,
/// the record's timestamp as the broker stored it).
///
public sealed record KafkaRecordMetadata(string Topic, int Partition, long Offset, long Timestamp);
Path: redb-route/redb.Route.Kafka/KafkaOptionParsers.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/KafkaOptionParsers.cs
----
using Confluent.Kafka;
using Microsoft.Extensions.Logging;
namespace redb.Route.Kafka;
///
/// Strict parsers for enum-valued Kafka options. Every parse either succeeds or throws an
/// naming the option and the valid values — a typo must never
/// fall back to a default. The worst case was securityProtocol: an unparsed value used to
/// be silently skipped, yielding a plaintext connection with no credentials; and the canonical
/// Kafka spellings (SASL_SSL, SCRAM-SHA-256) fell into the same hole, because
/// Enum.TryParse knows only the C# names. Separators are normalized away, so both families of
/// spellings work.
///
internal static class KafkaOptionParsers
{
/// Case-insensitive parse ignoring '_' and '-', so C# names and Kafka canon both work.
internal static TEnum ParseOrThrow(string value, string optionName) where TEnum : struct, Enum
{
var normalized = value.Trim().Replace("_", "").Replace("-", "");
if (normalized.Length > 0 && Enum.TryParse(normalized, ignoreCase: true, out var parsed)
&& Enum.IsDefined(parsed))
return parsed;
throw new ArgumentException(
$"Unknown value '{value}' for '{optionName}'. Valid values: {string.Join(", ", Enum.GetNames())} " +
"(case-insensitive; '_' and '-' separators are accepted).");
}
/// Acks with the numeric synonyms Kafka users write (0 / 1 / -1).
internal static Acks ParseAcks(string value) => value.Trim().ToLowerInvariant() switch
{
"none" or "0" => Acks.None,
"leader" or "1" => Acks.Leader,
"all" or "-1" => Acks.All,
_ => throw new ArgumentException(
$"Unknown value '{value}' for 'acks'. Valid values: None|0, Leader|1, All|-1."),
};
/// Consumer seek position; anything but beginning/end is a config error.
internal static Offset ParseSeekTo(string value) => value.Trim().ToLowerInvariant() switch
{
"beginning" => Offset.Beginning,
"end" => Offset.End,
_ => throw new ArgumentException(
$"Unknown value '{value}' for 'seekTo'. Valid values: beginning, end."),
};
///
/// SASL credential rule: the password-carrying mechanisms must arrive with credentials —
/// a mechanism without them used to produce an anonymous connection. Gssapi and OAuthBearer
/// authenticate through other channels and are exempt.
///
///
/// sslEndpointIdentificationAlgorithm: https verifies the broker's hostname against its certificate,
/// none (or empty) does not. Anything else used to mean https, so none itself turned the check
/// on; now it is refused by name.
///
internal static SslEndpointIdentificationAlgorithm ParseEndpointIdentification(string value) =>
value.Trim().ToLowerInvariant() switch
{
"https" => SslEndpointIdentificationAlgorithm.Https,
"none" or "" => SslEndpointIdentificationAlgorithm.None,
_ => throw new ArgumentException(
$"sslEndpointIdentificationAlgorithm='{value}' is not a value: use 'https' (verify the broker's " +
"hostname against its certificate) or 'none'."),
};
///
/// SASL PLAIN over SASL_PLAINTEXT sends the password as it is, unencrypted. Legal (a closed network, a test
/// stand), so it is said, not refused.
///
internal static void WarnIfPasswordInClear(ClientConfig config, ILogger? logger, string clientName)
{
if (config.SecurityProtocol == SecurityProtocol.SaslPlaintext && config.SaslMechanism == SaslMechanism.Plain)
logger?.LogWarning(
"{Client}: SASL PLAIN over SASL_PLAINTEXT sends the password unencrypted. Use securityProtocol=SaslSsl, " +
"or a SCRAM mechanism.", clientName);
}
///
/// Refuses the librdkafka properties that would break a guarantee the connector gives, whichever of the two
/// additionalProperties (the endpoint's or the connection factory's, both applied last) carries them:
/// transactional.id (transactional mode with nobody opening transactions), enable.auto.commit=true
/// (a background timer commits records read but not yet processed, under ackMode), and, for an idempotent or
/// transactional producer (transacted=true, transactionalIdPrefix), enable.idempotence or
/// acks contradicting it. A value that agrees with the connector is left alone.
///
internal static void RefuseReservedProperties(
IEnumerable> properties, string source, bool idempotentProducer)
{
foreach (var (key, raw) in properties)
{
var name = key.Trim().ToLowerInvariant();
var value = (raw ?? "").Trim().ToLowerInvariant();
if (name == "transactional.id")
throw new ArgumentException(
$"'transactional.id' in {source} puts librdkafka into transactional mode without the connector " +
"opening transactions, and every send fails with 'Erroneous state'. Use transactionalIdPrefix.");
if (name == "enable.auto.commit" && value != "false")
throw new ArgumentException(
$"'enable.auto.commit={raw}' in {source} lets librdkafka commit, on a timer, records read but not " +
"yet processed: a crash loses them, whatever ackMode says. The connector commits itself; choose " +
"when with ackMode (manual or auto).");
if (idempotentProducer && name == "enable.idempotence" && value != "true")
throw new ArgumentException(
$"'enable.idempotence={raw}' in {source} contradicts transacted=true / transactionalIdPrefix, " +
"which make the producer idempotent.");
if (idempotentProducer && name == "acks" && value is not ("all" or "-1"))
throw new ArgumentException(
$"'acks={raw}' in {source} contradicts transacted=true / transactionalIdPrefix, which require " +
"acks=all.");
}
}
internal static void RequireSaslCredentials(SaslMechanism mechanism, string? username, string? password)
{
if (mechanism is SaslMechanism.Gssapi or SaslMechanism.OAuthBearer) return;
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
throw new ArgumentException(
$"saslMechanism={mechanism} requires 'saslUsername' and 'saslPassword' " +
"(inline or via a named connectionFactory).");
}
}
Path: redb-route/redb.Route.Kafka/KafkaPartitions.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/KafkaPartitions.cs
----
using System.Globalization;
using Confluent.Kafka;
namespace redb.Route.Kafka;
///
/// The partition of a sent record: reading it from the header, and producing to
/// it. A value that is not a partition number, and a partition the topic does not have, are refused with words that name
/// them; nothing goes to partition 0, or to the partitioner, in their place.
///
internal static class KafkaPartitions
{
///
/// The partition a header value names: an integer type, or a whole-number text read without culture. A negative
/// number, a fraction, an empty or other text is refused.
///
public static int FromHeader(object? value)
{
long? number = value switch
{
int i => i,
long l => l,
short s => s,
byte b => b,
sbyte sb => sb,
ushort us => us,
uint ui => ui,
string text when long.TryParse(text.Trim(), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var parsed)
=> parsed,
_ => null,
};
if (number is null or < 0 or > int.MaxValue)
throw new ArgumentException(
$"The {KafkaHeaders.PartitionKey} header must be a partition number, 0 or more; it is " +
$"{(value is null ? "null" : $"'{value}' ({value.GetType().Name})")}. Nothing was sent.",
KafkaHeaders.PartitionKey);
return (int)number.Value;
}
/// The topic a value names: a non-empty text; anything else is refused.
public static string TopicFromHeader(object value)
=> value is string { Length: > 0 } topic && !string.IsNullOrWhiteSpace(topic)
? topic
: throw new ArgumentException(
$"The {KafkaHeaders.OverrideTopic} header must be a topic name; it is '{value}' ({value.GetType().Name}). Nothing was sent.",
KafkaHeaders.OverrideTopic);
///
/// The record timestamp a value names, in milliseconds since the Unix epoch
/// (Camel converts it to a Long): an integer, a whole-number text, a or a
/// (a local or unspecified one read as local time). A negative number or anything else is refused.
///
public static long TimestampFromHeader(object value)
{
long? ms = value switch
{
long l => l,
int i => i,
string text when long.TryParse(text.Trim(), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var parsed) => parsed,
DateTimeOffset dto => dto.ToUnixTimeMilliseconds(),
DateTime dt => new DateTimeOffset(dt.Kind == DateTimeKind.Utc ? dt : DateTime.SpecifyKind(dt, DateTimeKind.Local)).ToUnixTimeMilliseconds(),
_ => null,
};
if (ms is null or < 0)
throw new ArgumentException(
$"The {KafkaHeaders.OverrideTimestamp} header must be milliseconds since the Unix epoch or a date; it is '{value}' " +
$"({value.GetType().Name}). Nothing was sent.", KafkaHeaders.OverrideTimestamp);
return ms.Value;
}
///
/// Produces to of , or to the topic
/// (Kafka's partitioner, by the key) when there is no partition. A partition the topic does not have is refused by the
/// client; the refusal is rethrown naming the topic and the partition.
///
public static async Task> ProduceAsync(IProducer producer, string topic,
Message message, int? partition, CancellationToken ct)
{
if (partition is not { } p)
return await producer.ProduceAsync(topic, message, ct).ConfigureAwait(false);
try
{
return await producer.ProduceAsync(new TopicPartition(topic, new Partition(p)), message, ct).ConfigureAwait(false);
}
catch (ProduceException ex) when (ex.Error.Code == ErrorCode.Local_UnknownPartition)
{
throw new InvalidOperationException(
$"Kafka topic '{topic}' has no partition {p}: the record was not sent. Check {KafkaHeaders.PartitionKey} " +
"or the endpoint's partitionKey against the topic's partition count.", ex);
}
}
}
Path: redb-route/redb.Route.Kafka/KafkaProducer.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/KafkaProducer.cs
----
using System.Collections;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
using Confluent.Kafka;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Transactions;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.Kafka;
///
/// Kafka producer. Sends messages to a Kafka topic with support for transactional
/// deferred-commit via , and for Kafka transactions when
/// is set.
///
public sealed class KafkaProducer : ConnectableProducer
{
///
/// How long InitTransactions and SendOffsetsToTransaction may take before they fail. Commit and abort take no
/// timeout of ours (see CommitWithRetries).
///
private static readonly TimeSpan TransactionTimeout = TimeSpan.FromSeconds(30);
private static int s_transactionalProducers;
private readonly KafkaEndpoint _endpoint;
private readonly KafkaEndpointOptions _options;
private IProducer? _producer;
// Kafka transactions: one open transaction per producer at a time, so the transactions take turns; the id is the
// producer's own and survives a rebuild after a fatal error (InitTransactions with it fences the dead incarnation
// and aborts what it left open, instead of leaving that to block read_committed readers until it times out).
private readonly SemaphoreSlim _transactionTurn = new(1, 1);
private readonly string _batchKey = $"kafka-tx-{Guid.NewGuid():N}";
private string? _transactionalId;
private string _cluster = "";
private bool _rebuild;
private int _warnedForeignOffsets;
private int _warnedInheritedOffsets;
private int _warnedClosedOffsets;
/// Creates a Kafka producer.
public KafkaProducer(KafkaEndpoint endpoint, KafkaEndpointOptions options)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_options = options ?? throw new ArgumentNullException(nameof(options));
_headerFilter = endpoint.HeaderFilterStrategy;
}
private readonly redb.Route.Abstractions.IHeaderFilterStrategy _headerFilter;
///
protected override IEndpoint ProducerEndpoint => _endpoint;
///
protected override string ProducerName => $"kafka:{_endpoint.TopicName}";
///
protected override async Task ConnectAsync(CancellationToken ct)
{
var config = _options.BuildProducerConfig(_endpoint.ResolvedFactory, _endpoint.Uri.RawParameters);
KafkaOptionParsers.WarnIfPasswordInClear(config, Logger, ProducerName);
if (_options.TransactionalIdPrefix is { } prefix)
{
// An id of this producer's own: nodes deploying the same configuration, and two producers of one process,
// would fence each other with a shared one.
_transactionalId ??= $"{prefix}-{Environment.MachineName}-{Environment.ProcessId}-" +
Interlocked.Increment(ref s_transactionalProducers);
config.TransactionalId = _transactionalId;
}
_producer = new ProducerBuilder(config)
.SetValueSerializer(Serializers.ByteArray)
.SetErrorHandler((_, e) =>
Logger?.LogError("Kafka producer error: {Reason} (Code: {Code})", e.Reason, e.Code))
.Build();
if (_transactionalId is not null)
{
var producer = _producer;
await Task.Run(() => producer.InitTransactions(TransactionTimeout), ct).ConfigureAwait(false);
// The cluster whose consumed offsets this producer's transactions may take; the broker has just answered.
_cluster = await KafkaConsumedOffsets.ClusterIdOf(producer.Handle, TransactionTimeout).ConfigureAwait(false);
Logger?.LogInformation(
"Kafka producer uses transactions: topic={Topic}, transactional.id={TransactionalId}, cluster={Cluster}",
_endpoint.TopicName, _transactionalId, _cluster);
}
}
///
protected override Task DisconnectAsync(CancellationToken ct)
{
if (_producer is not null)
{
Logger?.LogInformation("Kafka producer flushing: topic={Topic}", _endpoint.TopicName);
_producer.Flush(TimeSpan.FromSeconds(30));
_producer.Dispose();
_producer = null;
}
return Task.CompletedTask;
}
///
public override async Task Process(IExchange exchange, CancellationToken ct = default)
{
EnsureStarted();
using var activity = RouteTelemetryExtensions.StartTransportSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"{_endpoint.TopicName} publish", ActivityKind.Producer,
"messaging.system", "kafka", _endpoint.Uri.NormalizedKey,
destination: _endpoint.TopicName, operation: "publish");
// recordMetadata: a fresh CamelKafkaRecordMeta list per call, as Camel sets one per send (filled as records go).
if (_options.RecordMetadata)
exchange.In.Headers[KafkaHeaders.RecordMeta] = new List();
// A list is sent element by element, each its own record (camel-kafka, useIterator): a list of IMessage with
// each element's own body, headers and key, a plain list with each value as the body under the exchange's
// headers and key.
var body = exchange.In.Body;
IEnumerable? elements = (IEnumerable?)ListBody.Messages(body) ?? (ListBody.IsPlainList(body) ? (IEnumerable)body! : null);
if (elements is not null)
{
try
{
await SendListAsync(exchange, elements, activity, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
activity.RecordFailure(ex);
throw;
}
return;
}
var message = PrepareMessage(exchange);
var target = ResolveTarget(exchange, message);
// The context of this send, over a traceparent copied from a consumed record's headers: that one names the
// previous hop.
RouteTelemetryExtensions.InjectTraceContext(activity, message.Headers, WriteTraceHeader);
try
{
await SendAsync(exchange, message, target, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
// Only a cancellation by the caller's own token is not a failure; any other (a client timeout) is.
// A send deferred to the block's commit fails later, outside this span; the route's span shows that one.
activity.RecordFailure(ex);
throw;
}
}
///
/// Writes a trace field to Kafka headers as UTF-8, replacing every value already there under that name in any case:
/// the consumer reads the name without case and takes the first, so a Traceparent bridged from an HTTP caller
/// would otherwise win over this send's traceparent. compares the name exactly.
///
private static readonly TraceHeaderWriter WriteTraceHeader = static (headers, name, value) =>
{
foreach (var key in headers.Select(h => h.Key)
.Where(k => string.Equals(k, name, StringComparison.OrdinalIgnoreCase))
.Distinct(StringComparer.Ordinal)
.ToList())
headers.Remove(key);
headers.Add(name, Encoding.UTF8.GetBytes(value));
};
///
/// Sends every element of a list body as its own record, in order, through the single-record send of
/// : inside a .Transacted() block they join its Kafka transaction (with the consumed
/// offsets), outside one each is sent at once. A failure stops the list; the records already sent stay, as in
/// camel-kafka. With recordMetadata=true the exchange's gets one entry
/// per record.
///
///
/// The topic and timestamp follow camel-kafka's createRecordIterable: the exchange's
/// is read and removed once, before the first element, and is the topic of
/// every element that does not name its own; an element's own override topic and timestamp win
/// and are removed from that element. The exchange's is not read for a
/// list, as in Camel, and stays on the exchange.
///
private async Task SendListAsync(IExchange exchange, IEnumerable elements, Activity? activity, CancellationToken ct)
{
var listTopic = TakeOverrideTopic(exchange.In) ?? _endpoint.TopicName;
var count = 0;
foreach (var element in elements)
{
string? ownTopic = null;
long? ownTimestamp = null;
if (element is IMessage own)
{
ownTopic = TakeOverrideTopic(own);
if (own.Headers.Remove(KafkaHeaders.OverrideTimestamp, out var stamp) && stamp is not null)
ownTimestamp = KafkaPartitions.TimestampFromHeader(stamp);
}
var source = ListBody.ElementExchange(exchange, element);
try
{
// Each element's own partition: an IMessage element's header, a plain value the exchange's (ElementExchange).
var message = PrepareMessage(source);
if (ownTimestamp is { } ms)
message.Timestamp = new Timestamp(ms, TimestampType.CreateTime);
var target = new KafkaTarget(ownTopic ?? listTopic, ResolvePartition(source));
RouteTelemetryExtensions.InjectTraceContext(activity, message.Headers, WriteTraceHeader);
await SendAsync(exchange, message, target, ct).ConfigureAwait(false);
}
finally
{
if (source is IAsyncDisposable disposable)
await disposable.DisposeAsync().ConfigureAwait(false);
}
count++;
}
activity?.SetTag("messaging.batch.message_count", count);
}
private async Task SendAsync(IExchange exchange, Message message, KafkaTarget target, CancellationToken ct)
{
if (_transactionalId is not null)
{
var send = new KafkaTransactionalSend(KafkaSendAction.CloneMessage(message), target, exchange);
if (TransactedActions.Defers(exchange, _options.Transacted))
{
// The block's sends through this producer commit as one Kafka transaction when the block commits,
// with the consumed offset when the route started from a Kafka consumer of this cluster.
TransactedActions.JoinBatch(exchange, _batchKey,
() => new KafkaTransactionBatch(this, OffsetsOfThisCluster(exchange)),
ProducerName)
.Add(send);
}
else
{
// A transactional producer sends nothing outside a transaction: this send is a transaction of its own.
await CommitTransactionAsync([send], offsets: null, ct).ConfigureAwait(false);
}
return;
}
if (TransactedActions.Defers(exchange, _options.Transacted))
{
// Deferred transactional send — actual publish happens on commit
var action = new KafkaSendAction(_producer, _endpoint, message,
target, _options.RecordMetadata, exchange, Logger);
TransactedActions.Register(exchange, $"kafka-send-{Guid.NewGuid():N}", action, ProducerName);
}
else
{
// Immediate send
DeliveryResult result;
try
{
result = await ProduceAsync(_producer!, message, target, ct).ConfigureAwait(false);
}
catch (ProduceException ex)
{
Logger?.LogError(ex, "Kafka produce failed: topic={Topic}, partition={Partition}, error={Error}",
target.Topic, target.Partition, ex.Error.Reason);
throw;
}
Logger?.LogDebug("Kafka message sent: topic={Topic}, partition={Partition}, offset={Offset}",
result.Topic, result.Partition.Value, result.Offset.Value);
// Wire-level bytes are the connector's to record: the core's ToProcessor counts
// MessagesOut/Errors for a routed producer but has no idea of payload sizes.
_endpoint.RecordBytesOut(message.Value.Length);
if (_options.RecordMetadata)
AddDeliveryMetadata(exchange, result);
}
}
// ── Kafka transactions ──
///
/// Commits as one Kafka transaction: begin, produce each in order, add the consumed offsets
/// when given and still claimable, commit. Any failure aborts the transaction — nothing becomes visible to
/// read_committed readers, the offsets stay uncommitted — and propagates. The producer's transactions take turns.
///
internal async Task CommitTransactionAsync(
IReadOnlyList sends, KafkaConsumedOffsets? offsets, CancellationToken ct)
{
await _transactionTurn.WaitAsync(ct).ConfigureAwait(false);
try
{
var producer = await TransactionalProducerAsync(ct).ConfigureAwait(false);
var claimed = offsets?.TryClaim() == true;
if (offsets is { IsClosed: true })
WarnOnce(ref _warnedClosedOffsets,
"Kafka transaction on topic {Topic} commits after the route returned to its Kafka consumer (an " +
"asynchronous step inside the .Transacted() block?): the consumed offsets are not in the transaction, " +
"the consumer settled them itself, and the route is not exactly-once. Keep the block synchronous.",
_endpoint.TopicName);
var delivered = new DeliveryResult[sends.Count];
try
{
producer.BeginTransaction();
for (var i = 0; i < sends.Count; i++)
delivered[i] = await ProduceAsync(producer, sends[i].Message, sends[i].Target, ct).ConfigureAwait(false);
if (claimed)
producer.SendOffsetsToTransaction(offsets!.Offsets, offsets.GroupMetadata, TransactionTimeout);
}
catch (Exception ex)
{
if (claimed)
offsets!.Release();
Abort(producer, ex);
throw;
}
try
{
CommitWithRetries(producer);
}
catch (KafkaRetriableException ex)
{
// The commit may have reached the coordinator and succeeded: aborting now is not the transaction's
// undo, only a call librdkafka refuses. The next incarnation's InitTransactions settles it (the
// coordinator completes a prepared commit, aborts an open transaction).
if (claimed)
offsets!.Release();
_rebuild = true;
Logger?.LogError(ex,
"Kafka transaction of producer {TransactionalId} on topic {Topic}: the commit did not answer, so its " +
"outcome is unknown. The producer is rebuilt before the next transaction; if this one did commit, a " +
"redelivery of the exchange writes its records again.", _transactionalId, _endpoint.TopicName);
throw;
}
catch (Exception ex)
{
if (claimed)
offsets!.Release();
Abort(producer, ex);
throw;
}
if (claimed)
offsets!.MarkCommitted();
for (var i = 0; i < sends.Count; i++)
{
_endpoint.RecordBytesOut(sends[i].Message.Value.Length);
if (_options.RecordMetadata)
AddDeliveryMetadata(sends[i].Exchange, delivered[i]);
}
Logger?.LogDebug("Kafka transaction committed: topic={Topic}, messages={Count}, consumed offsets={Offsets}",
_endpoint.TopicName, sends.Count, claimed);
}
finally
{
_transactionTurn.Release();
}
}
///
/// The offsets the route's Kafka consumer offered, when it reads the cluster this producer writes to: only that
/// cluster's transaction can commit them. Clusters are compared by the id their brokers report, however the brokers
/// are listed on the two endpoints. Another cluster (or one the consumer could not identify) leaves the offsets to the
/// consumer, and the route is at-least-once; that is said out loud.
///
private KafkaConsumedOffsets? OffsetsOfThisCluster(IExchange exchange)
{
var offered = KafkaConsumedOffsets.OfferedOn(exchange, out var inherited);
if (inherited)
{
WarnOnce(ref _warnedInheritedOffsets,
"Kafka transaction on topic {Topic} runs on a part of the consumed exchange (a split part, a multicast " +
"branch or another copy) and does not take the consumed offsets: the consumer commits them once, after " +
"the whole route. Put the transaction around the split or multicast for exactly-once.",
_endpoint.TopicName);
return null;
}
if (offered is null || offered.Cluster == _cluster)
return offered;
WarnOnce(ref _warnedForeignOffsets,
"Kafka transaction on topic {Topic} cannot take the consumed offsets: the route's consumer reads cluster " +
"'{ConsumerCluster}', this producer writes to cluster '{ProducerCluster}'. The consumer commits them itself, " +
"and the route is at-least-once, not exactly-once.",
_endpoint.TopicName, offered.Cluster ?? "(not identified)", _cluster);
return null;
}
///
/// Warns the first time a producer meets a condition that holds for every exchange of its route (its configuration or
/// shape), then at Debug: a warning per message would bury the log without saying more.
///
private void WarnOnce(ref int warned, string message, params object?[] args)
{
var level = Interlocked.Exchange(ref warned, 1) == 0 ? LogLevel.Warning : LogLevel.Debug;
Logger?.Log(level, message, args);
}
private async Task> TransactionalProducerAsync(CancellationToken ct)
{
if (_rebuild)
{
// The previous incarnation hit a fatal error (fenced, say) and can do nothing more. A new one with the same
// transactional.id fences it for good and aborts whatever it left open.
Logger?.LogWarning("Kafka producer {TransactionalId} is rebuilt after a fatal error", _transactionalId);
_producer?.Dispose();
_producer = null;
await ConnectAsync(ct).ConfigureAwait(false);
_rebuild = false;
// The rebuild goes round Start: a Stop that ran meanwhile found no client to close, and the new one would
// outlive the producer. Transactions never race a rebuild (they take turns); Stop does.
if (!IsStarted)
{
Interlocked.Exchange(ref _producer, null)?.Dispose();
throw new InvalidOperationException(
$"Kafka producer for topic '{_endpoint.TopicName}' was stopped while it was rebuilt: the transaction " +
"cannot be committed.");
}
}
return _producer ?? throw new InvalidOperationException(
$"Kafka producer for topic '{_endpoint.TopicName}' is stopped: the transaction cannot be committed.");
}
private Task> ProduceAsync(
IProducer producer, Message message, KafkaTarget target, CancellationToken ct) =>
KafkaPartitions.ProduceAsync(producer, target.Topic, message, target.Partition, ct);
///
/// The partition of one record, Apache Camel's precedence: the endpoint's partitionKey, else the
/// header of , else none (Kafka's partitioner places the
/// record by its key). A header value that is not a partition number is refused before anything is sent.
///
internal int? ResolvePartition(IExchange source)
=> _options.PartitionKey ?? (source.In.Headers.TryGetValue(KafkaHeaders.PartitionKey, out var value)
? KafkaPartitions.FromHeader(value)
: null);
///
/// Where one record goes, and its timestamp, as camel-kafka's createRecord reads them from
/// : wins over the endpoint's topic and
/// sets the record's timestamp; both are removed from the message, so they
/// do not travel further. The partition is 's. A bad value is refused before the send.
///
internal KafkaTarget ResolveTarget(IExchange source, Message message)
{
var topic = TakeOverrideTopic(source.In) ?? _endpoint.TopicName;
ApplyOverrideTimestamp(source.In, message);
return new KafkaTarget(topic, ResolvePartition(source));
}
///
/// Removes from and returns the topic it names, or
/// when it is absent. A value that is not a topic name is refused.
///
internal static string? TakeOverrideTopic(IMessage message)
=> message.Headers.Remove(KafkaHeaders.OverrideTopic, out var value) && value is not null
? KafkaPartitions.TopicFromHeader(value)
: null;
///
/// Removes from and, when it is there, makes it
/// the timestamp of . A value that is not a timestamp is refused.
///
internal static void ApplyOverrideTimestamp(IMessage source, Message record)
{
if (source.Headers.Remove(KafkaHeaders.OverrideTimestamp, out var value) && value is not null)
record.Timestamp = new Timestamp(KafkaPartitions.TimestampFromHeader(value), TimestampType.CreateTime);
}
private void CommitWithRetries(IProducer producer)
{
for (var attempt = 1; ; attempt++)
{
try
{
// No timeout of ours: librdkafka strongly recommends it (its API timeouts do not match the protocol
// requests); the call blocks up to transaction.timeout.ms instead.
producer.CommitTransaction();
return;
}
catch (KafkaRetriableException ex) when (attempt < 3)
{
// A retriable commit failure (a timeout, say) leaves the transaction open: the commit may be called
// again, and it resumes the same commit.
Logger?.LogWarning(ex, "Kafka transaction commit failed with a retriable error; retrying (attempt {Attempt})",
attempt);
}
}
}
private void Abort(IProducer producer, Exception failure)
{
if (failure is KafkaException { Error.IsFatal: true })
{
_rebuild = true;
Logger?.LogError(failure,
"Kafka producer {TransactionalId} hit a fatal error; its transaction is lost and it is rebuilt before the next one",
_transactionalId);
return;
}
try
{
producer.AbortTransaction(); // no timeout of ours, as for the commit
}
catch (KafkaException abortFailure)
{
// Not committed either way; a producer that cannot abort is not trusted with the next transaction.
_rebuild = true;
Logger?.LogError(abortFailure,
"Kafka producer {TransactionalId} could not abort its transaction; it is rebuilt before the next one",
_transactionalId);
}
}
// ── Message preparation ──
private Message PrepareMessage(IExchange exchange)
{
var body = exchange.In.Body;
byte[] valueBytes = body switch
{
byte[] bytes => bytes,
string str => Encoding.UTF8.GetBytes(str),
null => Array.Empty(),
_ => Encoding.UTF8.GetBytes(body.ToString() ?? string.Empty)
};
var msg = new Message
{
Value = valueBytes,
Key = DetermineKey(exchange),
Headers = new Headers()
};
// Propagate ContentType as Kafka header if set
var hasContentType = !string.IsNullOrEmpty(exchange.In.ContentType);
if (hasContentType)
{
msg.Headers.Add("content-type", Encoding.UTF8.GetBytes(exchange.In.ContentType!));
}
// Propagate headers (skip kafka.* internal ones)
foreach (var (key, value) in exchange.In.Headers)
{
// A consumed record keeps its content-type header next to ContentType: one on the wire, ContentType's.
if (hasContentType && string.Equals(key, "content-type", StringComparison.OrdinalIgnoreCase))
continue;
if (_headerFilter.FilterOutgoing(key, value, exchange))
continue;
try
{
var bytes = Encoding.UTF8.GetBytes(value?.ToString() ?? string.Empty);
msg.Headers.Add(key, bytes);
}
catch (Exception ex)
{
Logger?.LogWarning(ex, "Failed to add header {Key} to Kafka message", key);
}
}
return msg;
}
private string? DetermineKey(IExchange exchange)
{
// The key goes with the record whatever its partition, as in Camel: it still serves compaction and readers.
// Key from options — supports ${...} expressions (resolved per message)
if (!string.IsNullOrWhiteSpace(_options.Key))
{
var resolved = _options.ResolveOption(_options.Key, exchange);
if (!string.IsNullOrEmpty(resolved))
return resolved;
}
// Else the CamelKafkaKey header, as in Camel: the consumed record's key when the route passes the record on.
if (exchange.In.Headers.TryGetValue(KafkaHeaders.Key, out var header) && header?.ToString() is { Length: > 0 } key)
return key;
return null;
}
///
/// Adds one sent record to , Camel's list of RecordMetadata: a fresh list
/// per call of this producer (set in ), one entry per sent record.
///
internal static void AddDeliveryMetadata(IExchange exchange, DeliveryResult result)
{
if (exchange.In.Headers.TryGetValue(KafkaHeaders.RecordMeta, out var value) && value is List list)
{
lock (list)
list.Add(Metadata(result));
return;
}
exchange.In.Headers[KafkaHeaders.RecordMeta] = new List { Metadata(result) };
}
private static KafkaRecordMetadata Metadata(DeliveryResult result)
=> new(result.Topic, result.Partition.Value, result.Offset.Value, result.Timestamp.UnixTimestampMs);
}
///
/// Deferred Kafka send action. The message is captured at creation time
/// and published only on . On the message is discarded.
///
internal sealed class KafkaSendAction : ITransactedAction
{
private readonly IProducer _producer;
private readonly KafkaEndpoint _endpoint;
private readonly string _topicName;
private readonly int? _partition;
private readonly Message _message;
private readonly bool _recordMetadata;
private readonly IExchange _exchange;
private readonly ILogger? _logger;
public KafkaSendAction(
IProducer producer,
KafkaEndpoint endpoint,
Message message,
KafkaTarget target,
bool recordMetadata,
IExchange exchange,
ILogger? logger)
{
_producer = producer;
_endpoint = endpoint;
_topicName = target.Topic;
_message = CloneMessage(message);
_partition = target.Partition;
_recordMetadata = recordMetadata;
_exchange = exchange;
_logger = logger;
}
public async Task Commit(CancellationToken ct = default)
{
var result = await KafkaPartitions.ProduceAsync(_producer, _topicName, _message, _partition, ct).ConfigureAwait(false);
_logger?.LogDebug("Kafka transactional send committed: topic={Topic}, partition={Partition}, offset={Offset}",
result.Topic, result.Partition.Value, result.Offset.Value);
_endpoint.RecordBytesOut(_message.Value.Length);
if (_recordMetadata)
KafkaProducer.AddDeliveryMetadata(_exchange, result);
}
public Task Rollback(CancellationToken ct = default)
{
_logger?.LogDebug("Kafka transactional send rolled back (message discarded): topic={Topic}", _topicName);
return Task.CompletedTask;
}
internal static Message CloneMessage(Message source)
{
var clone = new Message
{
Key = source.Key,
Value = source.Value,
Timestamp = source.Timestamp,
Headers = new Headers()
};
if (source.Headers is not null)
{
foreach (var h in source.Headers)
{
var bytes = h.GetValueBytes();
var copy = new byte[bytes.Length];
Buffer.BlockCopy(bytes, 0, copy, 0, bytes.Length);
clone.Headers.Add(h.Key, copy);
}
}
return clone;
}
}
/// One send of a Kafka-transactional producer: the message, and the exchange its delivery metadata goes to.
internal sealed record KafkaTransactionalSend(Message Message, KafkaTarget Target, IExchange Exchange);
/// Where one record goes: its topic (the endpoint's, or CamelKafkaOverrideTopic) and its partition, if any.
internal readonly record struct KafkaTarget(string Topic, int? Partition);
///
/// The sends a Kafka-transactional producer deferred in one .Transacted() block, committed as one Kafka transaction
/// when the block commits, together with the offsets the route's Kafka consumer offered ().
///
internal sealed class KafkaTransactionBatch : ITransactedAction
{
private readonly KafkaProducer _producer;
private readonly KafkaConsumedOffsets? _offsets;
private readonly ConcurrentQueue _sends = new();
public KafkaTransactionBatch(KafkaProducer producer, KafkaConsumedOffsets? offsets)
{
_producer = producer;
_offsets = offsets;
}
public void Add(KafkaTransactionalSend send) => _sends.Enqueue(send);
public Task Commit(CancellationToken ct = default) => _producer.CommitTransactionAsync(_sends.ToArray(), _offsets, ct);
// The block rolled back before the transaction began: nothing was sent.
public Task Rollback(CancellationToken ct = default) => Task.CompletedTask;
}
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.
[](https://www.nuget.org/packages/redb.Route.Kafka)
[](../../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
```
Path: redb-route/redb.Route.Kafka/redb.Route.Kafka.csproj
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/redb.Route.Kafka.csproj
----
redb.Route.Kafka
Apache Kafka transport for redb.Route ESB framework.
esb;messaging;kafka;redb
README.md