Definition
- Connection pool is a cache of database connections that are kept open and reused across requests, so each query does not pay the cost of a new TCP handshake and authentication.
- HikariCP is the connection pool library bundled with Spring Boot by default; it is known for being the fastest Java connection pool with the smallest memory footprint.
- maximumPoolSize is the most critical setting; it defines the upper limit of connections the pool can create, including idle and in-use connections.
- connectionTimeout is the maximum time (in milliseconds) a thread waits for a connection from the pool; if no connection becomes available, the pool throws an exception.
- maxLifetime is the maximum lifetime of a connection in the pool; after this time, HikariCP retires the connection and creates a new one to prevent stale connections.
- minimumIdle is the minimum number of idle connections HikariCP maintains; the recommended setting is to make it equal to maximumPoolSize for consistent latency.
Think of the National Bank of India branch with 10 teller counters. When a customer (database query) arrives, the branch manager (HikariCP) assigns an available teller (connection). If all 10 tellers are busy, the customer waits in a queue (connectionTimeout). If a teller has been working for 30 minutes straight (maxLifetime), the manager sends them on break and brings in a fresh teller. The branch never has more than 10 tellers working at once (maximumPoolSize), and it always keeps at least 5 ready even when no customers are around (minimumIdle). Without this system, the bank would need to hire and fire a teller for every single customer.
Understanding the Concepts
What is connection pooling and why does it matter?
Every time your application runs a database query, it needs a JDBC connection. Without a pool, each query opens a new TCP connection to the database, performs the TLS handshake (if encrypted), authenticates, runs the query, and then closes the connection. This process takes 5 to 50 milliseconds depending on network latency and database load. For an application handling 1,000 requests per second, that overhead adds up to seconds of wasted time.
A connection pool solves this by keeping a set of connections open and ready. When your code needs a connection, it borrows one from the pool. When the query finishes, the connection returns to the pool instead of being closed. The next request reuses that same connection.
package com.bank;
public class ConnectionCostComparison {
public static void main(String[] args) {
System.out.println("Without connection pool:");
System.out.println(" Request 1: open TCP (20ms) + auth (5ms) + query (3ms) + close (2ms) = 30ms");
System.out.println(" Request 2: open TCP (20ms) + auth (5ms) + query (3ms) + close (2ms) = 30ms");
System.out.println(" 1000 requests: 30,000ms total overhead");
System.out.println();
System.out.println("With connection pool (HikariCP):");
System.out.println(" Request 1: borrow (0.1ms) + query (3ms) + return (0.1ms) = 3.2ms");
System.out.println(" Request 2: borrow (0.1ms) + query (3ms) + return (0.1ms) = 3.2ms");
System.out.println(" 1000 requests: 3,200ms total overhead");
System.out.println();
System.out.println("Pooling saves ~90% of connection overhead.");
}
}
Expected output:
Without connection pool:
Request 1: open TCP (20ms) + auth (5ms) + query (3ms) + close (2ms) = 30ms
Request 2: open TCP (20ms) + auth (5ms) + query (3ms) + close (2ms) = 30ms
1000 requests: 30,000ms total overhead
With connection pool (HikariCP):
Request 1: borrow (0.1ms) + query (3ms) + return (0.1ms) = 3.2ms
Request 2: borrow (0.1ms) + query (3ms) + return (0.1ms) = 3.2ms
1000 requests: 3,200ms total overhead
Pooling saves ~90% of connection overhead.
How does HikariCP work internally?
HikariCP uses a lock-free design based on ConcurrentBag, a custom concurrent collection. When a thread requests a connection, HikariCP first checks if the requesting thread already has a previously used connection available (thread-local affinity). If not, it scans the shared pool. If no idle connection exists and the pool has not reached maximumPoolSize, it creates a new one.
The pool tracks each connection's state: IN_USE, NOT_IN_USE, REMOVED, or RESERVED. When a connection is returned, HikariCP marks it as NOT_IN_USE and makes it available for the next request. A background housekeeper thread runs every 30 seconds to retire connections that have exceeded maxLifetime or been idle too long.
package com.bank;
public class HikariInternalFlow {
public static void main(String[] args) {
System.out.println("HikariCP connection lifecycle:");
System.out.println();
System.out.println("1. Thread calls dataSource.getConnection()");
System.out.println("2. HikariCP checks thread-local cache (fast path)");
System.out.println("3. If miss, scan ConcurrentBag for NOT_IN_USE connection");
System.out.println("4. If none available and pool < maximumPoolSize, create new connection");
System.out.println("5. If pool is full, wait up to connectionTimeout milliseconds");
System.out.println("6. Mark connection as IN_USE, return to caller");
System.out.println("7. Caller runs query, calls connection.close()");
System.out.println("8. HikariCP intercepts close(), marks as NOT_IN_USE");
System.out.println("9. Connection returns to pool for reuse");
System.out.println();
System.out.println("Background housekeeper (every 30s):");
System.out.println(" - Remove connections older than maxLifetime");
System.out.println(" - Add connections if below minimumIdle");
System.out.println(" - Validate idle connections with keepaliveTime");
}
}
Expected output:
HikariCP connection lifecycle:
1. Thread calls dataSource.getConnection()
2. HikariCP checks thread-local cache (fast path)
3. If miss, scan ConcurrentBag for NOT_IN_USE connection
4. If none available and pool < maximumPoolSize, create new connection
5. If pool is full, wait up to connectionTimeout milliseconds
6. Mark connection as IN_USE, return to caller
7. Caller runs query, calls connection.close()
8. HikariCP intercepts close(), marks as NOT_IN_USE
9. Connection returns to pool for reuse
Background housekeeper (every 30s):
- Remove connections older than maxLifetime
- Add connections if below minimumIdle
- Validate idle connections with keepaliveTime
What are the key HikariCP configuration properties?
Spring Boot configures HikariCP through application.properties or application.yml under the prefix spring.datasource.hikari. The most important properties and their defaults are:
| Property | Default | Description |
|---|---|---|
| maximumPoolSize | 10 | Max connections (idle + in-use) |
| minimumIdle | same as maximumPoolSize | Min idle connections to maintain |
| connectionTimeout | 30000 (30s) | Max wait time for a connection from pool |
| idleTimeout | 600000 (10min) | Max time a connection sits idle before removal |
| maxLifetime | 1800000 (30min) | Max total lifetime of a connection |
| keepaliveTime | 0 (disabled) | Interval for keepalive pings on idle connections |
| leakDetectionThreshold | 0 (disabled) | Time before a borrowed connection is flagged as a leak |
| poolName | HikariPool-1 | Name shown in logs and JMX |
# application.properties for a banking application
spring.datasource.url=jdbc:postgresql://db.nationalbank.in:5432/accounts
spring.datasource.username=app_user
spring.datasource.password=${DB_PASSWORD}
spring.datasource.driver-class-name=org.postgresql.Driver
# HikariCP pool settings
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=20
spring.datasource.hikari.connection-timeout=5000
spring.datasource.hikari.idle-timeout=300000
spring.datasource.hikari.max-lifetime=1200000
spring.datasource.hikari.keepalive-time=60000
spring.datasource.hikari.leak-detection-threshold=30000
spring.datasource.hikari.pool-name=NationalBankPool
package com.bank;
public class HikariConfigExplained {
public static void main(String[] args) {
System.out.println("National Bank pool configuration explained:");
System.out.println();
System.out.println("maximum-pool-size=20");
System.out.println(" At most 20 connections to PostgreSQL at any time.");
System.out.println();
System.out.println("minimum-idle=20 (same as max)");
System.out.println(" Pool always keeps 20 connections ready. No ramp-up delay.");
System.out.println();
System.out.println("connection-timeout=5000 (5 seconds)");
System.out.println(" If all 20 connections are busy, a thread waits max 5s.");
System.out.println(" After 5s: SQLTransientConnectionException.");
System.out.println();
System.out.println("max-lifetime=1200000 (20 minutes)");
System.out.println(" Each connection is replaced after 20 minutes.");
System.out.println(" Must be less than database wait_timeout (PostgreSQL: idle_in_transaction_session_timeout).");
System.out.println();
System.out.println("leak-detection-threshold=30000 (30 seconds)");
System.out.println(" If a connection is borrowed for 30+ seconds, HikariCP logs a warning.");
}
}
Expected output:
National Bank pool configuration explained:
maximum-pool-size=20
At most 20 connections to PostgreSQL at any time.
minimum-idle=20 (same as max)
Pool always keeps 20 connections ready. No ramp-up delay.
connection-timeout=5000 (5 seconds)
If all 20 connections are busy, a thread waits max 5s.
After 5s: SQLTransientConnectionException.
max-lifetime=1200000 (20 minutes)
Each connection is replaced after 20 minutes.
Must be less than database wait_timeout (PostgreSQL: idle_in_transaction_session_timeout).
leak-detection-threshold=30000 (30 seconds)
If a connection is borrowed for 30+ seconds, HikariCP logs a warning.
How do you choose the right maximumPoolSize?
The formula for optimal pool size is not "more is better." A database server can only handle a limited number of concurrent queries efficiently. Each connection uses a database backend process (PostgreSQL) or thread (MySQL), memory, and CPU. Beyond the optimal point, adding connections increases contention and makes the application slower.
The recommended starting formula from the HikariCP wiki is:
connections = (CPU cores * 2) + number of disk spindles
For a modern SSD-based database server with 4 cores, that gives: (4 * 2) + 1 = 9 connections. In practice, 10 to 20 is a good range for most applications.
package com.bank;
public class PoolSizeCalculator {
public static void main(String[] args) {
int dbCpuCores = 4;
int effectiveSpindles = 1; // SSD counts as 1
int optimalSize = (dbCpuCores * 2) + effectiveSpindles;
System.out.println("Database CPU cores: " + dbCpuCores);
System.out.println("Effective spindles (SSD=1): " + effectiveSpindles);
System.out.println("Optimal pool size: (" + dbCpuCores + " * 2) + " + effectiveSpindles + " = " + optimalSize);
System.out.println();
// Multiple app instances sharing the same database
int appInstances = 3;
int perInstancePool = optimalSize / appInstances;
System.out.println("With " + appInstances + " app instances:");
System.out.println(" Total DB connections: " + optimalSize);
System.out.println(" Per instance pool size: " + perInstancePool);
System.out.println();
System.out.println("Common mistake: setting maximumPoolSize=100");
System.out.println(" 100 concurrent queries fight for 4 CPU cores");
System.out.println(" Context switching wastes more time than queuing");
System.out.println(" Throughput decreases above ~10 connections");
}
}
Expected output:
Database CPU cores: 4
Effective spindles (SSD=1): 1
Optimal pool size: (4 * 2) + 1 = 9
With 3 app instances:
Total DB connections: 9
Per instance pool size: 3
Common mistake: setting maximumPoolSize=100
100 concurrent queries fight for 4 CPU cores
Context switching wastes more time than queuing
Throughput decreases above ~10 connections
How do you monitor HikariCP pool metrics in Spring Boot?
Spring Boot Actuator exposes HikariCP metrics automatically when you include the actuator dependency. The metrics are available at /actuator/metrics/hikaricp.* and are exported to Micrometer, which can forward them to Prometheus, Datadog, or CloudWatch.
The key metrics to monitor are: hikaricp.connections.active (connections currently in use), hikaricp.connections.idle (connections waiting for work), hikaricp.connections.pending (threads waiting for a connection), and hikaricp.connections.timeout (how many times a thread timed out waiting).
package com.bank.monitoring;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.HikariPoolMXBean;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
@Component
public class PoolMetricsPrinter implements CommandLineRunner {
private final DataSource dataSource;
public PoolMetricsPrinter(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void run(String... args) {
if (dataSource instanceof HikariDataSource hikariDs) {
HikariPoolMXBean pool = hikariDs.getHikariPoolMXBean();
System.out.println("Pool name: " + hikariDs.getPoolName());
System.out.println("Max pool size: " + hikariDs.getMaximumPoolSize());
System.out.println("Active connections: " + pool.getActiveConnections());
System.out.println("Idle connections: " + pool.getIdleConnections());
System.out.println("Total connections: " + pool.getTotalConnections());
System.out.println("Threads waiting: " + pool.getThreadsAwaitingConnection());
}
}
}
Expected output:
Pool name: NationalBankPool
Max pool size: 20
Active connections: 0
Idle connections: 20
Total connections: 20
Threads waiting: 0
What is a complete banking project with HikariCP pool monitoring?
This project simulates the National Bank of India account balance service with HikariCP monitoring. It uses Spring Boot 3.4, H2 database, and prints pool statistics after each batch of queries.
Project structure
pool-monitor-service/
├── pom.xml
└── src/
└── main/
├── java/
│ └── com/
│ └── bank/
│ ├── PoolMonitorApp.java
│ ├── model/
│ │ └── Account.java
│ ├── repository/
│ │ └── AccountRepository.java
│ └── service/
│ └── BalanceService.java
└── resources/
└── application.properties
pom.xml
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>
syn-kw"><parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-parentsyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>3.4.7syn-kw"></versionsyn-kw">>
syn-kw"></parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>pool-monitor-servicesyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>
syn-kw"><propertiessyn-kw">>
syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
syn-kw"></propertiessyn-kw">>
syn-kw"><dependenciessyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-data-jpasyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-actuatorsyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>com.h2databasesyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>h2syn-kw"></artifactIdsyn-kw">>
syn-kw"><scopesyn-kw">>runtimesyn-kw"></scopesyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"></dependenciessyn-kw">>
syn-kw"></projectsyn-kw">>
application.properties
spring.datasource.url=jdbc:h2:mem:nationalbank
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.hikari.maximum-pool-size=5
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.connection-timeout=3000
spring.datasource.hikari.max-lifetime=600000
spring.datasource.hikari.pool-name=NationalBankPool
spring.datasource.hikari.leak-detection-threshold=10000
spring.jpa.hibernate.ddl-auto=create-drop
management.endpoints.web.exposure.include=health,metrics
BalanceService.java
package com.bank.service;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.HikariPoolMXBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.sql.DataSource;
import java.math.BigDecimal;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@Service
public class BalanceService {
private final AccountRepository accountRepository;
private final DataSource dataSource;
public BalanceService(AccountRepository accountRepository, DataSource dataSource) {
this.accountRepository = accountRepository;
this.dataSource = dataSource;
}
@Transactional
public void seedAccounts() {
accountRepository.save(new Account("SAV2001", "Priya Sharma", new BigDecimal("50000.00"), "ACTIVE"));
accountRepository.save(new Account("SAV2002", "Rajesh Kumar", new BigDecimal("150000.00"), "ACTIVE"));
accountRepository.save(new Account("CUR3001", "Amit Patel", new BigDecimal("300000.00"), "ACTIVE"));
}
public void simulateConcurrentLookups(int threadCount) throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
printPoolStats("Before concurrent lookups");
for (int i = 0; i < threadCount; i++) {
executor.submit(() -> {
var accounts = accountRepository.findAll();
System.out.println(Thread.currentThread().getName() +
" fetched " + accounts.size() + " accounts");
});
}
executor.shutdown();
executor.awaitTermination(10, TimeUnit.SECONDS);
printPoolStats("After concurrent lookups");
}
private void printPoolStats(String label) {
if (dataSource instanceof HikariDataSource hikariDs) {
HikariPoolMXBean pool = hikariDs.getHikariPoolMXBean();
System.out.println("[" + label + "]");
System.out.println(" Active: " + pool.getActiveConnections());
System.out.println(" Idle: " + pool.getIdleConnections());
System.out.println(" Total: " + pool.getTotalConnections());
System.out.println(" Waiting: " + pool.getThreadsAwaitingConnection());
}
}
}
PoolMonitorApp.java
package com.bank;
import com.bank.service.BalanceService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class PoolMonitorApp {
public static void main(String[] args) {
SpringApplication.run(PoolMonitorApp.class, args);
}
@Bean
CommandLineRunner demo(BalanceService balanceService) {
return args -> {
balanceService.seedAccounts();
System.out.println("Seeded 3 accounts.");
System.out.println();
balanceService.simulateConcurrentLookups(8);
};
}
}
Expected output:
Seeded 3 accounts.
[Before concurrent lookups]
Active: 0
Idle: 5
Total: 5
Waiting: 0
pool-1-thread-1 fetched 3 accounts
pool-1-thread-2 fetched 3 accounts
pool-1-thread-3 fetched 3 accounts
pool-1-thread-4 fetched 3 accounts
pool-1-thread-5 fetched 3 accounts
pool-1-thread-6 fetched 3 accounts
pool-1-thread-7 fetched 3 accounts
pool-1-thread-8 fetched 3 accounts
[After concurrent lookups]
Active: 0
Idle: 5
Total: 5
Waiting: 0
How is HikariCP different from other connection pools?
| Feature | HikariCP | Apache DBCP2 | Tomcat JDBC Pool |
|---|---|---|---|
| Speed | Fastest (lock-free ConcurrentBag) | Slower (GenericObjectPool with locks) | Medium |
| Memory | Smallest footprint (~130KB) | Larger (~500KB) | Medium (~300KB) |
| Connection validation | On borrow, configurable | On borrow/return/idle | On borrow/return/idle |
| Leak detection | Built-in (leakDetectionThreshold) | Separate AbandonedConfig | removeAbandoned flag |
| JMX monitoring | Built-in | Built-in | Built-in |
| Spring Boot default | Yes (since Spring Boot 2.0) | No (was default in Spring Boot 1.x) | No |
| Statement caching | Delegates to JDBC driver | Built-in PooledConnection | Built-in StatementCache |
| Proxy overhead | Zero-overhead bytecode proxy | Standard Java reflection proxy | Standard interceptor chain |
package com.bank;
public class PoolComparison {
public static void main(String[] args) {
System.out.println("Connection pool comparison for National Bank:");
System.out.println();
System.out.println("HikariCP (Spring Boot default):");
System.out.println(" getConnection() benchmark: ~250ns");
System.out.println(" Uses ConcurrentBag (lock-free)");
System.out.println(" Proxy: zero-overhead bytecode generation");
System.out.println();
System.out.println("Apache DBCP2:");
System.out.println(" getConnection() benchmark: ~3,500ns");
System.out.println(" Uses GenericObjectPool (synchronized blocks)");
System.out.println(" Proxy: standard Java reflection");
System.out.println();
System.out.println("Tomcat JDBC Pool:");
System.out.println(" getConnection() benchmark: ~1,200ns");
System.out.println(" Uses FairBlockingQueue");
System.out.println(" Proxy: interceptor chain");
System.out.println();
System.out.println("Verdict: HikariCP is 5-14x faster for getConnection()");
}
}
Expected output:
Connection pool comparison for National Bank:
HikariCP (Spring Boot default):
getConnection() benchmark: ~250ns
Uses ConcurrentBag (lock-free)
Proxy: zero-overhead bytecode generation
Apache DBCP2:
getConnection() benchmark: ~3,500ns
Uses GenericObjectPool (synchronized blocks)
Proxy: standard Java reflection
Tomcat JDBC Pool:
getConnection() benchmark: ~1,200ns
Uses FairBlockingQueue
Proxy: interceptor chain
Verdict: HikariCP is 5-14x faster for getConnection()
What are common mistakes when configuring HikariCP?
Wrong: maximumPoolSize too large
package com.bank;
public class WrongPoolSize {
public static void main(String[] args) {
// WRONG: database has 4 CPU cores, but pool size is 200
System.out.println("WRONG configuration:");
System.out.println(" spring.datasource.hikari.maximum-pool-size=200");
System.out.println();
System.out.println("What happens:");
System.out.println(" 1. 200 connections compete for 4 CPU cores on the database");
System.out.println(" 2. Each query takes longer due to context switching");
System.out.println(" 3. Database memory usage: 200 * ~10MB = 2GB just for connections");
System.out.println(" 4. Total throughput DECREASES despite more connections");
System.out.println(" 5. Other applications sharing the database get starved");
}
}
Expected output:
WRONG configuration:
spring.datasource.hikari.maximum-pool-size=200
What happens:
1. 200 connections compete for 4 CPU cores on the database
2. Each query takes longer due to context switching
3. Database memory usage: 200 * ~10MB = 2GB just for connections
4. Total throughput DECREASES despite more connections
5. Other applications sharing the database get starved
Correct: size the pool based on database capacity
package com.bank;
public class CorrectPoolSize {
public static void main(String[] args) {
System.out.println("CORRECT configuration:");
System.out.println(" spring.datasource.hikari.maximum-pool-size=10");
System.out.println();
System.out.println("Why 10 works:");
System.out.println(" Formula: (CPU cores * 2) + spindles = (4 * 2) + 1 = 9");
System.out.println(" Round up to 10 for headroom");
System.out.println(" With 3 app instances: total 30 connections, still manageable");
System.out.println();
System.out.println(" Database memory: 10 * ~10MB = 100MB (per instance)");
System.out.println(" Queries run without context-switch overhead");
System.out.println(" Throughput is optimal for the hardware");
}
}
Expected output:
CORRECT configuration:
spring.datasource.hikari.maximum-pool-size=10
Why 10 works:
Formula: (CPU cores * 2) + spindles = (4 * 2) + 1 = 9
Round up to 10 for headroom
With 3 app instances: total 30 connections, still manageable
Database memory: 10 * ~10MB = 100MB (per instance)
Queries run without context-switch overhead
Throughput is optimal for the hardware
Wrong: maxLifetime greater than database timeout
package com.bank;
public class WrongMaxLifetime {
public static void main(String[] args) {
// WRONG: HikariCP maxLifetime is 60 minutes,
// but PostgreSQL idle_in_transaction_session_timeout is 30 minutes
System.out.println("WRONG configuration:");
System.out.println(" spring.datasource.hikari.max-lifetime=3600000 (60 min)");
System.out.println(" PostgreSQL: idle_in_transaction_session_timeout=1800000 (30 min)");
System.out.println();
System.out.println("What happens:");
System.out.println(" 1. Connection sits idle for 35 minutes");
System.out.println(" 2. PostgreSQL kills the connection server-side");
System.out.println(" 3. HikariCP does not know the connection is dead");
System.out.println(" 4. Next query on that connection fails with: Connection is closed");
System.out.println();
System.out.println("CORRECT: set max-lifetime to LESS than the database timeout");
System.out.println(" spring.datasource.hikari.max-lifetime=1500000 (25 min)");
}
}
Expected output:
WRONG configuration:
spring.datasource.hikari.max-lifetime=3600000 (60 min)
PostgreSQL: idle_in_transaction_session_timeout=1800000 (30 min)
What happens:
1. Connection sits idle for 35 minutes
2. PostgreSQL kills the connection server-side
3. HikariCP does not know the connection is dead
4. Next query on that connection fails with: Connection is closed
CORRECT: set max-lifetime to LESS than the database timeout
spring.datasource.hikari.max-lifetime=1500000 (25 min)
What should a senior or principal engineer know?
At the senior level, you should be able to size the pool correctly for your infrastructure, configure leak detection, and read HikariCP metrics in production. You should know that the pool size should be calculated based on the database server capacity, not the application load. Adding more connections does not fix slow queries.
At the principal level, you need to think about:
- Multi-datasource configuration: when your banking app connects to both the accounts database and the audit database, each HikariCP pool is independent. Total database connections = sum of all pools across all instances.
- Connection validation: set keepaliveTime to a value less than your network firewall's TCP idle timeout. Cloud load balancers (AWS ALB, Azure LB) often close idle TCP connections after 350 seconds.
- Statement caching: HikariCP does not cache prepared statements itself; it relies on the JDBC driver. For PostgreSQL, set preparedStatementCacheQueries=256 in the connection URL.
- Monitoring and alerting: alert on hikaricp.connections.pending > 0 for more than 30 seconds (threads are waiting for connections). Alert on hikaricp.connections.timeout count increasing.
- Connection pool per microservice: each microservice in the banking platform gets its own pool. A shared database with 5 microservices, each with pool size 10, means 50 total connections to the database.
package com.bank.config;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
@Configuration
public class MultiDataSourceConfig {
@Primary
@Bean(name = "accountsDataSource")
@ConfigurationProperties(prefix = "spring.datasource.accounts")
public DataSource accountsDataSource() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
@Bean(name = "auditDataSource")
@ConfigurationProperties(prefix = "spring.datasource.audit")
public DataSource auditDataSource() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
}
package com.bank;
public class MultiPoolSummary {
public static void main(String[] args) {
System.out.println("National Bank multi-datasource pool planning:");
System.out.println();
System.out.println("Accounts DB (PostgreSQL, 8 cores):");
System.out.println(" Optimal pool per instance: (8*2)+1 = 17");
System.out.println(" 4 instances: 17 * 4 = 68 total connections");
System.out.println();
System.out.println("Audit DB (MySQL, 4 cores):");
System.out.println(" Optimal pool per instance: (4*2)+1 = 9");
System.out.println(" 4 instances: 9 * 4 = 36 total connections");
System.out.println();
System.out.println("Total database connections: 68 + 36 = 104");
System.out.println("Monitor: pg_stat_activity (PostgreSQL), SHOW PROCESSLIST (MySQL)");
}
}
Expected output:
National Bank multi-datasource pool planning:
Accounts DB (PostgreSQL, 8 cores):
Optimal pool per instance: (8*2)+1 = 17
4 instances: 17 * 4 = 68 total connections
Audit DB (MySQL, 4 cores):
Optimal pool per instance: (4*2)+1 = 9
4 instances: 9 * 4 = 36 total connections
Total database connections: 68 + 36 = 104
Monitor: pg_stat_activity (PostgreSQL), SHOW PROCESSLIST (MySQL)
What are common interview follow-up questions?
- What happens if you set maximumPoolSize to 1? (Every database request is serialized. Only one query runs at a time. All other threads wait in the queue. This is useful for testing concurrency bugs but never for production.)
- Can you change pool size at runtime? (Yes. HikariCP supports dynamic pool sizing through the HikariConfigMXBean JMX interface. You can call setMaximumPoolSize() without restarting the application.)
- What is the difference between connectionTimeout and idleTimeout? (connectionTimeout is how long a thread waits for a connection from the pool. idleTimeout is how long an unused connection stays in the pool before being removed.)
- How does HikariCP detect a dead connection? (It validates connections before handing them to your code. By default, it runs a lightweight JDBC isValid() check. You can also set a connectionTestQuery for databases that do not support isValid().)
- Should you use connection pooling with reactive/R2DBC? (No. R2DBC uses a non-blocking connection pool like r2dbc-pool, not HikariCP. HikariCP is for blocking JDBC only.)
- What is the relationship between Hibernate and HikariCP? (Hibernate uses JDBC connections. Spring Boot configures Hibernate to get connections from HikariCP. Hibernate requests a connection, runs queries, and returns it to the pool.)
Visual Overview
HikariCP Connection Pool Lifecycle
====================================
┌───────────────────────────────────┐
│ Application Thread │
│ accountRepository.findById(1) │
└──────────┬────────────────────────┘
│ getConnection()
▼
┌───────────────────────────────────┐
│ HikariCP Pool │
│ (NationalBankPool, max=20) │
│ │
│ Step 1: Check thread-local cache │
│ Step 2: Scan ConcurrentBag │
│ Step 3: Create new if below max │
│ Step 4: Wait if pool is full │
└──────────┬────────────────────────┘
│ Connection returned
▼
┌───────────────────────────────────┐
│ JDBC Connection │
│ (ProxyConnection wrapping real) │
│ │
│ Thread runs SQL query │
└──────────┬────────────────────────┘
│ connection.close()
│ (intercepted by HikariCP)
▼
┌───────────────────────────────────┐
│ HikariCP Pool │
│ │
│ Marks connection as NOT_IN_USE │
│ Connection stays open for reuse │
└───────────────────────────────────┘
Pool States
============
┌──────────┐ borrow ┌──────────┐
│ NOT_IN │ ──────────> │ IN_USE │
│ _USE │ │ │
│ (idle) │ <────────── │ (active) │
└──────────┘ return └──────────┘
│ │
│ maxLifetime │ leakDetection
│ exceeded │ threshold
▼ ▼
┌──────────┐ ┌──────────┐
│ REMOVED │ │ WARNING │
│ (closed) │ │ (logged) │
└──────────┘ └──────────┘
Key Takeaway
HikariCP is the default connection pool in Spring Boot, and it exists because opening a new database connection for every query is expensive. A TCP handshake, TLS negotiation, and database authentication can take 20 to 50 milliseconds. Multiply that by thousands of requests per second, and the overhead becomes a bottleneck. HikariCP keeps a pool of pre-opened connections that your application borrows and returns, reducing per-query overhead to fractions of a millisecond.
The most important configuration property is maximumPoolSize. It is not a tuning knob you set to a large number. The optimal size depends on the database server's CPU cores and storage type: (cores * 2) + spindles. For a 4-core database with SSD, that is roughly 9 to 10 connections. Adding more connections beyond this point increases contention and reduces throughput. When multiple application instances share a database, divide the optimal total by the number of instances.
In our National Bank of India pool-monitor-service, we configured a pool of 5 connections and simulated 8 concurrent threads fetching accounts. HikariCP queued the extra 3 threads and served them as connections became available. We printed pool metrics showing active, idle, total, and waiting counts. In production, you monitor these metrics through Spring Boot Actuator and Micrometer, alerting on pending connections and timeout counts.
At the senior level, know that maxLifetime must be shorter than the database's idle connection timeout, and that leak detection (leakDetectionThreshold) helps catch code paths that hold connections too long. At the principal level, plan connection budgets across all microservices, configure keepaliveTime to survive cloud load balancer idle timeouts, and use multi-datasource configurations when your service connects to more than one database.
Remember one sentence: HikariCP keeps a fixed pool of reusable database connections, and the right pool size is determined by the database server's CPU cores, not by how many requests your application handles.
---