Why opening a connection per query is slow
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A ShopLite page runs ten lookups and still takes seconds, while MySQL sits almost idle. The time goes into connecting and logging in again before every single query.
What happens when a connection opens
Opening a connection is the conversation between your program and the MySQL server that must finish before any SQL can run: network connect, handshake and encryption, login, and session setup.
DriverManager.getConnection returns only after the four steps below are finished. Example 1 times one open against one query.
Example 1 · Measure one connection open against one query
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class ConnectionCostDemo { static final String URL = System.getenv("DB_URL"); static final String USER = System.getenv("DB_USER"); static final String PASSWORD = System.getenv("DB_PASSWORD");
public static void main(String[] args) throws SQLException { // Warm-up: the first connection and query also load Java classes, a one-time cost try (Connection warm = DriverManager.getConnection(URL, USER, PASSWORD); Statement st = warm.createStatement()) { st.executeQuery("SELECT COUNT(*) FROM products").close(); }
long t0 = System.nanoTime(); try (Connection con = DriverManager.getConnection(URL, USER, PASSWORD)) { long t1 = System.nanoTime(); try (Statement st = con.createStatement(); ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM products")) { rs.next(); long t2 = System.nanoTime(); System.out.println("Products in the table: " + rs.getInt(1)); System.out.printf("Open a connection: %.1f ms%n", (t1 - t0) / 1_000_000.0); System.out.printf("Run one query: %.1f ms%n", (t2 - t1) / 1_000_000.0); } try (Statement st = con.createStatement(); ResultSet rs = st.executeQuery("SHOW SESSION STATUS LIKE 'Ssl_cipher'")) { rs.next(); System.out.println("Encrypted with: " + rs.getString(2)); } } }}Products in the table: 15 Open a connection: 28.5 ms Run one query: 1.5 ms Encrypted with: TLS_AES_128_GCM_SHA256
What this code does
- The warm-up block opens one connection and runs the query once, so the timing below does not include loading the driver classes, which happens only once per program.
- Opening the second connection took about 28 ms; the query on it took about 1.5 ms. The open was nearly 20 times slower than the actual work.
Ssl_cipheris a MySQL status value. It is not empty, so this connection did a full TLS handshake: encryption is part of the open cost.
Four steps happen, and each waits for a reply from the other side:
- Network: the driver opens a TCP connection to the server's port, usually 3306.
- Handshake and encryption: both sides agree on the protocol, and MySQL 8 sets up TLS encryption by default.
- Login: the server checks the user name and password.
- Session setup: the server creates a thread and memory for the session, then the driver sends its own setup statements (Connector/J 26.7 sends three, such as
SET autocommit=1).
So opening a connection costs tens of milliseconds, while a simple query by primary key often takes one or two. The numbers here come from one laptop with MySQL on the same machine; with the database on another computer every reply crosses the network, and opening gets slower still.
Order of execution
Order the steps of opening
Tap the steps in the order they happen when DriverManager.getConnection runs.
Timing 100 queries: new connection each versus one reused
Connection per query means every lookup opens a connection, runs one statement and closes the connection again. It is the easiest code to write, and the slowest to run.
Example 2 runs the same 100 lookups twice and times them: a new connection each time, then one connection reused.
Example 2 · 100 lookups: a new connection each time versus one connection
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;
public class HundredQueriesDemo { static final String URL = System.getenv("DB_URL"); static final String USER = System.getenv("DB_USER"); static final String PASSWORD = System.getenv("DB_PASSWORD"); static final String SQL = "SELECT stock FROM products WHERE product_id = ?";
// Style 1: a brand-new connection for every lookup static int stockWithNewConnection(int productId) throws SQLException { try (Connection con = DriverManager.getConnection(URL, USER, PASSWORD); PreparedStatement ps = con.prepareStatement(SQL)) { ps.setInt(1, productId); try (ResultSet rs = ps.executeQuery()) { rs.next(); return rs.getInt(1); } } }
// Style 2: the caller passes in one connection that stays open static int stockWithConnection(Connection con, int productId) throws SQLException { try (PreparedStatement ps = con.prepareStatement(SQL)) { ps.setInt(1, productId); try (ResultSet rs = ps.executeQuery()) { rs.next(); return rs.getInt(1); } } }
public static void main(String[] args) throws SQLException { stockWithNewConnection(1); // warm-up: load the driver classes once
long t0 = System.nanoTime(); int total1 = 0; for (int i = 0; i < 100; i++) { total1 += stockWithNewConnection(i % 15 + 1); } long t1 = System.nanoTime();
int total2 = 0; try (Connection con = DriverManager.getConnection(URL, USER, PASSWORD)) { for (int i = 0; i < 100; i++) { total2 += stockWithConnection(con, i % 15 + 1); } } long t2 = System.nanoTime();
System.out.println("Same answer both ways: " + (total1 == total2)); System.out.printf("100 lookups, new connection each: %5d ms%n", (t1 - t0) / 1_000_000); System.out.printf("100 lookups, one connection: %5d ms%n", (t2 - t1) / 1_000_000); }}Same answer both ways: true 100 lookups, new connection each: 2195 ms 100 lookups, one connection: 93 ms
What this code does
- Both loops run the same 100 queries and add up the same stock numbers, so the only difference is how connections are handled.
- With a new connection each time, about 2.1 of the 2.2 seconds went into opening and closing connections. Reusing one connection cut the time by more than 20 times.
- Your numbers will differ. With MySQL on another machine, every open pays for extra network round trips, so the gap usually grows.
The queries are identical, so the gap of about 2.2 seconds against under 0.1 seconds is pure connection cost. A web page that runs 10 queries for each visitor would spend most of its time logging in again and again.
One connection for the whole program is not the answer either: it runs one statement at a time, it must not be shared by several threads at once, and if the network drops it, every later query fails.
The pool idea: borrow, use, give back
A connection pool keeps a few database connections open and lends them out: code borrows one, runs its SQL and gives it back for the next caller. The slow open happens a few times, not once per query.
Example 3 is a toy pool with fake connections, so it runs without MySQL. Watch which connection each request gets.
Example 3 · A toy pool: borrow, use, give back
import java.util.ArrayDeque;import java.util.Deque;
// A stand-in for a real database connection, so the idea runs without MySQLclass FakeConnection { private final int number;
FakeConnection(int number) { this.number = number; }
int number() { return number; }}
// A simplified pool: real pools also handle threads, timeouts and broken connectionsclass ToyPool { private final Deque<FakeConnection> idle = new ArrayDeque<>(); private int opened = 0;
FakeConnection borrow() { FakeConnection con = idle.pollFirst(); if (con == null) { // nothing idle: open a new one (the slow part) opened++; con = new FakeConnection(opened); System.out.println(" (pool opened connection #" + opened + ")"); } return con; }
void giveBack(FakeConnection con) { idle.addFirst(con); }
int opened() { return opened; }}
public class ToyPoolDemo { public static void main(String[] args) { ToyPool pool = new ToyPool();
for (int request = 1; request <= 4; request++) { FakeConnection con = pool.borrow(); System.out.println("Request " + request + " uses connection #" + con.number()); pool.giveBack(con); }
System.out.println("Two requests at the same time:"); FakeConnection a = pool.borrow(); FakeConnection b = pool.borrow(); System.out.println("Request A uses #" + a.number() + ", request B uses #" + b.number()); pool.giveBack(a); pool.giveBack(b);
System.out.println("Connections opened for 6 requests: " + pool.opened()); }}(pool opened connection #1) Request 1 uses connection #1 Request 2 uses connection #1 Request 3 uses connection #1 Request 4 uses connection #1 Two requests at the same time: (pool opened connection #2) Request A uses #1, request B uses #2 Connections opened for 6 requests: 2
What this code does
borrow()takes an idle connection if there is one and opens a new one only when none is free.giveBack()keeps the connection open for the next borrower.- Four requests one after another all reuse connection #1. Only when two requests overlap does the pool need a second connection: 6 requests, 2 opens.
- This is a simplified model with fake connections. A real pool also handles many threads, waiting, timeouts and broken connections.
A pool tracks two kinds of connections. Idle connections are open and waiting in the pool. Active (in-use) connections are borrowed by some code right now. A borrow turns an idle connection into an active one, and giving it back turns it idle again.
Predict the output
Predict the toy pool
Example 3 gave connections back to ToyPool. How many does it open here?
close() on a pooled connection gives it back
A proxy is the wrapper a pool hands out in place of the real connection. It looks like a normal Connection, but its close() returns the real connection to the pool instead of closing it.
Example 4 shows a wrapper whose close() gives the connection back, and what happens if you use it afterwards.
Example 4 · close() gives the connection back to the pool
import java.util.ArrayDeque;import java.util.Deque;
class RealConnection { private final int number;
RealConnection(int number) { this.number = number; }
String run(String sql) { return "#" + number + " ran: " + sql; }
void reallyClose() { System.out.println(" (connection #" + number + " closed for real)"); }}
// What the pool hands out: a wrapper whose close() gives the real connection backclass PooledConnection implements AutoCloseable { private final RealConnection real; private final MiniPool pool; private boolean closed = false;
PooledConnection(RealConnection real, MiniPool pool) { this.real = real; this.pool = pool; }
String run(String sql) { if (closed) { throw new IllegalStateException("Connection is closed"); } return real.run(sql); }
@Override public void close() { if (!closed) { closed = true; pool.giveBack(real); // not real.reallyClose() } }}
class MiniPool { private final Deque<RealConnection> idle = new ArrayDeque<>(); private int opened = 0;
PooledConnection getConnection() { RealConnection real = idle.isEmpty() ? new RealConnection(++opened) : idle.pollFirst(); return new PooledConnection(real, this); }
void giveBack(RealConnection real) { idle.addFirst(real); System.out.println(" (connection back in the pool, idle now " + idle.size() + ")"); }
void shutdown() { while (!idle.isEmpty()) { idle.pollFirst().reallyClose(); } }}
public class PooledCloseDemo { public static void main(String[] args) { MiniPool pool = new MiniPool();
try (PooledConnection con = pool.getConnection()) { System.out.println(con.run("SELECT stock FROM products WHERE product_id = 1")); } // close() runs here
PooledConnection saved; try (PooledConnection con = pool.getConnection()) { System.out.println(con.run("SELECT COUNT(*) FROM orders")); saved = con; }
try { saved.run("SELECT 1"); } catch (IllegalStateException e) { System.out.println("Error: " + e.getMessage()); }
System.out.println("Application stopping:"); pool.shutdown(); }}#1 ran: SELECT stock FROM products WHERE product_id = 1 (connection back in the pool, idle now 1) #1 ran: SELECT COUNT(*) FROM orders (connection back in the pool, idle now 1) Error: Connection is closed Application stopping: (connection #1 closed for real)
What this code does
- The pool hands out a
PooledConnectionwrapper. try-with-resources calls itsclose(), which returns the real connection to the pool instead of closing it. - The second block gets the same real connection #1. The wrapper
savedis closed, so using it again throws, even though connection #1 itself is still open. - Real network connections close only when the pool shuts down, as the last line shows.
Pooled code looks exactly like the JDBC code you already write: try (Connection con = ...) and nothing else. Closing is still your job. A connection you never close is never given back. That is a leak: the pool slowly runs out of connections and the app freezes.
After close(), the proxy is dead even though the real connection lives on. HikariCP, the pool used later in this module, throws java.sql.SQLException: Connection is closed if you use it again. Calling close() a second time is safe and does nothing.
Find the bug
Find the leaking line
Each method borrows from a pool. Find the line that is wrong.
This method counts the orders of one customer.
Round 1 of 2A pool also limits how many connections hit the database
The maximum pool size is the most connections a pool will ever open. When all of them are borrowed, the next caller waits for one to come back, and gets an error if none is free in time.
Example 5 gives a toy pool a maximum of 2 connections, then asks for a third.
Example 5 · A full pool makes the next caller wait, then fail
import java.util.ArrayDeque;import java.util.Deque;
class PoolExhaustedException extends RuntimeException { PoolExhaustedException(String message) { super(message); }}
// A simplified pool with a maximum size and a waiting timeclass LimitedPool { private final int maxSize; private final long timeoutMillis; private final Deque<Integer> idle = new ArrayDeque<>(); private int opened = 0;
LimitedPool(int maxSize, long timeoutMillis) { this.maxSize = maxSize; this.timeoutMillis = timeoutMillis; }
synchronized int borrow() throws InterruptedException { long deadline = System.currentTimeMillis() + timeoutMillis; while (idle.isEmpty() && opened == maxSize) { // all connections are busy long left = deadline - System.currentTimeMillis(); if (left <= 0) { throw new PoolExhaustedException("No free connection after " + timeoutMillis + " ms (max " + maxSize + ", all in use)"); } wait(left); // sleep until giveBack() or timeout } return idle.isEmpty() ? ++opened : idle.pollFirst(); }
synchronized void giveBack(int con) { idle.addFirst(con); notifyAll(); }
synchronized int opened() { return opened; }}
public class PoolLimitDemo { public static void main(String[] args) throws InterruptedException { LimitedPool pool = new LimitedPool(2, 300);
int a = pool.borrow(); int b = pool.borrow(); System.out.println("Borrowed #" + a + " and #" + b);
try { pool.borrow(); } catch (PoolExhaustedException e) { System.out.println("Third borrow failed: " + e.getMessage()); }
pool.giveBack(a); int c = pool.borrow(); System.out.println("After one was given back, borrowed #" + c); System.out.println("Connections ever opened: " + pool.opened()); }}Borrowed #1 and #2 Third borrow failed: No free connection after 300 ms (max 2, all in use) After one was given back, borrowed #1 Connections ever opened: 2
What this code does
- With a maximum of 2, the third
borrow()cannot open another connection. It waits up to 300 ms for agiveBack(), then throws. wait(left)sleeps until another thread callsnotifyAll()ingiveBack(), or until the time runs out. Here nobody gives one back in time, so the borrow fails.- After
giveBack(a), borrowing works again and reuses #1. The pool never opened more than 2 connections, whatever the callers did.
The limit protects the database. Each MySQL connection uses a server thread and memory, and the server accepts at most max_connections of them (151 by default). Without a pool, a rush of users, such as a college website on results day, opens one connection per request until MySQL refuses new ones with error 1040, Too many connections.
With a pool of 10, the app can never hold more than 10. Extra requests queue for a few milliseconds instead of overloading the server. If several copies of the app run, their pool sizes added together must stay below max_connections.
Next step
Check your understanding
12 quick questions