Event sourcing with Apache Kafka
Introduction
Apache Kafka is a distributed streaming system primary used to build real-time streaming data pipelines and applications that adapt to the data streams. It combines messaging, storage, and stream processing to allow storage and analysis of both historical and real-time data. In this article, we going to build a simple application that produce and consumer the data from Kafka
We will use Confluent to configure our Kafka and create web application to act as Producer to produce event message and a console app to retrieve the event message by subscribe to Kafka.
Walkthrough
Create a Confluent account
You need to create Confluent account for this exercise. If you already have it, you can skip to next step.
Create an account on Confluent
You will be request to key in payment information, but don’t worry it won’t charge you a cent as long as you clean up all the resources after you finish this exercise
Apply Promo code
There are few promo code you can apply to get free usage.
Navigate to “Billing & payment”
Navigate to “Payment details & contacts”
Add new promo code at the bottom of the page
Create Cluster
Before we can produce or consume event from Kafka, we need to create a cluster. Clusters are a group of interconnected Kafka brokers that work together to manage and distribute the data streams.
Click “Add Cluster”
Select the environment you want to use, we will have a “default” environment when you create your Confluent account.
Enter a name for cluster, and choose “Basic” type.
You can select any region you want.
Create API key
We need an API key to connect our application and Confluent Kafka.
Navigate to “API Keys” and create a key.
We will select create an account API key for this walkthrough.
Confluent will generate the API key and secret, click “Download and continue” will download the API key as text file for later use.
Create Topic
Topics are categories used to organize messages, producer will publish their messages to topics and consumer subscribe topics to get the messages data.
Navigate to “Topics” and create a topic
Give the topic a name.
Note that the topic name is used on producer and consumer, if you choose a name different with mine, you need to put your on producer and consumer later.
Data contract is a service that let you define the data structure of your topic. You can learn more from here. We can click “Skip” for this walkthrough.
Create Producer
A producer will produce the message, which actually just send a message to Kafka. I will create a simple Blazor web app for this walkthrough, but an simple API that contain an endpoint to send message to Kafka also will achieve the same result.
Create Blazor web app
Name the project as “KafkaProducer”.
I didn’t place the solution and project in same directory because I will create a new project for consumer in same solution later.
To keep it simple, Select “Server” render mode.
Add the Kafka config into
appsetting.jsonRight click the “Dependencies” on the right panel and click “Manage NuGet Packages”
Click “Browse”, enter “kafka” in the text box, install the Confluent.Kafka
Click “Apply”
We will use the
Home.razorbe our producer page.Remove the content inside
Home.razorand replace it with below1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
@page "/" @rendermode InteractiveServer @using Confluent.Kafka @inject IConfiguration Configuration <PageTitle>Producer</PageTitle> <h3>Producer</h3> <div class="text-center flex-fill d-flex justify-content-center align-items-center"> <div> <label for="message">Enter Text:</label> <input type="text" id="message" name="message" @bind="newMessage"/> </div> <div> <button @onclick="ProduceMessage">Submit</button> </div> </div>
This is just a simple HTML with one text box for user input any message and a button to send the message to Kafka. Next we will be adding the actual login that produce the message.
First we need to read the Kafka config from
appsetting.json1 2 3 4 5 6
private IConfiguration configuration; protected override void OnInitialized() { configuration = Configuration.GetSection("Kafka"); }
Next, we need to have a function to produce the message
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
private string? newMessage; private void ProduceMessage() { string topic = configuration["Topic"]!; ProducerConfig config = new() { BootstrapServers = configuration["BootstrapServers"], SecurityProtocol = SecurityProtocol.SaslSsl, SaslMechanism = SaslMechanism.Plain, SaslUsername = configuration["ApiKey"], SaslPassword = configuration["ApiSecret"], }; // creates a new Kafka producer instance using (var producer = new ProducerBuilder<Null, string>(config).Build()) { // produces the message to kafka producer.Produce(topic, new Message<Null, string> { Value = newMessage! }, (deliveryReport) => { if (deliveryReport.Error.Code != ErrorCode.NoError) { Console.WriteLine($"Failed to deliver message: {deliveryReport.Error.Reason}"); } else { Console.WriteLine($"Produced event to topic {topic}: key = {deliveryReport.Message.Key,-10} value = {deliveryReport.Message.Value}"); } }); producer.Flush(TimeSpan.FromSeconds(10)); } newMessage = null; }
We feed the config from
appsetting.jsonintoProducerConfigand build a Kafka producer instance to produce the message.Flush()method will send all the message in the internal queue to Kafka.Note: This might not the actual Kafka producer setup, the producer will only send out message if the message in the internal queue ≥
queue.buffering.max.ms. Read more from here.Below is the combined HTML code and logic
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
@page "/" @rendermode InteractiveServer @using Confluent.Kafka @inject IConfiguration Configuration <PageTitle>Producer</PageTitle> <h3>Producer</h3> <div class="text-center flex-fill d-flex justify-content-center align-items-center"> <div> <label for="message">Enter Text:</label> <input type="text" id="message" name="message" @bind="newMessage" /> </div> <div> <button @onclick="ProduceMessage">Submit</button> </div> </div> @code { private string? newMessage; private IConfiguration configuration; protected override void OnInitialized() { configuration = Configuration.GetSection("Kafka"); } private void ProduceMessage() { string topic = configuration["Topic"]!; ProducerConfig config = new() { BootstrapServers = configuration["BootstrapServers"], SecurityProtocol = SecurityProtocol.SaslSsl, SaslMechanism = SaslMechanism.Plain, SaslUsername = configuration["ApiKey"], SaslPassword = configuration["ApiSecret"], }; // creates a new Kafka producer instance using (var producer = new ProducerBuilder<Null, string>(config).Build()) { // produces the message to kafka producer.Produce(topic, new Message<Null, string> { Value = newMessage! }, (deliveryReport) => { if (deliveryReport.Error.Code != ErrorCode.NoError) { Console.WriteLine($"Failed to deliver message: {deliveryReport.Error.Reason}"); } else { Console.WriteLine($"Produced event to topic {topic}: key = {deliveryReport.Message.Key,-10} value = {deliveryReport.Message.Value}"); } }); producer.Flush(TimeSpan.FromSeconds(10)); } newMessage = null; } }
Example Output
Create Consumer
Consumer will subscribe a topic and keep pooling the message data from topic. We will create a simple console application as Kafka Consumer.
Right click the solution and create new project
Select “Console App”
Name it as “KafkaConsumer”
Leave other as default
Same as KafkaProducer, install Confluent.Kafka dependency
Now we can implement the consumer logic. First we need to prepare the config value of the consumer.
- BoostrapServer, ApiKey, and ApiSecret is same as Producer
- groupId: Is string that represent a consumer group, so that a message won’t process by different consumer node in the same group
Prepare the ConsumerConfig
1 2 3 4 5 6 7 8 9 10
ConsumerConfig config = new() { GroupId = groupId, AutoOffsetReset = AutoOffsetReset.Earliest, BootstrapServers = bootstrapServer, SecurityProtocol = SecurityProtocol.SaslSsl, SaslMechanism = SaslMechanism.Plain, SaslUsername = apiKey, SaslPassword = apiSecret, };
Create consumer instance to read message from topic
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
using (var consumer = new ConsumerBuilder<string, string>(config).Build()) { consumer.Subscribe(topic); while (true) { // consumes messages from the subscribed topic and prints them to the console var cr = consumer.Consume(); try { Console.WriteLine($"Consumed event from topic \"{topic}\": value = {cr.Message.Value}"); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
Below is the combined consumer logic
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
using Confluent.Kafka; Console.WriteLine("Consumer Starting"); string topic = "order"; string groupId = "kitchen-group-1"; string bootstrapServer = "pkc-921jm.us-east-2.aws.confluent.cloud:9092"; string apiKey = "U2CFPHN5KWCOONF3"; string apiSecret = "9SivBcQfQRHt1+XQL9dXH+0gWVOGL5CyNNLSYrQWkoX8T2rF128EsXQZRFHgsKqY"; ConsumerConfig config = new() { GroupId = groupId, AutoOffsetReset = AutoOffsetReset.Earliest, BootstrapServers = bootstrapServer, SecurityProtocol = SecurityProtocol.SaslSsl, SaslMechanism = SaslMechanism.Plain, SaslUsername = apiKey, SaslPassword = apiSecret, }; // creates a new consumer instance using (var consumer = new ConsumerBuilder<string, string>(config).Build()) { consumer.Subscribe(topic); while (true) { // consumes messages from the subscribed topic and prints them to the console var cr = consumer.Consume(); try { Console.WriteLine($"Consumed event from topic \"{topic}\": value = {cr.Message.Value}"); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
Example output
Extra: Start Producer and Consumer at the same time
Since the Producer and Consumer is in different project, you can only execute one project by default. But Visual Studio allow to configure execute both project in the same time.
Right click the solution and select “Properties”
Select “Multiple startup project” and change action to “Start” for both project. Then click “Apply” and “Ok”
Select “Yes” in popup window
Now you can start boh projects with “Start”
Clean up
To unexpected charges from Confluent, we need to delete the resources we created in confluent.
Navigate to Cluster > Cluster settings
At the bottom of cluster settings click the “Delete cluster” button
Enter the cluster name
Done
Conclusion
You had successfully created a Kafka Producer that produce event messages into Apache Kafka and a Kafka Consumer that subscribe the Apache Kafka to consume event messages. Understand the relationship between the components of the Apache Kafka like cluster, topics, producer, and consumer allow you to build a real-time event streaming application. Take note that this is just a simple Apache Kafka application, there are still a lot of component not cover like schema registry, data connector, and etc.










































