Prevent SQL Server JDBC Connections from Hanging Forever

A firewall or load balancer can silently discard an idle TCP flow without sending a reset. If the Microsoft JDBC driver keeps its default infinite socket timeout, a read or connection check can wait indefinitely. Set a finite socketTimeout and coordinate it with statement and pool timeouts.

Last updated: October 8, 2026.

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

public final class DataSourceFactory {
    public static HikariDataSource create() {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(
            "jdbc:sqlserver://db.example.com:1433;" +
            "databaseName=app;encrypt=true;" +
            "loginTimeout=30;queryTimeout=30;" +
            "cancelQueryTimeout=10;socketTimeout=45000"
        );
        config.setValidationTimeout(5000);
        config.setConnectionTimeout(10000);
        config.setKeepaliveTime(120000);
        return new HikariDataSource(config);
    }
}

socketTimeout is measured in milliseconds; the other JDBC URL timeouts shown here are seconds. Choose values from the application service-level objective and confirm the units for every pool and driver property.

Use the timeout that covers network reads

loginTimeout bounds connection establishment. queryTimeout bounds a statement waiting for results, while cancelQueryTimeout limits the wait for cancellation acknowledgment. The driver-level socketTimeout applies to socket communication and closes the connection when the server stops replying.

Microsoft states in Understanding timeout properties that the default socketTimeout is zero, meaning an infinite wait. It recommends making it longer than the query and cancellation windows so a normal query cancellation can complete first.

Keep pool validation bounded and observable

A pool validation timeout is useful, but it should not be the only network safety control. Test failure by dropping packets without sending a TCP reset, then confirm that a borrowed connection fails within the intended limit and is evicted. Record pool active, idle, pending, and timeout metrics; alert before waiting threads exhaust the application server.

Do not automatically retry an ambiguous write unless the operation is idempotent or its outcome can be checked. A timeout may occur after SQL Server committed the change. The full property definitions are in Microsoft’s JDBC connection properties reference. Continue with encrypted SQL Server connections, certificate-chain troubleshooting, and preventing duplicate operations after timeouts.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov