Transaction in Confluent.Kafka at Consumer

Viewed 2850

I'm using Apache Kafka as a Message Processor and using Confluent.Kafka in Asp.Net Core as a consumer.

I want to consume messages and save in database, Apparently, I need to a transaction for commit or rollback message in Queue

I'm using a sample of this library as below code:

public static void Main(string[] args)
    {
        var conf = new ConsumerConfig
        {
            GroupId = "test-consumer-group",
            BootstrapServers = "127.0.0.1:9092",
            // Note: The AutoOffsetReset property determines the start offset in the event
            // there are not yet any committed offsets for the consumer group for the
            // topic/partitions of interest. By default, offsets are committed
            // automatically, so in this example, consumption will only start from the
            // earliest message in the topic 'my-topic' the first time you run the program.
            AutoOffsetReset = AutoOffsetReset.Earliest
        };

        using (var c = new ConsumerBuilder<Ignore, string>(conf).Build())
        {
            c.Subscribe("testtopic");

            CancellationTokenSource cts = new CancellationTokenSource();
            Console.CancelKeyPress += (_, e) => {
                e.Cancel = true; // prevent the process from terminating.
                cts.Cancel();
            };

            try
            {
                while (true)
                {
                    try
                    {
                        var cr = c.Consume(cts.Token);  // I NEED TRANSACTION HERE...


                        Console.WriteLine($"Consumed message '{cr.Value}' at: '{cr.TopicPartitionOffset}'.");
                    }
                    catch (ConsumeException e)
                    {
                        Console.WriteLine($"Error occured: {e.Error.Reason}");
                    }
                }
            }
            catch (OperationCanceledException)
            {
                c.Close();
            }
        }
    }

What should I do?

1 Answers

By default Kafka-consumer "automatically and periodically commit offsets in the background" - this behaviour defined by two config params: EnableAutoCommit and AutoCommitIntervalMs.

In your case need to manually make commit:

var conf = new ConsumerConfig
{
    // ..
    EnableAutoCommit = false // <-----
};


// ..

    try
    {
        var cr = c.Consume(cts.Token);

        // .. save data to database ..

        c.Commit(); // <-----

        Console.WriteLine($"Consumed message '{cr.Value}' at: '{cr.TopicPartitionOffset}'.");
    }
    catch (ConsumeException e)
    {
        Console.WriteLine($"Error occured: {e.Error.Reason}");
    }
Related