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