Skip to content

Connection Pooling

A technique where a set of pre-established database connections are reused rather than creating a new connection every time a client makes a request.

The Problem It Solves

Creating a new database connection is expensive — it involves network handshake, authentication, memory allocation, and session setup. If every request creates and destroys a connection, it leads to high latency and resource wastage under heavy load.

How It Works

Clients            Connection Pool          Database
  |                      |                      |
  |---Request----------->|                      |
  |                      |---Use Connection---->|
  |                      |<--Result--------------|
  |<--Response-----------|                      |
  |     (connection returned to pool, not closed)
  |---Request----------->|                      |
  |     (reuses same connection)

Key Parameters

ParameterDescription
Minimum Pool SizeConnections kept open even when idle
Maximum Pool SizeMax connections allowed in the pool
Connection TimeoutHow long a client waits for a free connection
Idle TimeoutHow long an unused connection stays in the pool
Max LifetimeMaximum age of a connection before it's recycled

Pool Size Rule of Thumb (HikariCP)

Pool Size = (Core Count × 2) + Effective Disk Spindles

Important: Bigger pool ≠ Better performance. Too many connections can overwhelm the database.

Connection Pool States

  • Idle → Available, waiting to be borrowed
  • Active → Currently in use by a client
  • Closed → Removed from pool (timed out or errored)

Benefits vs Drawbacks

BenefitsDrawbacks
Reduced connection overheadConsumes memory even when idle
Faster response timesMisconfigured pool size can cause issues
Better resource managementStale connections can cause errors
Handles traffic spikes betterAdds complexity to the system
LanguageLibrary
JavaHikariCP, c3p0, DBCP
PythonSQLAlchemy Pool, psycopg2 pool
Node.jspg-pool, mysql2 pool
.NETBuilt-in ADO.NET pooling