Connection pools and their limits
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)On sale day ShopLite auto-scales from 4 to 20 servers, and users suddenly see "Connection is not available" while MySQL is almost idle. Where did the connections go?
Your turn: sale day, 20 servers
Each ShopLite server keeps some connections open to MySQL and lends them to requests. On sale day 20 servers start, and MySQL allows 151 connections in total. Think about three questions:
- Why not open a fresh connection for every request? What does it cost, and who pays?
- If every server keeps 10 connections, how many does MySQL see, and does it fit?
- What would you check first when the pool runs dry but MySQL is almost idle?
Why a connection per request is slow
A connection pool is a set of already-open database connections that an app lends to requests and takes back after use, so no request pays the cost of opening its own.
Opening a connection means handshakes and a login before the first query. This program adds up the simplified costs for 1,000 requests.
Example 1 · What opening a connection per request costs
public class ConnectionCostDemo { // Simplified costs of opening a new MySQL connection over the network static final double TCP_HANDSHAKE_MS = 1.0; static final double TLS_HANDSHAKE_MS = 6.0; static final double LOGIN_AND_SETUP_MS = 8.0; static final double BORROW_FROM_POOL_MS = 0.05; static final double QUERY_MS = 2.0;
public static void main(String[] args) { double open = TCP_HANDSHAKE_MS + TLS_HANDSHAKE_MS + LOGIN_AND_SETUP_MS; int requests = 1_000;
double perRequestNew = open + QUERY_MS; double perRequestPool = BORROW_FROM_POOL_MS + QUERY_MS; System.out.printf("Open a new connection: %.1f ms + query %.1f ms = %.2f ms per request%n", open, QUERY_MS, perRequestNew); System.out.printf("Borrow from a pool: %.2f ms + query %.1f ms = %.2f ms per request%n", BORROW_FROM_POOL_MS, QUERY_MS, perRequestPool); System.out.printf("For %d requests: %.0f ms vs %.0f ms (%.1fx)%n", requests, perRequestNew * requests, perRequestPool * requests, perRequestNew / perRequestPool); }}Open a new connection: 15.0 ms + query 2.0 ms = 17.00 ms per request Borrow from a pool: 0.05 ms + query 2.0 ms = 2.05 ms per request For 1000 requests: 17000 ms vs 2050 ms (8.3x)
What this code does
- The handshake and login steps add 15 ms (simplified numbers) before a 2 ms query even starts.
- Borrowing an open connection from a pool costs a fraction of a millisecond, so 1,000 requests take about 8 times less time.
A database connection is a long-lived network link between the app and MySQL. Opening one needs a TCP handshake, usually a TLS handshake, then login, permission checks and session setup: several milliseconds, often more than the query itself.
If every request opens and closes its own connection, that cost is paid on every page view, and MySQL spends CPU creating and destroying sessions instead of running queries. A pool opens connections once and reuses them thousands of times.
Pool basics: size, idle connections and wait timeout
HikariCP is the connection pool Spring Boot uses by default; you set its maximum size, idle connections and wait timeout in application.properties.
A pool has a maximum size, some idle connections kept ready and a wait timeout. These are HikariCP's main settings, with their default values.
# most connections this server may openspring.datasource.hikari.maximum-pool-size=10# idle connections kept ready (default: same as the maximum)spring.datasource.hikari.minimum-idle=10# ms a request waits for a free connectionspring.datasource.hikari.connection-timeout=30000# ms before an extra idle connection is closedspring.datasource.hikari.idle-timeout=600000# ms before a connection is replaced with a fresh onespring.datasource.hikari.max-lifetime=1800000Example 2 · A tiny pool: open once, reuse many times
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.TimeUnit;
class FakeConnection { private static int opened = 0; final int id;
FakeConnection() { id = ++opened; System.out.println(" opened connection #" + id + " (slow, done once)"); }}
class SimplePool { private final BlockingQueue<FakeConnection> idle;
SimplePool(int size) { idle = new ArrayBlockingQueue<>(size); for (int i = 0; i < size; i++) { idle.add(new FakeConnection()); // opened up front, like minimum-idle } }
FakeConnection borrow(long timeoutMs) throws InterruptedException { FakeConnection c = idle.poll(timeoutMs, TimeUnit.MILLISECONDS); if (c == null) { throw new IllegalStateException("Connection is not available, request timed out after " + timeoutMs + "ms"); } return c; }
void giveBack(FakeConnection c) { idle.add(c); }}
public class SimplePoolDemo { public static void main(String[] args) throws InterruptedException { SimplePool pool = new SimplePool(3); for (int request = 1; request <= 6; request++) { FakeConnection c = pool.borrow(1_000); try { System.out.println("request " + request + " uses connection #" + c.id); } finally { pool.giveBack(c); // always return it, even after an error } } }}opened connection #1 (slow, done once) opened connection #2 (slow, done once) opened connection #3 (slow, done once) request 1 uses connection #1 request 2 uses connection #2 request 3 uses connection #3 request 4 uses connection #1 request 5 uses connection #2 request 6 uses connection #3
What this code does
- The pool opens three connections up front. Six requests then take turns with them; no request opens a new one.
borrowwaits up to a timeout withpoll, andgiveBackruns infinally, so a connection comes back even if the request throws.
Borrowing returns a connection quickly when one is free, and giving it back makes it available to the next request. Code must always give it back, which is what try-with-resources on a Connection does.
The maximum size is a hard limit. When every connection is borrowed, the next request waits up to connection-timeout (30 seconds by default) and then fails. The JDBC section used the same pool.
Simulating a full pool with a Semaphore
A Semaphore is a counter of permits: tryAcquire takes a permit if one is free (or waits up to a timeout), and release gives it back. A Semaphore with 5 permits behaves like a pool with 5 connections.
This program lets 20 users compete for 5 permits. Each holds one for 100 ms and gives up after waiting 250 ms.
Example 3 · 5 connections, 20 users, 250 ms timeout
import java.util.ArrayList;import java.util.List;import java.util.concurrent.Semaphore;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;
public class SemaphorePoolDemo { static final int POOL_SIZE = 5; static final int USERS = 20; static final long HOLD_MS = 100; static final long TIMEOUT_MS = 250;
public static void main(String[] args) throws InterruptedException { Semaphore pool = new Semaphore(POOL_SIZE, true); AtomicInteger servedAtOnce = new AtomicInteger(); AtomicInteger servedAfterWait = new AtomicInteger(); AtomicInteger timedOut = new AtomicInteger();
List<Thread> threads = new ArrayList<>(); for (int i = 0; i < USERS; i++) { Thread t = new Thread(() -> { long start = System.nanoTime(); try { if (!pool.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS)) { timedOut.incrementAndGet(); return; } try { long waitedMs = (System.nanoTime() - start) / 1_000_000; (waitedMs < 20 ? servedAtOnce : servedAfterWait).incrementAndGet(); Thread.sleep(HOLD_MS); } finally { pool.release(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); threads.add(t); t.start(); } for (Thread t : threads) { t.join(); } System.out.println("pool=" + POOL_SIZE + " users=" + USERS + " hold=" + HOLD_MS + "ms timeout=" + TIMEOUT_MS + "ms"); System.out.println("served at once: " + servedAtOnce.get()); System.out.println("served after wait: " + servedAfterWait.get()); System.out.println("timed out (errors): " + timedOut.get()); }}pool=5 users=20 hold=100ms timeout=250ms served at once: 5 served after wait: 10 timed out (errors): 5
What this code does
- The fair
Semaphorelets 5 users in at once; 10 more get a connection after waiting about 100 or 200 ms. - The last 5 would have to wait about 300 ms, longer than the 250 ms timeout, so they fail. Timing depends on your machine, so a busy computer can shift a user between groups.
When 20 requests arrive together and each holds a connection for 100 ms, 5 start at once, 5 more after 100 ms and 5 more after 200 ms. The last 5 would wait 300 ms, so they fail. In a real app those failures are errors such as HikariCP's "Connection is not available, request timed out", and the users see an error page.
Predict the output
Count the permits
Follow the permits and pick what is printed.
Round 1 of 3
Servers × pool size vs max_connections
max_connections is MySQL's limit on open connections from all clients together (151 by default); above it MySQL refuses new ones with ERROR 1040: Too many connections.
The database sees servers × pool size. This program checks fleets of 2 to 20 servers against MySQL's limit.
Example 4 · When the fleet's pools exceed max_connections
public class FleetConnectionsDemo { static final int MAX_CONNECTIONS = 151; // MySQL's default max_connections static final int RESERVED = 11; // admin tools, migrations, monitoring, replicas
public static void main(String[] args) { int poolSize = 10; // HikariCP's default maximum-pool-size int[] serverCounts = {2, 4, 8, 14, 20}; System.out.println("Servers | Pool | App connections | Limit for apps | Result"); for (int servers : serverCounts) { int total = servers * poolSize; int limit = MAX_CONNECTIONS - RESERVED; String result = total <= limit ? "OK" : "Too many connections"; System.out.printf("%7d | %4d | %15d | %14d | %s%n", servers, poolSize, total, limit, result); } int safePool = (MAX_CONNECTIONS - RESERVED) / 20; System.out.println("For 20 servers, keep each pool at most " + safePool + " connections"); }}Servers | Pool | App connections | Limit for apps | Result
2 | 10 | 20 | 140 | OK
4 | 10 | 40 | 140 | OK
8 | 10 | 80 | 140 | OK
14 | 10 | 140 | 140 | OK
20 | 10 | 200 | 140 | Too many connections
For 20 servers, keep each pool at most 7 connectionsWhat this code does
- With 11 connections reserved, apps may use 140 of MySQL's default 151. Up to 14 servers with pools of 10 fit.
- At 20 servers the pools ask for 200 connections. Keeping each pool at 7 makes 20 servers fit, or the database limit must be raised (which costs memory).
Each app server has its own pool, so MySQL sees the total: servers × pool size. Each connection also uses memory on the database server.
This bites when you scale out. Four servers with the default pool of 10 use 40 connections. Auto-scaling to 20 servers for a sale asks for 200, and new servers fail to start or fail requests. Plan the pool size from the largest fleet you expect, and keep some connections free for admin tools, migrations and monitoring.
Exhausted pool: symptoms and fixes
An exhausted pool is a pool whose connections are all borrowed, so new requests have to wait for one and fail if the wait timeout passes.
A payment call inside a transaction keeps the connection busy. This program compares holding it for 320 ms with holding it for 20 ms.
Example 5 · A slow call inside the transaction starves the pool
public class LongTransactionDemo { static long finishTimeMs(int requests, int poolSize, long holdMs) { long rounds = (requests + poolSize - 1) / poolSize; return rounds * holdMs; }
static long perSecond(int poolSize, long holdMs) { return poolSize * 1000L / holdMs; }
public static void main(String[] args) { int pool = 10; int requests = 200; long dbWork = 20; long paymentCall = 300;
long badHold = dbWork + paymentCall; long goodHold = dbWork; System.out.println("Checkout holding the connection during the payment call:"); System.out.println(" hold " + badHold + " ms, max " + perSecond(pool, badHold) + " checkouts/s, 200 checkouts take " + finishTimeMs(requests, pool, badHold) + " ms"); System.out.println("Checkout releasing it before the payment call:"); System.out.println(" hold " + goodHold + " ms, max " + perSecond(pool, goodHold) + " checkouts/s, 200 checkouts take " + finishTimeMs(requests, pool, goodHold) + " ms"); }}Checkout holding the connection during the payment call: hold 320 ms, max 31 checkouts/s, 200 checkouts take 6400 ms Checkout releasing it before the payment call: hold 20 ms, max 500 checkouts/s, 200 checkouts take 400 ms
What this code does
- With the payment call inside the transaction, each checkout holds a connection for 320 ms, so 10 connections handle only 31 checkouts a second.
- Moving the 300 ms call outside the transaction drops the hold to 20 ms: the same pool handles 500 checkouts a second.
Symptoms: response times jump to the connection timeout and errors such as "Connection is not available, request timed out" appear, while the database itself may be nearly idle. The usual cause is connections held too long, not too few connections: a transaction that calls a payment gateway, sends an email or waits for a user keeps its connection the whole time.
Do slow outside calls before or after the transaction, keep transactions short, and fix leaks (connections not returned on errors). A bigger pool is the last step: past a point it only moves the queue into MySQL. Connections busy on average ≈ requests per second × seconds each request holds one (Little's law): 400 requests/s × 0.025 s = 10 busy connections, but the same traffic holding 0.32 s needs 128.
Find the bug
Find the pool problem
Tap the line that starves or breaks the pool, then read the fix.
Give the connection back on every path.
Round 1 of 3Next step
Check your understanding
11 quick questions