CodexBloom - Programming Q&A Platform

How to properly handle database connection pooling with HikariCP in a Spring Boot application?

👀 Views: 1 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
spring-boot hikaricp database connection-pooling Java

I need some guidance on Hey everyone, I'm running into an issue that's driving me crazy... I'm stuck on something that should probably be simple... I'm working on a Spring Boot application using HikariCP for database connection pooling, but I'm experiencing unexpected connection timeouts and intermittent SQLExceptions. I've configured my `application.properties` as follows: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=password spring.datasource.hikari.maximum-pool-size=10 spring.datasource.hikari.minimum-idle=5 spring.datasource.hikari.connection-timeout=30000 ``` Even with these settings, I'm seeing logs like `org.springframework.jdbc.CannotAcquireTooManyConnectionsException: HikariPool-1 - Connection is not available, request timed out after 30000ms.` This occurs especially when the application is under load. I tried increasing the `maximum-pool-size` to 20, but it didn't resolve the scenario. I've also ensured that there are enough connections available in the MySQL database itself. I suspect that there might be a configuration scenario or that my application is not closing connections properly, leading to exhaustion of the connection pool. I've implemented a custom `DataSource` bean as such: ```java @Bean public DataSource dataSource() { HikariDataSource dataSource = new HikariDataSource(); dataSource.setJdbcUrl(environment.getProperty("spring.datasource.url")); dataSource.setUsername(environment.getProperty("spring.datasource.username")); dataSource.setPassword(environment.getProperty("spring.datasource.password")); dataSource.setMaximumPoolSize(Integer.parseInt(environment.getProperty("spring.datasource.hikari.maximum-pool-size"))); return dataSource; } ``` However, I still encounter the same timeout scenario. I've also checked my JPA configurations and found that the entities are being managed correctly. What could be causing these connection timeouts and how can I properly manage the connection pool to avoid this scenario during heavy loads? Any insights or best practices would be greatly appreciated. Am I missing something obvious? For context: I'm using Java on macOS. This is my first time working with Java 3.9. Am I missing something obvious?