Databases 6 min read

Analyzing the Time Cost of Establishing MySQL Database Connections in Java Applications

This article examines how a Java web application connects to a MySQL database, measuring each step of the TCP handshake, authentication, and setup with Wireshark, and demonstrates that a single connection can take over 200 ms, highlighting the importance of connection pooling.

Architect's Guide
Architect's Guide
Architect's Guide
Analyzing the Time Cost of Establishing MySQL Database Connections in Java Applications

The author investigates the details and performance cost of establishing a MySQL database connection from a Java web application, using Wireshark packet capture to break down the TCP three‑handshake, authentication, and configuration phases.

Below is the minimal Java code used for the test (five lines):

Class.forName("com.mysql.jdbc.Driver");

String name = "xttblog2";
String password = "123456";
String url = "jdbc:mysql://172.16.100.131:3306/xttblog2";
Connection conn = DriverManager.getConnection(url, name, password);
// after program ends, connection is forcibly closed

Wireshark analysis shows that establishing this connection consumes about 0.225243s = 225.243ms . The delay includes the TCP three‑handshake, the server’s handshake response, and the client’s authentication packet, totaling at least seven round‑trips between client and server.

When the connection is closed properly using Connection.close() , the following code is executed:

Class.forName("com.mysql.jdbc.Driver");

String name = "shine_user";
String password = "123";
String url = "jdbc:mysql://172.16.100.131:3306/clever_mg_test";
Connection conn = DriverManager.getConnection(url, name, password);
conn.close();

The measured time for a clean shutdown (including the TCP four‑handshake) is about 0.183357s = 183.357ms . The difference illustrates the overhead of both establishing and terminating a database connection.

Extrapolating these numbers to a site with 20,000 daily active users, each making five requests, the naive approach of opening a new connection per request would consume roughly 15,000 seconds (≈4.17 hours) per day solely on connection setup, not counting query execution.

Therefore, the core message is clear: database connections are expensive; developers should avoid frequent creation by employing connection pools and complementary techniques such as caching, SQL statement pre‑compilation, and load balancing.

JavaPerformanceMySQLconnection poolingdatabase-connection
Architect's Guide
Written by

Architect's Guide

Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.