Analyzing MySQL Database Connection Latency in Java Applications
This article investigates the time cost of establishing and closing a MySQL connection from a Java web application, using Wireshark packet captures and simple code examples to quantify latency and illustrate why connection pooling is essential for high‑traffic services.
The author explores the detailed process of connecting to a MySQL database from a Java web application, aiming to quantify how much time each step of the connection consumes.
Two minimal Java snippets are presented: the first creates a connection without closing it, and the second creates a connection and explicitly calls Connection.close() before termination.
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 closed 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();Using Wireshark, the author captures the TCP three‑handshake, MySQL handshake, authentication packet exchange, and the subsequent data interactions, noting that the MySQL protocol runs over TCP and is binary rather than HTTP.
The connection establishment involves three main steps:
Step 1: TCP three‑way handshake.
Step 2: Server sends a handshake packet, client responds.
Step 3: Client sends an authentication packet; after successful verification the server replies with OK and the session proceeds.
After authentication, additional configuration packets (character set, autocommit, etc.) are exchanged before any SQL statements are executed.
Timing measurements show that the simplest connection (without explicit close) takes about 0.225243 s (225.243 ms) , while a connection that is properly closed takes about 0.183357 s (183.357 ms) . Both figures illustrate that a single connection can consume roughly 200 ms.
Extrapolating to a site with 20 000 daily active users, each making five requests, the author calculates that 100 000 connections per day would spend around 4 hours solely on establishing connections, underscoring the necessity of connection pooling.
The article concludes that frequent creation of database connections is costly; using a connection pool, caching, SQL pre‑compilation, and load balancing are recommended strategies to mitigate the overhead.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
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.