<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Kafka - TheCodeBuzz</title>
	<atom:link href="https://thecodebuzz.com/category/kafka/feed/" rel="self" type="application/rss+xml" />
	<link>https://thecodebuzz.com</link>
	<description>Best Practices for Software Development</description>
	<lastBuildDate>Mon, 22 Jan 2024 03:04:35 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://thecodebuzz.com/wp-content/uploads/2022/11/cropped-android-chrome-512x512-1-1-51x51.jpg</url>
	<title>Kafka - TheCodeBuzz</title>
	<link>https://thecodebuzz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Add Kafka Topic Health Check in ASP.NET Core</title>
		<link>https://thecodebuzz.com/add-kafka-topic-health-check-route-csharp-asp-net-core/</link>
					<comments>https://thecodebuzz.com/add-kafka-topic-health-check-route-csharp-asp-net-core/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 02 Dec 2021 17:13:00 +0000</pubDate>
				<category><![CDATA[Kafka]]></category>
		<category><![CDATA[asp.net core kafka consumer]]></category>
		<category><![CDATA[c# kafka]]></category>
		<category><![CDATA[c# kafka consumer]]></category>
		<category><![CDATA[c# kafka consumer example]]></category>
		<category><![CDATA[c# kafka producer example]]></category>
		<category><![CDATA[consume message from kafka topic c#]]></category>
		<category><![CDATA[health check asp net core ui]]></category>
		<category><![CDATA[kafka .net]]></category>
		<category><![CDATA[Kafka c#]]></category>
		<category><![CDATA[kafka c# example]]></category>
		<category><![CDATA[kafka consumer c#]]></category>
		<category><![CDATA[kafka consumer c# example]]></category>
		<category><![CDATA[kafka consumer code in c#]]></category>
		<category><![CDATA[kafka consumer health check]]></category>
		<category><![CDATA[Kafka Health Check]]></category>
		<category><![CDATA[Kafka Topic Health Check]]></category>
		<category><![CDATA[kafka-net vs confluent kafka]]></category>
		<category><![CDATA[net core background service kafka]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=19130</guid>

					<description><![CDATA[<p>Add Kafka Topic Health Check in ASP.NET Core In this article, we shall check how to implement the Apache Kafka Topic Health Check in ASP.NET Core API or MVC-based applications. Today in this article, we will cover below aspects, In our previous article on how to get started with Kafka in ASP.NET Core, we learned [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/add-kafka-topic-health-check-route-csharp-asp-net-core/">Add Kafka Topic Health Check in ASP.NET Core</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading"><strong>Add Kafka Topic Health Check in ASP.NET Core</strong></h1>



<figure class="wp-block-image size-large is-resized"><img fetchpriority="high" decoding="async" width="1024" height="468" src="https://www.thecodebuzz.com/wp-content/uploads/2021/12/Apache-Kafka-Health-Check-1024x468.jpg" alt=" Kafka Topic Health Check in ASP.NET Core" class="wp-image-19563" srcset="https://thecodebuzz.com/wp-content/uploads/2021/12/Apache-Kafka-Health-Check-1024x468.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2021/12/Apache-Kafka-Health-Check-300x137.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2021/12/Apache-Kafka-Health-Check-768x351.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2021/12/Apache-Kafka-Health-Check-1536x701.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2021/12/Apache-Kafka-Health-Check-785x358.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2021/12/Apache-Kafka-Health-Check.jpg 1765w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>In this article, we shall check how to implement the Apache Kafka Topic Health Check in ASP.NET Core API or MVC-based applications.</p>



<p></p>



<p>Today in this article, we will cover below aspects,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-kafka-topic-health-check-getting-started">Kafka Topic Health Check &#8211; Getting started</a></li><li><a href="#aioseo-create-kafka-health-checks-using-the-ihealthcheck-interface">Create Kafka health checks using the IHealthCheck interface</a></li><li><a href="#aioseo-step1-implement-kafka-ihealthcheck-interface-for-kafka-producer">Step1 &#8211; Implement Kafka IHealthCheck interface for Kafka Producer</a></li><li><a href="#aioseo-step2-register-kafka-health-check-services-in-api">Step2 &#8211; Register Kafka health check services in API</a></li><li><a href="#aioseo-step-3-implement-kafka-ihealthcheck-interface-for-kafka-consumer">Step 3 &#8211; Implement Kafka IHealthCheck interface for Kafka Consumer</a></li><li><a href="#aioseo-summary">Summary</a></li></ul></div>



<p></p>



<p>In our previous article on how to get started with Kafka in ASP.NET Core, we learned how to use Kafka using simple Consumer and Producer examples in ASP.NET Core 3.1 or 6.0 API. </p>



<p></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/kafka-asp-net-core-event-driven-microservices/" target="_blank" rel="noreferrer noopener" title="Getting Started with Kafka in ASP.NET Core"><strong><em>Getting Started with Kafka in ASP.NET Core</em></strong></a></li>
</ul>



<p></p>



<p>In the above article, we created an <strong>API </strong>that acts as a traditional service listening to business events continuously as produced by another Kafka event producer.</p>



<p></p>



<ul class="wp-block-list">
<li>Implementing a health check might be mandatory in many stages of the application development life cycle. </li>
</ul>



<ul class="wp-block-list">
<li>It helps you to keep track of the health of numerous resources, databases, and services that your business application depends on in real time. </li>
</ul>



<ul class="wp-block-list">
<li>This enables you to quickly troubleshoot and resolve technical or environmental issues.</li>
</ul>



<p></p>



<p>Health check services and middleware in ASP.Net core allow us to validate APIs by allowing us to create health check routes. </p>



<p></p>



<p><strong>Kafka Health Check</strong> can be implemented by multiple approaches. You can verify Kafka topic health using either,</p>



<p></p>



<ul class="wp-block-list">
<li>Producing the event to a given topic and verifying the status  Or</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li>Consuming the event message from a given topic (provided you have the right consumer group or consuming messages will not affect any existing consumption)</li>
</ul>



<p></p>



<h2 class="wp-block-heading" id="aioseo-kafka-topic-health-check-getting-started">Kafka Topic Health Check &#8211; Getting started</h2>



<p></p>



<p>If you already have an API, then please follow below two steps below,</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-create-kafka-health-checks-using-the-ihealthcheck-interface">Create Kafka health checks using the IHealthCheck interface</h2>



<p></p>



<p>Creating Kafka health checks using the <strong><em>IHealthCheck </em></strong>interface is simple and it is explained in detail below </p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-step1-implement-kafka-ihealthcheck-interface-for-kafka-producer">Step1 &#8211; Implement Kafka IHealthCheck&nbsp;interface for Kafka Producer</h2>



<p></p>



<p>Here,  please implement the&nbsp;<strong><em><a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.diagnostics.healthchecks.ihealthcheck" target="_blank" rel="noreferrer noopener">IHealthCheck</a>&nbsp;</em></strong>interface and override the <em><strong>CheckHealthAsync&nbsp;</strong></em>method. <strong><em><a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.diagnostics.healthchecks.ihealthcheck" target="_blank" rel="noreferrer noopener">IHealthCheck</a>&nbsp;</em></strong>check is readily available in the below namespace from Microsoft,</p>



<p></p>



<ul class="wp-block-list">
<li><a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.diagnostics.healthchecks?view=dotnet-plat-ext-6.0" target="_blank" rel="noreferrer noopener"><strong><em>Microsoft.Extensions.Diagnostics.HealthChecks</em></strong></a></li>
</ul>



<p></p>



<p>below we are defining <strong><em>KafkaHealthCheck</em></strong> check using <em><strong>ProducerConfig</strong></em> <em><strong>class.</strong></em> This class is available to use from NuGet packages as explained in the below article,</p>



<p></p>



<p>We shall be using Producer capability where we will be pushing the messages to the Kafka topic and verifying Kafka topics access the messages command.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [1]; title: ; notranslate">
public class KafkaHealthCheck : IHealthCheck
    {
        private readonly ProducerConfig _producerConfig;

        private string _topicName;

        public KafkaHealthCheck(ProducerConfig producerConfig, IConfiguration configuration)
        {
            _producerConfig = producerConfig;
            _topicName = configuration.GetValue&lt;string&gt;(&quot;KafkaConsumer:HealthTopicName&quot;);
        }

..

..}
</pre></div>


<p>&nbsp;</p>



<p>Above <strong><em>ProducerConfig </em></strong>is configured at the <strong><em>Startp.cs</em></strong> and then dependency injected by the API pipeline which is already explained in the below article <a style="font-size: revert;" href="https://www.thecodebuzz.com/kafka-asp-net-core-event-driven-microservices/" target="_blank" rel="noreferrer noopener" title="Getting Started with Kafka in ASP.NET Core"><strong><em>Getting Started with Kafka in ASP.NET Core</em></strong></a> </p>



<p></p>



<p>Below is how we are configuring the<strong> ProducerBuilder</strong>,</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">using var p = new ProducerBuilder&lt;Null, string&gt;(_producerConfig).Build();</pre>



<p></p>



<p>below is the <strong><em>CheckHealthAsync </em></strong>which is the <strong><em>IHealthCheck </em></strong>interface method implemented for <strong><em>Kafka producer </em></strong>connection.</p>



<p></p>



<p>Below is the implementation of the method,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [1,9,14]; title: ; notranslate">
public async Task&lt;HealthCheckResult&gt; CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                using var p = new ProducerBuilder&lt;Null, string&gt;(_producerConfig).Build();

                var result = await p.ProduceAsync(_topicName, new Message&lt;Null, string&gt; { Value = $&quot;Kafka is healthy on {DateTime.UtcNow}&quot; }, cancellationToken);

                if (result.Status == PersistenceStatus.NotPersisted)
                {
                    return new HealthCheckResult(context.Registration.FailureStatus, description: $&quot;health check for kafka topic failed.&quot;);
                }

                return HealthCheckResult.Healthy();

            }
            catch (Exception ex)
            {
                return new HealthCheckResult(context.Registration.FailureStatus, exception: ex);
            }
        }

</pre></div>


<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong><em><a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.diagnostics.healthchecks.healthcheckresult" target="_blank" rel="noreferrer noopener">HealthCheckResult</a>&nbsp;</em></strong>lets you return health as&nbsp;<strong><em><code>Healthy</code>,&nbsp;<code>Degraded</code>, or&nbsp;<code>Unhealthy</code></em></strong> statuses.</p>
</blockquote>



<p></p>



<p>In the above method, for any connection failure, you shall get an exception that can be used to return the failure status of the method.</p>



<p></p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-step2-register-kafka-health-check-services-in-api">Step2 &#8211; Register Kafka health check services in API</h2>



<p></p>



<p>In <strong><em>Startup.ConfigureServices</em></strong> please add the <strong><em>HealthChecks </em></strong>as below,</p>



<p></p>



<figure class="wp-block-image size-full"><img decoding="async" width="1022" height="264" src="https://www.thecodebuzz.com/wp-content/uploads/2021/12/kafka-health-check-.net-5-or-.net-6.jpg" alt="How to check kafka health in C# .NET" class="wp-image-19560" srcset="https://thecodebuzz.com/wp-content/uploads/2021/12/kafka-health-check-.net-5-or-.net-6.jpg 1022w, https://thecodebuzz.com/wp-content/uploads/2021/12/kafka-health-check-.net-5-or-.net-6-300x77.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2021/12/kafka-health-check-.net-5-or-.net-6-768x198.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2021/12/kafka-health-check-.net-5-or-.net-6-785x203.jpg 785w" sizes="(max-width: 1022px) 100vw, 1022px" /></figure>



<p></p>



<p>Below is a sample <strong><em>Configure </em></strong>method,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [10]; title: ; notranslate">
 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseHealthChecks(&quot;/healthcheck&quot;);

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =&gt;
            {
                endpoints.MapControllers();
            });
        }
</pre></div>


<p></p>



<p>Let&#8217;s execute the route &#8220;/health check&#8221; and we shall get the Kafka Health check success as below,</p>



<p></p>



<p></p>



<p class="has-medium-font-size">You shall be able to verify <strong><em><code>Healthy</code>,&nbsp;<code>Degraded</code>, or&nbsp;<code>Unhealthy</code></em></strong> status accordingly.</p>



<p></p>



<figure class="wp-block-image size-full"><img decoding="async" width="630" height="183" src="https://www.thecodebuzz.com/wp-content/uploads/2021/12/kafka-health-check-.net-5-or-.net-6-c.webp" alt="Kafka Health Check route in ASP.NET Core Csharp" class="wp-image-19561" srcset="https://thecodebuzz.com/wp-content/uploads/2021/12/kafka-health-check-.net-5-or-.net-6-c.webp 630w, https://thecodebuzz.com/wp-content/uploads/2021/12/kafka-health-check-.net-5-or-.net-6-c-300x87.webp 300w" sizes="(max-width: 630px) 100vw, 630px" /></figure>



<p></p>



<h2 class="wp-block-heading" id="aioseo-step-3-implement-kafka-ihealthcheck-interface-for-kafka-consumer">Step 3 &#8211; Implement Kafka IHealthCheck&nbsp;interface for Kafka Consumer</h2>



<p></p>



<p>If you need to verify the Consumer side of Kafka topics, then the above approach can be extended by adding the producer and consumer together. In that way, you can verify the messages for the producing and consuming sides simultaneously.</p>



<p></p>



<p>For Consumer side implementation &#8211; Plz get it <a href="https://www.thecodebuzz.com/apache-kafka-net-client-producer-consumer-csharp-confluent-examples-ii/" target="_blank" rel="noreferrer noopener">here</a>.</p>



<p></p>



<p><strong>Useful <em>References:</em></strong></p>



<p></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/kafka-asp-net-core-event-driven-microservices/" target="_blank" rel="noreferrer noopener" title="Getting Started with Kafka in ASP.NET Core"><strong><em>Getting Started with Kafka in ASP.NET Core</em></strong></a></li>
</ul>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/apache-kafka-net-client-producer-consumer-csharp-confluent-examples-ii/" target="_blank" rel="noreferrer noopener" title="Kafka C#.NET-Producer and Consumer examples"><strong><em>Kafka C#.NET-Producer and Consumer examples</em></strong></a></li>
</ul>



<p></p>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-summary">Summary </h2>



<p></p>



<p>A health check is critical in multiple aspects and allows you to check the health of various resources, databases, and services that applications are critically dependent on. Today in this article, we looked at a simple approach of enabling Health Check for <strong><em>Kafka Topics </em></strong>(using both the consumer and producer ) in the .NET application.</p>



<p></p>



<p></p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p>



<p></p>



<p></p><p>The post <a href="https://thecodebuzz.com/add-kafka-topic-health-check-route-csharp-asp-net-core/">Add Kafka Topic Health Check in ASP.NET Core</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/add-kafka-topic-health-check-route-csharp-asp-net-core/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
