Configuring Hikari Connection Pool with Spring Boot

In this article, we will learn the steps to configure Hikari with Spring Boot. We will cover steps to configure Hikari for both Spring Boot 1 and Spring Boot 2 application.

Configure Hikari with Spring Boot

HikariCP is a reliable, high-performance production ready jdbc connection pool. It is much faster, lightweight and has better performance as compare to other connection pool API. Because of all these compelling reasons, HikariCP is now the default connection pool implementation in Spring Boot 2. In this article, we will have a closer look to configure Hikari with Spring Boot application and some configurations to get the high performance connection pool.

1. Setting Up Hikari with Spring Boot

Hikari is the default DataSource implementation with Spring Boot 2. This means we need not add explicit dependency in the pom.xml. To sum up, you require no other steps with Spring Boot 2.. To use Hikari connection pooling, add the following dependency in the pom.xml.

1.1. Maven Dependency

<dependency>
  <groupId>com.zaxxer</groupId>
  <artifactId>HikariCP</artifactId>
  <version>5.1.0</version>
</dependency>

There are few major changes that was done in Spring-Boot application

  • The spring-boot-starter-jdbc and spring-boot-starter-data-jpa resolve it by default.
  • Spring Boot auto-configuration now prefers Hikari data source over TomcatJDBC
You can skip adding Hikari’s latest version unless you really want it.

2. HikariCP Configurations

Although Spring Boot provides some default value for Hikari, however we can customize the Hikaricp configuration using the application.properties file. Hikari DataSource provides offer a lot of configuration parameters as compared to others. We can specify the values for these parameters by using the prefix spring.datasource.hikari and appending the name of the Hikari parameter.

Let’s look at some following properties of the Hikari data source which can be useful for fine tuning our application.

spring.datasource.hikari.connection-timeout = 20000 #maximum number of milliseconds that a client will wait for a connection
spring.datasource.hikari.minimum-idle= 10 #minimum number of idle connections maintained by HikariCP in a connection pool
spring.datasource.hikari.maximum-pool-size= 10 #maximum pool size
spring.datasource.hikari.idle-timeout=10000 #maximum idle time for connection
spring.datasource.hikari.max-lifetime= 1000 # maximum lifetime in milliseconds of a connection in the pool after it is closed.
spring.datasource.hikari.auto-commit =true #default auto-commit behavior.

Let’s look at the common property name for our reference:

  • auto-commit – This property controls the default auto-commit behavior of connections returned from the hikaricp connection pool. It is a boolean value. Default: true.
  • connectionTimeout – The connection timeout controls the maximum number of milliseconds that a client will wait for a new connection from the pool. It will throw SQLException if no connection is available in the pool.
  • idle-timeout – The idle timeout property controls the maximum amount of time that a connection may sit idle in the pool of connections.
  • max-lifetime – The maximum lifetime of a connection in the pool. An in-use connection will never be retired, only when it is closed will it then be removed. It’s recommended setting this value, and it should be several seconds shorter than any database or infrastructure imposed connection time limit.
  • minimum-idle – minimum number of idle connections that HikariCP tries to maintain in the pool.
  • maximum-pool-size – This property controls the max pool size that may reach, including both idle and in-use connections. It maximum number of actual db connection to the database.

For more details on hikari configuration for your spring boot application, please refer to the HikariCP documentation or Spring Boot.

3. Custom Data Source

If you like to create a custom data source for your Spring Boot Hikari, we need to define a datasource bean if our custom configuration.Spring Boot reuses this DataSource anywhere one is required, including database initialization. Look at the following example.

@Configuration
public class DataSourceConfiguration {

    @Bean(name = "customDataSource")
    @ConfigurationProperties("spring.datasource")
    public DataSource customDataSource() {
        return DataSourceBuilder.create().build();
    }
}

We used the Spring Boot builder class DataSourceBuilder to build the custom data source. This utility class offers a lot of benefits:

  1. The build class will help us create a standard data source with default settings.
  2. It can auto-detect a driver based on the JDBC URL.

In case you want to be more specific, you can use the same DataSourceBuilder utility class to create new HikariDataSource

@Configuration
public class DataSourceConfiguration {

    @Bean
    @ConfigurationProperties("spring.datasource")
    public HikariDataSource customDataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }
}

4. Hikari Log Output

Once we start our application, monitor the console log, you may notice an identical output:

2019-03-24 17:43:58.066  INFO 51692 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-03-24 17:43:58.072  WARN 51692 --- [  restartedMain] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
2019-03-24 17:43:58.353  INFO 51692 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.

5. Configuring Hikari with Spring Boot 1

Spring Boot 1 uses the tomcat JDBC connection pool. Spring Boot automatically adds dependency to tomcat-jdbc if you use the spring-boot-starter-jdbc or spring-boot-starter-data-jpastarters’ in your application. To configure Hikari in our application, we have the following two options:

  1. Add the HikariCP maven dependency.
  2. Remove the Tomcat JDBC connection pool and let Spring Boot look for HikariCP in the class-path.

5.1. Maven Dependency

The first step for Hikari and Spring Boot configuration is to add hikaricp dependency in the pom.xml file:

<dependency>
  <groupId>com.zaxxer</groupId>
  <artifactId>HikariCP</artifactId>
  <version>5.1.0</version>
</dependency>
<!-- exclude tomcat jdbc connection pool, use HikariCP -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
   <exclusions>
      <exclusion>
         <groupId>org.apache.tomcat</groupId>
         <artifactId>tomcat-jdbc</artifactId>
      </exclusion>
   </exclusions>
</dependency>

This step will force Spring Boot to look for the Hikari data source in the class path. We can use the Maven standard <exclude> tag for this.

6. Monitoring Hikari Connection Pool Configuration

Just like regular health checkups are important for your body, monitoring your app’s data source is crucial for its health. If any problems pop up with your data source, it can cause issues for your entire application.Spring Boot actuator makes it easy to monitor the Datasource properties by actuator metrics with the help of below properties.

management.endpoint.metrics.enabled=true
management.endpoints.web.exposure.include=metrics

Now you can easily access and view all kinds of data source metrics, including:

  • Connection pool metrics: Get insights into active connections, idle connections, and more.
  • Database metrics: Track query execution times, connection errors, and other database-specific details.
Make sure you add the Spring Boot actuator dependency in your application

Run the following command:

http://localhost:8080/actuator/metrics

You will have something similar

{
  "names": [
    "application.ready.time",
    "application.started.time",
    "disk.free",
    "disk.total",
    "executor.active",
    "executor.completed",
    "executor.pool.core",
    "executor.pool.max",
    "executor.pool.size",
    "executor.queue.remaining",
    "executor.queued",
    "hikaricp.connections",
    "hikaricp.connections.acquire",
    "hikaricp.connections.active",
    "hikaricp.connections.creation",
    "hikaricp.connections.idle",
    "hikaricp.connections.max",
    "hikaricp.connections.min",
    "hikaricp.connections.pending",
    "hikaricp.connections.timeout",
    "hikaricp.connections.usage",
    "http.server.requests",
    "http.server.requests.active",
    "jdbc.connections.active",
    "jdbc.connections.idle",
    "jdbc.connections.max",
    "jdbc.connections.min",
    "jvm.buffer.count",
    "jvm.buffer.memory.used",
    "jvm.buffer.total.capacity",
    "jvm.classes.loaded",
    "jvm.classes.unloaded",
    "jvm.compilation.time",
    "jvm.gc.live.data.size",
    "jvm.gc.max.data.size",
    "jvm.gc.memory.allocated",
    "jvm.gc.memory.promoted",
    "jvm.gc.overhead",
    "jvm.gc.pause",
    "jvm.info",
    "jvm.memory.committed",
    "jvm.memory.max",
    "jvm.memory.usage.after.gc",
    "jvm.memory.used",
    "jvm.threads.daemon",
    "jvm.threads.live",
    "jvm.threads.peak",
    "jvm.threads.started",
    "jvm.threads.states",
    "logback.events",
    "process.cpu.usage",
    "process.files.max",
    "process.files.open",
    "process.start.time",
    "process.uptime",
    "system.cpu.count",
    "system.cpu.usage",
    "system.load.average.1m",
    "tomcat.sessions.active.current",
    "tomcat.sessions.active.max",
    "tomcat.sessions.alive.max",
    "tomcat.sessions.created",
    "tomcat.sessions.expired",
    "tomcat.sessions.rejected"
  ]
}

You can check individual metric by passing that in the request. Let’s try to find details of the hikaricp.connections

http://localhost:8080/actuator/metrics/hikaricp.connections

{
  "name": "hikaricp.connections",
  "description": "Total connections",
  "measurements": [
    {
      "statistic": "VALUE",
      "value": 10
    }
  ],
  "availableTags": [
    {
      "tag": "pool",
      "values": [
        "HikariPool-1"
      ]
    }
  ]
}

Summary

In this short article, we saw how to configure Hikari with Spring Boot. We also leaned that Hikari is the default data source in Spring Boot.

3 thoughts on “Configuring Hikari Connection Pool with Spring Boot”

      • Automatically gets taken care

        2020-07-21 07:55:41.710 WARN 63445 — [ restartedMain] com.zaxxer.hikari.HikariConfig      : HikariPool-1 – maxLifetime is less than 30000ms, setting to default 1800000ms.
        [WARN] com.zaxxer.hikari.HikariConfig – HikariPool-1 – maxLifetime is less than 30000ms, setting to default 1800000ms.

Comments are closed.