Analyzing the Time Cost of Establishing MySQL Database Connections in Java Web Applications
This article examines how a MySQL connection is created from a Java web application, breaking down the TCP handshake, authentication, and variable‑setting steps with Wireshark captures, measuring latency, and demonstrating why connection pooling is essential to avoid hundreds of milliseconds of overhead per request.
The article investigates the detailed latency involved in establishing a MySQL database connection from a Java web application, using Wireshark packet captures to break down the TCP three‑handshake, authentication, and variable‑setting phases.
Initial simple Java code demonstrates loading the driver, setting credentials, and calling DriverManager.getConnection , after which the process is captured with Wireshark, revealing that the MySQL protocol runs over TCP and requires at least seven round‑trips before the connection is ready.
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);
// program ends, connection forced closedMeasurements show a minimum connection time of about 225 ms in a test where the program terminates abruptly, and about 183 ms when the connection is properly closed with Connection.close() .
747.284311 - 747.100954 = 0.183357s = 183.357msExtrapolating to a site with 100 000 daily requests and an estimated 150 ms per connection yields roughly 4 hours of CPU time spent solely on establishing connections, underscoring the necessity of connection pooling and other optimizations such as caching, prepared statements, and load balancing.
Finally, the article provides additional Java examples for proper connection closure and discusses the TCP four‑handshake termination sequence.
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();Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.