Analyzing the Cost of Establishing MySQL Database Connections in Java Applications
This article examines the detailed steps and performance impact of creating a MySQL connection from a Java web application, measures the latency of the handshake and authentication using Wireshark, and demonstrates why connection pooling is essential for high‑traffic services.
The article investigates the details of establishing a database connection in web applications, using MySQL as an example and Java as the programming language, and quantifies the time cost of the connection process.
Sample Java code used for the test is shown below:
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);
// program ends, connection is forcibly closedWireshark captures reveal the MySQL protocol (built on TCP) and the three main steps of establishing a connection: (1) TCP three‑way handshake, (2) server sends handshake packet and client responds, (3) client sends authentication packet, server validates and returns OK.
Timing measurements from the capture show that the minimal connection setup takes 10.416042 - 10.190799 = 0.225243s = 225.243ms , i.e., about 225 ms.
When the connection is properly closed with conn.close(); , the total time from handshake to termination (excluding the final RST packet) is measured as 747.284311 - 747.100954 = 0.183357s = 183.357ms , roughly 183 ms.
Extrapolating to a site with 100 000 daily requests (assuming 150 ms per connection) yields 15 000 seconds, or about 4.17 hours spent solely on establishing connections, underscoring the necessity of a connection pool.
The article concludes that database connections are costly; frequent creation should be avoided, and techniques such as connection pooling, caching, prepared statements, and load balancing are recommended to improve performance.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.