.NET Client for Apache Kafka

confluent-kafka-dotnet is the .NET client library for Apache Kafka®. Confluent develops and maintains the client, which wraps librdkafka, the C/C++ client for Kafka. The client provides a high-level producer, consumer, and AdminClient that are compatible with Kafka brokers version 0.8 and later, Confluent Cloud, and Confluent Platform.

For release updates, see the changelog in the GitHub repository.

Ready to get started?

Installation

Install the .NET client from NuGet with the following command:

dotnet add package Confluent.Kafka

The client is a binding to librdkafka, a C client library for Kafka that is licensed under the 2-clause BSD license. The librdkafka.redist dependency package provides librdkafka automatically for these platforms:

  • linux-x64

  • linux-s390x (IBM Z and LinuxONE)

  • osx-arm64 (Apple Silicon)

  • osx-x64

  • win-x64

  • win-x86

The client is compatible with the following .NET versions:

  • .NET Framework 4.6.2 and later

  • .NET Core 1.0 and later

  • .NET Standard 1.3 and later

Mono is not officially supported.

The Confluent.Kafka package is the core client. The following packages integrate the client with Confluent Schema Registry:

  • Confluent.SchemaRegistry: client for Confluent Schema Registry

  • Confluent.SchemaRegistry.Serdes.Protobuf: serializer and deserializer for Protobuf

  • Confluent.SchemaRegistry.Serdes.Json: serializer and deserializer for JSON Schema

  • Confluent.SchemaRegistry.Serdes.Avro: serializer and deserializer for Avro

Quick start

For a step-by-step tutorial with code samples for the producer and consumer, see Get Started with Apache Kafka and .NET.

The client GitHub repo includes examples that demonstrate the client’s features. For an additional example, see C# client example.

Produce messages with the .NET client

To create a .NET Producer, first construct an instance of the ProducerConfig class, then pass this into the ProducerBuilder’s constructor:

using Confluent.Kafka;
using System.Net;

...

var config = new ProducerConfig
{
    BootstrapServers = "host1:9092",
    ...
};

using (var producer = new ProducerBuilder<Null, string>(config).Build())
{
    ...
}

To write messages to Kafka, use the Produce or ProduceAsync method. ProduceAsync returns a Task that completes when the client receives the result of the request. For high throughput, use Produce, which reports the result of each request to an optional delivery report handler instead.

To write a message with ProduceAsync:

var result = await producer.ProduceAsync("weblog", new Message<Null, string> { Value="a log message" });

Awaiting each ProduceAsync call limits throughput except in highly concurrent applications, such as ASP.NET request handlers. In those applications, the client automatically batches near-concurrent requests for efficiency.

For high throughput with ProduceAsync, use Task.WhenAll to await a block of requests simultaneously. You can also use the Produce method:

public static void handler(DeliveryReport<Null, string>)
{
    ...
}

public static process(...)
{
    ...
    producer.Produce(
        "my-topic", new Message<Null, string> { Value = "hello world" }, handler);
}

The Produce method is also asynchronous meaning it never blocks. The client sends delivery information to the optional delivery report handler on a background thread. Produce maps more directly to the underlying librdkafka produce API, so it has less overhead than ProduceAsync. ProduceAsync still performs well, producing hundreds of thousands of messages per second on typical hardware.

The .NET client supports the following producer features. For in-depth information, see the librdkafka documentation.

  • Idempotent producer. Set the EnableIdempotence configuration property to true for exactly once, ordered delivery guarantees.

  • Transactional producer API. For an example of how to use transactions from .NET, see the ExactlyOnce example in the GitHub repo.

Consume messages with the .NET client

Create a .NET consumer

To create a .NET consumer, first construct an instance of the ConsumerConfig class, then pass this into the constructor for a ConsumerBuilder:

using System.Collections.Generic;
using Confluent.Kafka;

...

var config = new ConsumerConfig
{
    BootstrapServers = "host1:9092,host2:9092",
    GroupId = "foo",
    AutoOffsetReset = AutoOffsetReset.Earliest
};

using (var consumer = new ConsumerBuilder<Ignore, string>(config).Build())
{
    ...
}

A consumer group is a set of consumers that share a group ID and divide the partitions of the topics they subscribe to. The GroupId property is mandatory and specifies which consumer group the consumer is a member of.

The AutoOffsetReset property specifies the offset the consumer starts reading from only when a partition has no committed offsets or the committed offset is invalid, for example after log truncation.

Consume messages in a loop

The consume loop repeatedly calls the Consume method to retrieve records one by one. The consumer pre-fetches the records in background threads. A typical Kafka consumer application revolves around this loop.

Before entering the loop, use the Subscribe method to join a group. The group then assigns the consumer an exclusive subset of the partitions it manages.

...

using (var consumer = new ConsumerBuilder<Ignore, string>(config).Build())
{
    consumer.Subscribe(topics);

    while (!cancelled)
    {
        var consumeResult = consumer.Consume(cancellationToken);

        // handle consumed message.
        ...
    }

    consumer.Close();
}

Call the Close method before disposing the consumer to commit final offsets and leave the group cleanly. Closing triggers a group rebalance that reassigns the partitions the consumer owned to other members of the group in a timely fashion. Disposing the consumer, which the using block in the consume loop example does, closes active sockets and cleans up internal state.

Choose an offset commit strategy

Use the StoreOffset method to get at-least-once delivery without blocking the main processing loop. The .NET consumer supports three ways to commit offsets:

  • Auto offset commit. The consumer commits offsets periodically in the background. This is the default, with EnableAutoCommit set to true. After an application failure, the application can miss messages or process duplicates. It doesn’t block the processing loop.

  • Synchronous commit. Set EnableAutoCommit to false and call Commit yourself. You get at-least-once delivery as long as you commit an offset only after processing the corresponding message, but each commit blocks the processing loop.

  • Store offsets. Set EnableAutoOffsetStore to false and call StoreOffset. You get at-least-once delivery, and the processing loop doesn’t block.

Auto offset commit

By default, the .NET consumer commits offsets automatically. A background thread commits offsets periodically, at the interval you set with the AutoCommitIntervalMs configuration property. An offset becomes eligible for commit immediately before the Consume method delivers the message to the application.

Auto offset commit has two risks if the application fails:

  • Missed messages. The application can stop before it finishes processing a message, while the background thread commits the offset for that message to Kafka.

  • Duplicate processing. The consumer commits offsets only periodically, so the application can process messages again after a restart.

Synchronous commits

The C# client lets you commit offsets explicitly with the Commit method. In the following example, the application commits synchronously every commitPeriod messages:

var config = new ConsumerConfig
{
    ...
    // Disable auto-committing of offsets.
    EnableAutoCommit = false
}

...

while (!cancelled)
{
    var consumeResult = consumer.Consume(cancellationToken);

    // process message here.

    if (consumeResult.Offset % commitPeriod == 0)
    {
        try
        {
            consumer.Commit(consumeResult);
        }
        catch (KafkaException e)
        {
            Console.WriteLine($"Commit error: {e.Error.Reason}");
        }
    }
}

For processing failures that result in an application crash, the Commit method provides at-least-once delivery semantics. The application commits the offset for a message only after it processes the message successfully. For errors that don’t crash the application, the application calls the Seek method and move backward to the failed offset.

If you reverse the order of processing and commit, and you commit before every message instead of periodically, you get at-most-once delivery semantics.

Note

Avoid blocking network calls, including synchronous use of Commit, because they reduce throughput.

Store offsets for at-least-once processing

Use the StoreOffset method to specify the offsets you want the background thread to commit. By default, the consumer updates the offsets to commit to Kafka immediately before the Consume method delivers a message to the application. To prevent this, set the EnableAutoOffsetStore configuration property to false. You can call StoreOffset as many times as you like. The consumer sends the offset commit request to the group coordinator periodically, with the most recently stored offsets for the owned partitions. Use this approach instead of synchronous commits.

The following example uses this approach to achieve at-least-once delivery semantics without blocking the main processing loop:

var config = new ConsumerConfig
{
    ...
    EnableAutoCommit = true, // the default
    EnableAutoOffsetStore = false
}

...

while (!cancelled)
{
    var consumeResult = consumer.Consume(cancellationToken);

    // process message here.

    consumer.StoreOffset(consumeResult);
}

Committing during a rebalance

A rebalance reassigns partitions among the members of a consumer group. A consumer subscribed to a group can commit offsets only for the partitions that it owns. By default, the consumer handles a rebalance automatically in the background. This behavior creates a potential race condition: you try to commit or store an offset, but a rebalance has already removed the consumer’s ownership of that partition. In this case, the Commit or StoreOffset call throws a KafkaException with ErrorCode equal to Local_State, which means that the consumer is in an erroneous state. For at-least-once processing, you can treat this error as a warning and ignore it, because the new owner of the partition processes the message again.

To avoid the race condition, you can instead specify a partitions revoked handler, which can be empty. The client calls rebalance handlers as a side effect of a Consume call on the application thread, so the rebalance waits while you process the consumed message and store or commit offsets.

...

using (var consumer = new ConsumerBuilder<Ignore, string>(config)
    .SetPartitionsRevokedHandler((c, partitions) =>
    {
        ...
    })
    .Build())
{
    ...
}

.NET client API reference

See the .NET client API reference.