<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[backend with spring boot - Medium]]></title>
        <description><![CDATA[Spring Boot - Medium]]></description>
        <link>https://medium.com/backend-with-spring-boot?source=rss----1050be04ff4a---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>backend with spring boot - Medium</title>
            <link>https://medium.com/backend-with-spring-boot?source=rss----1050be04ff4a---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 17:21:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/backend-with-spring-boot" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Custom Health Indicators in Spring Boot]]></title>
            <link>https://medium.com/backend-with-spring-boot/custom-health-indicators-in-spring-boot-2763d0bcd07a?source=rss----1050be04ff4a---4</link>
            <guid isPermaLink="false">https://medium.com/p/2763d0bcd07a</guid>
            <category><![CDATA[database-health-checks]]></category>
            <category><![CDATA[spring-boot-actuator]]></category>
            <category><![CDATA[kafka-health-check]]></category>
            <category><![CDATA[custom-health-indicator]]></category>
            <category><![CDATA[custom-health-checks]]></category>
            <dc:creator><![CDATA[Krishna]]></dc:creator>
            <pubDate>Thu, 13 Jun 2024 12:48:58 GMT</pubDate>
            <atom:updated>2024-06-08T08:46:22.654Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lp8ipoeJ5HGBNC3mmUKxlA.png" /></figure><p><strong>Introduction</strong></p><p>Spring Boot provides Health Indicators to monitor application health and database health with the help of Spring Boot Actuator. Spring Boot Actuator comes with various Health Indicators for most of the relational databases and non-relational databases like MongoDB, Redis, ElasticSearch etc. Spring Boot Actuator also provides health indicators for RabbitMQ, IBM MQ out of the box.</p><p><strong>Why to go for Custom Health Checks</strong></p><p>If we want to monitor health status of external services our application connects to, Spring Boot doesn’t provide any health indicators for this scenario out of the box, we need to write custom health indicators. Also Spring Boot doesn’t provide any kafka health indicator out of the box as of today, so in this scenario we need to go for custom health indicator.</p><p><strong>Implementation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*Opdx8XrkrYU2gBEe8Vw6FQ.png" /><figcaption>project structure</figcaption></figure><p><strong>Main class</strong></p><pre>package com.lights5.services.orders.api;<br><br>import com.lights5.services.orders.api.config.EndpointsRegistry;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br><br>@SpringBootApplication<br>public class OrdersApiApplication {<br><br> @Autowired<br> private EndpointsRegistry endpointsRegistry;<br><br> public static void main(String[] args) {<br>  SpringApplication.run(OrdersApiApplication.class, args);<br> }<br>}</pre><p><strong>application.yml file</strong></p><pre>spring:<br>  application:<br>    name: orders-api<br>  kafka:<br>    producer:<br>      bootstrap-servers: localhost:9092<br>  data:<br>    mongodb:<br>      host: localhost<br>      port: 27017<br>      database: orders_db<br>      username: ${username}<br>      password: ${pwd}<br>      authentication-database: orders_db<br><br>app:<br>  client:<br>    payments-service:<br>      host: https://example.com<br>      paths:<br>        health-check: /mock-service/health<br>        intiate-payment: /payments</pre><p><strong>ApplicationConfig</strong></p><pre>package com.lights5.services.orders.api.config;<br><br>import org.apache.kafka.clients.admin.AdminClient;<br>import org.springframework.boot.actuate.data.mongo.MongoHealthIndicator;<br>import org.springframework.boot.autoconfigure.kafka.KafkaProperties;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.data.mongodb.core.MongoTemplate;<br><br>import java.util.Properties;<br><br>@Configuration<br>public class AppConfig {<br><br>    @Bean<br>    MongoHealthIndicator mongoHealthIndicator(MongoTemplate mongoTemplate) {<br><br>        return new CustomMongoHealthIndicator(mongoTemplate);<br>    }<br><br>    @Bean<br>    AdminClient kafkaAdminClient(KafkaProperties kafkaProperties) {<br><br>        Properties properties = new Properties();<br>        properties.put(&quot;bootstrap.servers&quot;, kafkaProperties.getBootstrapServers());<br>        properties.put(&quot;request.timeout.ms&quot;, 3000);<br>        properties.put(&quot;connections.max.idle.ms&quot;, 5000);<br>        return AdminClient.create(properties);<br>    }<br>}</pre><p><strong>EndpointsRegistry</strong></p><p>This class registers all external clients that application connects to.</p><pre>package com.lights5.services.orders.api.config;<br><br>import lombok.Getter;<br>import lombok.Setter;<br>import org.springframework.boot.context.properties.ConfigurationProperties;<br>import org.springframework.context.annotation.Configuration;<br><br>import java.util.Map;<br><br>@Getter<br>@Setter<br>@Configuration<br>@ConfigurationProperties(prefix = &quot;app&quot;)<br>public class EndpointsRegistry {<br><br>    private Map&lt;String, ServiceEndpoint&gt; client;<br><br>    @Getter<br>    @Setter<br>    static class ServiceEndpoint {<br><br>        private String host;<br>        private Map&lt;String, String&gt; paths;<br>    }<br><br>    public String getHealthCheckURL(String serviceName) {<br>        ServiceEndpoint endpoint = this.client.get(serviceName);<br>        if (endpoint != null) {<br>            String healthCheckPath = endpoint.getPaths().get(&quot;health-check&quot;);<br>            String host = endpoint.getHost();<br><br>            return host + healthCheckPath;<br>        }<br>        return null;<br>    }<br>}</pre><p><strong>PaymentServiceMonitor (External Client)</strong></p><p>This class overrides the default behaviour of AbstractHealthIndicator class. It executes GET request on health check url of external client and updates the status accordingly.</p><pre>package com.lights5.services.orders.api.config;<br><br>import lombok.RequiredArgsConstructor;<br>import lombok.extern.slf4j.Slf4j;<br>import org.apache.hc.client5.http.classic.methods.HttpGet;<br>import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;<br>import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;<br>import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;<br>import org.springframework.boot.actuate.health.AbstractHealthIndicator;<br>import org.springframework.boot.actuate.health.Health;<br>import org.springframework.stereotype.Component;<br><br>import java.io.IOException;<br><br>@Slf4j<br>@Component<br>@RequiredArgsConstructor<br>public class PaymentServiceHealthIndicator extends AbstractHealthIndicator {<br><br>    private final EndpointsRegistry endpointsRegistry;<br><br>    @Override<br>    protected void doHealthCheck(Health.Builder builder) {<br>        try {<br>            String healthCheckURL = endpointsRegistry.getHealthCheckURL(&quot;payment-service&quot;);<br>            CloseableHttpClient httpClient = HttpClientBuilder.create().build();<br><br>            CloseableHttpResponse response = httpClient.execute(new HttpGet(healthCheckURL));<br>            if (response.getCode() &gt;= 500) {<br>                log.error(&quot;Payment Service is down&quot;);<br>            }<br>            else {<br>                builder.up();<br>            }<br>        } catch (IOException ex) {<br>            builder.down();<br>        }<br>    }<br>}</pre><p><strong>HostAvailability Class</strong></p><p>This class is used to verify whether application is able to connect to given host and port number.</p><pre>package com.lights5.services.orders.api.service;<br><br>import lombok.extern.slf4j.Slf4j;<br><br>import java.io.IOException;<br>import java.net.*;<br><br>@Slf4j<br>public class HostAvailability {<br><br>    private HostAvailability() {<br>        // to prevent instantiation from other classes.<br>    }<br><br>    public static boolean isAvailable(String hostName, int port) {<br>        SocketAddress socketAddress = new InetSocketAddress(hostName, port);<br><br>        try (Socket socket = new Socket()) {<br><br>            socket.connect(socketAddress, 5000);<br>        } catch (IOException e) {<br><br>            log.error(&quot;Application Health Check Failed due to service unavailability {}&quot;, e.getMessage());<br>            return false;<br>        }<br>        return true;<br>    }<br>}</pre><p><strong>CustomMongoHealthIndicator</strong></p><p>This class extends the MongoHealthIndicator (provided by spring boot) and oveerides the behaviour of health check method. First we are verifying whether app is able to connect to host and port and then we are executing small command on database to check database connectivity. If we execute command directly without verifying server connectivity, it takes more time if server is not reachable from application. That’s why we are verifying server connectivity first.</p><pre>package com.lights5.services.orders.api.config;<br><br>import com.lights5.services.orders.api.service.HostAvailability;<br>import lombok.extern.slf4j.Slf4j;<br>import org.bson.Document;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.boot.actuate.data.mongo.MongoHealthIndicator;<br>import org.springframework.boot.actuate.health.Health;<br>import org.springframework.data.mongodb.core.MongoTemplate;<br><br>@Slf4j<br>public class CustomMongoHealthIndicator extends MongoHealthIndicator {<br><br>    private final MongoTemplate mongoTemplate;<br><br>    @Value(&quot;${spring.data.mongodb.host}&quot;)<br>    private String mongodbHost;<br><br>    @Value(&quot;${spring.data.mongodb.port}&quot;)<br>    private int port;<br><br>    public CustomMongoHealthIndicator(MongoTemplate mongoTemplate) {<br>        super(mongoTemplate);<br>        this.mongoTemplate = mongoTemplate;<br>    }<br><br>    public void doHealthCheck(Health.Builder builder) throws Exception {<br>        boolean isServerAvailable = HostAvailability.isAvailable(mongodbHost, port);<br>        if (isServerAvailable) {<br>            Document result = mongoTemplate.executeCommand(&quot;{ isMaster: 1 }&quot;);<br>            builder.up().withDetail(&quot;maxWireVersion&quot;, result.getInteger(&quot;maxWireVersion&quot;));<br>        }<br>        else {<br>            log.error(&quot;MongoDB Server is down.&quot;);<br>            builder.down();<br>        }<br>    }<br>}</pre><p><strong>KafkaHealthIndicator</strong></p><p>This class provides implementation to verify kafka cluster health. It uses KafkaAdminClient to describe the cluster, if get the response then cluster is up else cluster is down.</p><p>Note: Doesn’t work if producer is configured to support transactions.</p><pre>package com.lights5.services.orders.api.config;<br><br>import lombok.RequiredArgsConstructor;<br>import lombok.extern.slf4j.Slf4j;<br>import org.apache.kafka.clients.admin.AdminClient;<br>import org.apache.kafka.common.Node;<br>import org.springframework.boot.actuate.health.AbstractHealthIndicator;<br>import org.springframework.boot.actuate.health.Health;<br>import org.springframework.stereotype.Component;<br><br>import java.util.Collection;<br>import java.util.concurrent.TimeUnit;<br><br>@Slf4j<br>@Component<br>@RequiredArgsConstructor<br>public class KafkaHealthIndicator extends AbstractHealthIndicator {<br><br>    private final AdminClient kafkaAdminClient;<br><br>    @Override<br>    protected void doHealthCheck(Health.Builder builder) throws Exception {<br><br>        Collection&lt;Node&gt; nodes = kafkaAdminClient.describeCluster()<br>                .nodes().get(3, TimeUnit.SECONDS);<br><br>        if (!nodes.isEmpty()) {<br>            log.error(&quot;Kafka Server is up with nodes {}&quot;, nodes.size());<br>            builder.up();<br>        }<br>        else {<br>            log.error(&quot;Kafka Server is down&quot;);<br>            builder.down();<br>        }<br>    }<br>}</pre><p><strong>Working</strong></p><p>If any of these HealthIndicators (MongoDB, Kafka, Payments Service) is down, then health check url of application returns status as</p><pre>{<br>  &quot;status&quot;: &quot;DOWN&quot;<br>}</pre><p>If all these dependent services are up, then the status will be returned as</p><pre>{<br>  &quot;status&quot;: &quot;UP&quot;<br>}</pre><p>Endpoint to verify app health: <a href="http://localhost:8080/actuator/health">http://localhost:8080/actuator/health</a></p><p><strong>Conclusion</strong></p><p>Custom Health Checks are important as it provides greater visibility of external services availability. We can take action immediately there by decreasing application errors.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2763d0bcd07a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/backend-with-spring-boot/custom-health-indicators-in-spring-boot-2763d0bcd07a">Custom Health Indicators in Spring Boot</a> was originally published in <a href="https://medium.com/backend-with-spring-boot">backend with spring boot</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>