We have a service in Java 17 which executes logic on our end sends request to a third party system. The response time from the third party system is around 800-1400ms. We have a ThreadPoolExecutor for this with a size of 12 (cannot further increase it due to infrastructure limitations)
Our request sending rate was 5-8 requests/S due to the response time of the 3rd party system. To increase throughput we are upgrading to Java 21 to use Virtual Threads. However, during development testing there seems to be another issue being faced.
Our request sending rate has increased to around 50 requests/s. But we are facing Exceptions related to JDBC connection request failure. My db connection pool size must be around 100.
When my service starts there are 10 connections belonging to my microservice. When sending requests using ThreadPoolExecutor: 13 additional connections so total 23. When using newVirtualThreadPerTaskExecutor: total of 94 connections
I use the following query to monitor my PostGre Database V13.9
SELECT pid, datname, usename, application_name, client_addr, client_port, backend_start, query_start, state_change, query, state
FROM pg_stat_activity where application_name ='PostgreSQL JDBC Driver';
Exceptions:
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:466) ~[spring-orm-6.1.2.jar:6.1.2]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.startTransaction(AbstractPlatformTransactionManager.java:531) ~[spring-tx-6.1.2.jar:6.1.2]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:405) ~[spring-tx-6.1.2.jar:6.1.2]
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:610) ~[spring-tx-6.1.2.jar:6.1.2]
at java.base/java.util.concurrent.ThreadPerTaskExecutor$TaskRunner.run(ThreadPerTaskExecutor.java:314) ~[na:na]
at java.base/java.lang.VirtualThread.run(VirtualThread.java:309) ~[na:na]
Caused by: org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection [FATAL: remaining connection slots are reserved for non-replication superuser connections] [n/a]
at java.base/java.util.concurrent.ThreadPerTaskExecutor$TaskRunner.run(ThreadPerTaskExecutor.java:314) ~[na:na]
at java.base/java.lang.VirtualThread.run(VirtualThread.java:309) ~[na:na]
Caused by: org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection [FATAL: remaining connection slots are reserved for non-replication superuser connections] [n/a]
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:63) ~[hibernate-core-6.4.1.Final.jar:6.4.1.Final]
What I understand is when using ThreadPoolExecutor of 12 threads, each thread makes an connection and uses that. When using Virtual Threads, as soon as any Virtual Thread gets busy in response waiting, or Thread.sleep, another Virtual Thread takes lead. As soon as I initiate a load test, I notice a burst of connections, some resulting in exceptions (For example 11 requests failed out of 1500 (due to JDBC error)), and then the process going forward moves smoothly utilising the max 94 connections currently that I have.
Question is, how do I resolve this, and limit the number of processes initiated at a time. And more importantly, limit the number of connections/resuse connections created to the database. I have multiple other applications to the database, so will not be able to increase them much.
I have tried using System property "jdk.virtualThreadScheduler.maxPoolSize" by passing the VM Arugment -Djdk.virtualThreadScheduler.maxPoolSize=5
But the exception still occurs even if set -Djdk.virtualThreadScheduler.maxPoolSize=1
What am I missing? Is it that Virtual Threads should be used for basic I/O tasks, CPU tasks, rather than communications with Third Party Systems?
Some code of how my Virtual Threads are initiated:
this.executorService = Executors.newSingleThreadScheduledExecutor();
this.taskExecutorService = Executors.newVirtualThreadPerTaskExecutor();
this.executorService.scheduleAtFixedRate(this, 0L, this.pollingTime.toMillis(), TimeUnit.MILLISECONDS); //Called once when service starts
public void run() {
this.taskExecutorService.execute(//my runnable job);
}
I also tried using counters/semaphores to restrict Virtual Threads. It reduces throughput but it still creates new connections more compared to the ThreadPoolExecutor. Is it designed this way? I suspect each virtual thread / process creates a new connection, whereas in ThreadPoolExecutor it utilises the connection allocated to its PID. Any clarification or suggestions please?
Edit: (JDBC Connection Code) I see most delete queries in open connections, as that is what is executed when sending requests via virtual threads. Following is the code.
public Optional<Job> getNextJob(String queue) {
Optional<Job> job = Optional.empty();
try {
Connection connection = this.dataSource.getConnection();
try {
String sql = "DELETE FROM scheduler_task WHERE id = (SELECT id FROM scheduler_task WHERE queue = ? and trigger_date < now() LIMIT 1 FOR UPDATE SKIP LOCKED) RETURNING id, queue, reference_id, trigger_date";
PreparedStatement stmt = connection.prepareStatement(sql);
try {
ResultSet resultSet = stmt.executeQuery();
try {
if (resultSet.next()) {
job = Optional.of(this.mapToJob(resultSet));
}
} catch (Throwable var14) {
if (resultSet != null) {
try {
resultSet.close();
} catch (Throwable var13) {
var14.addSuppressed(var13);
}
}
throw var14;
}
if (resultSet != null) {
resultSet.close();
}
} catch (Throwable var15) {
if (stmt != null) {
try {
stmt.close();
} catch (Throwable var12) {
var15.addSuppressed(var12);
}
}
throw var15;
}
if (stmt != null) {
stmt.close();
}
} catch (Throwable var16) {
if (connection != null) {
try {
connection.close();
} catch (Throwable var11) {
var16.addSuppressed(var11);
}
}
throw var16;
}
if (connection != null) {
connection.close();
}
return job;
} catch (SQLException var17) {
log.error("error", var17);
throw new Exception(var17);
}
}
Are you using Hikari to access the database? It comes by default with Spring Boot Data. If so, there's an issue with it
https://github.com/brettwooldridge/HikariCP/issues/2151
What happens, basically, is that once created, the connection stays in the ThreadLocal storage. When using a thread pool, the first time a thread accesses the database, it creates a connection and stores it in the ThreadLocal space of its thread. If this thread is reused, as is the case of a Thread Pool, the connection is already there and it's reused. However, when working with virtual threads, threads are created and destroyed continuously, so their ThreadLocal space is cleared and so, connections are created and destroyed once per task. In your case, if you have 1000 threads trying to access the database, they may try to create 1000 connections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With