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");
}