Video in progress
On a high-load service, how do you design connection pool size, transaction length and Hibernate settings together?
The pool should be small: usually close to the database's core count, divided by the number of service instances. I keep transactions short, turn off open-in-view and make no external calls inside a transaction, otherwise the pool runs out at any size.
📖 Answer
Many teams see slowness and raise maximumPoolSize to 100. 20 pods × 100 = 2000 connections, and PostgreSQL opens a separate process for each connection. The result: the database itself slows down.
I start the math from the database. If the database has 16 cores, the number of queries it can run efficiently at once is roughly a few dozen. I divide that number among all the instances. When many services share one database, I put PgBouncer (transaction mode) in front.
Then I look at what holds the connection. A connection is busy from the start of the transaction to the end. So:
spring.jpa.open-in-view=false: otherwise the connection can stay busy for the whole HTTP request, including JSON serialization;- no HTTP, Kafka
get()or file upload inside a transaction; hibernate.connection.provider_disables_autocommit=trueandauto-commit: falsein Hikari: Hibernate can then delay acquiring the connection until the first SQL is actually needed.
spring:
datasource:
hikari:
maximum-pool-size: 12
connection-timeout: 2000 # failing fast beats waiting long
auto-commit: false
jpa:
open-in-view: false
properties:
hibernate.connection.provider_disables_autocommit: true
In monitoring I watch Hikari's pending and usage metrics. If pending is always above zero, the problem is not the pool size but code that holds connections too long. To find it, I temporarily turn on leak-detection-threshold.
Sign up to mark studied questions and save your progress.