TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท databases ยท sql ยท performance ยท java ยท spring

Connection pooling

Keeping a small set of open database connections that application threads borrow and return, so requests skip the expensive connection setup and the database is protected from more sessions than it can serve.

14 min6 animations

๐Ÿ“š Builds on๐Ÿ›’ Transactions and isolation

๐Ÿ–จ๏ธ Cheat sheet

A brand-new taxi every time

Ana is at the station and needs to get to the hotel. There's no taxi rank, so for every trip a brand-new taxi has to be found. It drives up, the driver checks the hotel's badge to be sure it's the real hotel, the driver gives the password, and the hotel sets up a parking bay and a helper just for that taxi.

Only then does the trip happen, and it takes a minute. Afterwards the taxi is sent away for good. The next rider starts all over again. Most of the time goes on getting a taxi, not on the ride. Each of those taxis is a connection.

Why opening a connection is expensive

A database connection is a long-lived network session between your application and the database server. Opening one costs far more than a typical short query:

  1. TCP handshake: one network round trip before any bytes flow.
  2. TLS handshake: more round trips, a certificate check and key exchange (if the connection is encrypted, as it should be).
  3. Authentication: the server checks credentials, for example with SCRAM-SHA-256 in PostgreSQL.
  4. Server-side session: PostgreSQL forks a whole backend process per connection; MySQL dedicates a thread. Each holds memory for buffers, caches and session state.

A query on an indexed key might take a millisecond; setting up the connection for it can take several, more across regions. Opening and closing a connection per request wastes that time on every request and churns processes on the server.

Opening a connection from scratch5 steps
๐ŸงRider Ana๐ŸจHotel
Press play and watch it happen!

The taxi rank

So the station sets up a taxi rank, which is a connection pool. When the day starts, a few taxis are found, signed in at the hotel, and left waiting at the rank with their engines running.

Ana walks up, takes the first free taxi, rides to the hotel and back, and the taxi returns to the rank. Nobody scraps it. Ben takes the next one. Taking a taxi now takes a second, because all the checks were done hours ago. The rank's marshal tidies each taxi when it comes back, so the next rider finds nothing left behind.

The pool: borrow and return

A connection pool opens connections up front and keeps them open. Code borrows one, uses it, and returns it; the physical connection survives for the next borrower.

In JDBC, the pool hides behind a DataSource. getConnection() hands out an idle pooled connection (no handshake), and close() on it returns it to the pool rather than closing the socket. On return, HikariCP rolls back uncommitted work (when auto-commit is off) and resets what the borrower changed through JDBC setters (auto-commit, isolation level, read-only, catalog, schema, network timeout). State set with SQL, such as SET search_path or temp tables, is not reset, so avoid it or undo it before close().

1HikariConfig config = new HikariConfig();2config.setJdbcUrl("jdbc:postgresql://db.internal:5432/orders");3config.setUsername("app");4config.setPassword(System.getenv("DB_PASSWORD"));5config.setMaximumPoolSize(10);6HikariDataSource dataSource = new HikariDataSource(config);   // one per app, shared7 8try (Connection conn = dataSource.getConnection();          // borrow9     PreparedStatement ps = conn.prepareStatement("SELECT name FROM customer WHERE id = ?")) {10    ps.setLong(1, id);11    try (ResultSet rs = ps.executeQuery()) {12        // ...13    }14}                                                            // close() returns it

HikariCP is Spring Boot's default pool: the JDBC and JPA starters bring it in, and Boot builds the DataSource from spring.datasource.*. Spring then borrows for you: JdbcTemplate borrows per call, and a transaction (@Transactional, see Spring transactions) holds one connection from begin to commit or rollback, since a transaction lives on a single connection.

Borrow and return4 steps
๐Ÿš Taxi rank๐ŸงRider Ana๐Ÿงโ€โ™‚๏ธRider Ben๐Ÿš•Taxi 1๐Ÿš•Taxi 2๐Ÿš•Taxi 3๐ŸจHotel
Press play and watch it happen!

All the taxis are out

The rank has only so many taxis. Ana asks hers to wait outside a shop while she browses for half an hour. Ben gets to the hotel and simply never sends his taxi back.

Now Cleo arrives and the rank is empty. She queues, but not forever: after a set time she gives up and goes home upset. That waiting limit is called the timeout. A good marshal also keeps a watch: if a taxi has been gone far too long, they write down who took it, so the station can find out why it never came back.

Pool exhaustion and timeouts

When every connection is checked out, getConnection() blocks. After connectionTimeout (HikariCP default 30 seconds) it throws:

1java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available,2request timed out after 30000ms (total=10, active=10, idle=0, waiting=24)

The usual causes aren't "too small a pool" but connections held too long:

  • Long transactions: a @Transactional method that calls a slow HTTP API, sends email or waits on a lock holds its connection the whole time. Do slow non-database work outside the transaction.
  • Leaks: code that borrows and never calls close() (no try-with-resources) loses a connection forever. leakDetectionThreshold (default 0, off; at least 2000 ms when on) logs a warning with the borrower's stack trace when a connection stays out longer than the threshold.
  • Nested borrowing: a thread holding one connection that asks for a second (for example a REQUIRES_NEW transaction) can deadlock the pool under load when every thread holds one and waits for another.

Prefer a short connectionTimeout (a few seconds) so requests fail fast instead of piling up, and watch the pool's metrics (with Actuator, Spring Boot publishes them through Micrometer as hikaricp.connections.active, .idle and .pending).

When the pool runs dry5 steps
๐Ÿš Taxi rank๐ŸงRider Ana๐Ÿงโ€โ™‚๏ธRider Ben๐Ÿงโ€โ™€๏ธRider Cleo๐Ÿš•Taxi 1๐Ÿš•Taxi 2๐ŸจHotel
Press play and watch it happen!

How many taxis?

The hotel sits on a narrow street with room for only so many taxis, and it has a handful of porters. More taxis than porters don't make anything faster: they just sit in the street, blocking each other. A short line of taxis that keep moving beats a traffic jam.

And the street is shared. If three stations each send forty taxis, the street fills up and the last ones are turned away. So each station keeps a small rank. When a crowd of riders turns up all at once, they queue calmly at the station, not in the hotel's street.

Sizing the pool

The database does useful work on only as many connections as it has CPU cores and disk I/O to serve; beyond that, extra connections add context switching, lock contention and memory. Small pools usually win:

  • HikariCP's "About Pool Sizing" page quotes a PostgreSQL-project starting point: connections = ((core_count * 2) + effective_spindle_count), counted for the database server. Treat it as a starting point to load-test, not a rule. HikariCP's default maximumPoolSize is 10.
  • The database's limit is shared. PostgreSQL's max_connections defaults to 100 (minus slots reserved for superusers), and every app instance has its own pool. Keep instances ร— maximumPoolSize, plus migrations and admin tools, below it, and remember autoscaling adds instances. Past the limit, PostgreSQL refuses new sessions with a FATAL error (remaining connection slots are reserved ... for ordinary roles, or sorry, too many clients already once every slot is used).
  • HikariCP recommends a fixed-size pool: leave minimumIdle at its default (equal to maximumPoolSize). If you set it lower, idleTimeout (default 10 minutes) closes connections idle beyond it, down to minimumIdle.

Virtual threads change the thread side, not the database side. With thousands of cheap threads, thousands of requests can be waiting in getConnection() at once, so the pool becomes the real limit on concurrent database work. That's the point of it: don't raise maximumPoolSize to match the thread count. Keep it sized for the database, and use a short connectionTimeout or a Semaphore so the queue doesn't grow without bound.

Sizing pools against one database4 steps
๐Ÿš‰Station A๐Ÿš‰Station B๐ŸจHotel
Press play and watch it happen!

The barrier that closes quietly

On the road to the hotel there's a barrier with a guard. If a taxi sits still too long, the guard quietly closes its lane without telling anyone. The taxi at the rank still looks fine, but the next rider who takes it gets nowhere.

So a careful marshal does three things. They check a taxi that's been sitting a while before handing it over. They send waiting taxis for a short drive now and then, so the guard sees them moving. And they retire every taxi after a set shift, its maximum lifetime, shorter than the guard's limit, bringing in a fresh one before the lane is ever closed.

Stale connections and maxLifetime

Pooled connections live a long time, and things between the app and the database don't always tolerate that: firewalls, NAT gateways and load balancers drop idle TCP flows silently, and the database may enforce its own limits (MySQL's wait_timeout, PostgreSQL's idle_session_timeout). The pool then holds a socket that looks open but is dead.

HikariCP defends in layers:

  • Validation on borrow: a connection that has been idle for more than 500 ms is checked with JDBC4 Connection.isValid() (bounded by validationTimeout, default 5 s) before it's handed out; a dead one is evicted and replaced. Don't set connectionTestQuery if your driver supports JDBC4.
  • keepaliveTime (default 2 minutes since HikariCP 6.2.1, as shipped by Spring Boot 3.5+; 0, meaning off, in older versions such as 5.x; minimum 30 s): idle connections are pinged periodically, so idle-timeout middleboxes see traffic.
  • maxLifetime (default 30 minutes): a connection is retired once it reaches this age, at the next point it's idle, and replaced. HikariCP shortens each connection's lifetime by a random amount (up to 25% in 6.x and later) so they don't all retire at once, and recommends setting it several seconds shorter than any database or infrastructure connection time limit.

Validation can't save a connection that dies mid-query: that statement fails with an I/O error, and the transaction must be retried. On managed databases, a short maxLifetime also helps connections follow DNS after a failover (see RDS).

1spring:2  datasource:3    url: jdbc:postgresql://db.internal:5432/orders4    username: app5    password: ${DB_PASSWORD}6    hikari:7      maximum-pool-size: 10          # sized for the database, not for threads8      connection-timeout: 3000       # fail fast when the pool is exhausted9      max-lifetime: 1500000          # 25 min: below a 30 min firewall or server limit10      keepalive-time: 12000011      leak-detection-threshold: 20000
Stale connections and maxLifetime5 steps
๐Ÿš Taxi rank๐ŸงRider Ana๐Ÿš•Taxi 1๐Ÿ’‚Barrier guard๐ŸจHotel
Press play and watch it happen!

A shuttle desk at the hotel

Some hotels get so many taxis from so many stations that they put a shuttle desk, a kind of pooler, at the end of the street. Taxis stop at the desk, and a few hotel shuttle carts carry riders the last stretch. When a rider's trip is done, their cart takes the next rider, from any station.

There's a catch. You may get a different cart on every trip, so you can't leave your bag in a cart and expect to find it next time. Anything you need, you bring along on each trip.

Server-side poolers

An app-side pool limits one process. When many instances, serverless functions or languages share a database, a pooler in front of it caps the total:

  • PgBouncer (PostgreSQL) accepts many client connections and maps them onto few server connections. In session mode a client keeps one server connection until it disconnects (little gain for pooled apps). In transaction mode, the usual choice, a server connection is assigned per transaction and returned when the transaction ends (commit or rollback), so many clients share it.
  • The catch with transaction mode: session state doesn't survive between transactions. SET and RESET (use SET LOCAL inside the transaction instead), session advisory locks (pg_advisory_lock; use pg_advisory_xact_lock), LISTEN, WITH HOLD cursors and SQL-level PREPARE aren't supported. Protocol-level prepared statements, which JDBC drivers use, need PgBouncer's max_prepared_statements (added in 1.21, on by default with 200 since 1.24); on older setups, disable server-side prepares in the driver (pgjdbc prepareThreshold=0).
  • RDS Proxy does the same for Amazon RDS and Aurora. Session state there causes pinning, which ties a client to one database connection and removes the benefit.

Keep the app-side HikariCP pool even behind a pooler: it still saves the client-to-pooler handshakes. Size the two together, so the app pools don't just move the queue to the pooler.

A pooler in front of the database4 steps
๐Ÿš‰Station A๐Ÿš‰Station B๐Ÿš‰Station C๐Ÿ›Ž๏ธShuttle desk๐ŸจHotel
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Connection pooling, told the same way as the story.
  1. Why does the station keep a taxi rank instead of finding a brand-new taxi for every rider?
  2. Cleo finds the rank empty and gives up after the waiting time, yet the hotel was quiet. What's the most likely cause?
  3. Three stations share one hotel street with room for 100 taxis. A fourth station opens. What should each station's rank look like?
  4. A barrier guard quietly closes any lane where nothing has moved for 30 minutes. How long should each taxi's shift be?
  5. At the hotel's shuttle desk, a rider leaves a bag in a cart and expects it on the next trip. Why is it missing?
Answer every question to check.Passing marks Connection pooling as done.
Got the hang of Connection pooling? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ—ƒ๏ธ Spring and databasesStep 5 of 7

โ† Previous on the path๐Ÿ“ Spring transactions (@Transactional)Next on the path โ†’๐Ÿฝ๏ธ The N+1 query problem (JPA and Hibernate)