Object Pool keeps a bounded set of expensive objects (database connections, threads, large buffers) and lends them out instead of creating and destroying one per use. A caller borrows an object with acquire(), uses it and gives it back with release(); the pool resets it and hands it to the next caller. It trades memory and some bookkeeping for skipping the slow creation step, and it puts one class in charge of how many of those objects can exist at once.
Think of it like
The library's laptop cart
A school does not buy a laptop for every lesson and throw it away afterwards. It keeps a cart of 30. A student signs one out, uses it, and signs it back in; the librarian wipes the student's files before lending it again. When all 30 are out, the next student waits, is told to come back later, or (in a generous school) the librarian buys one more. Forgetting the wipe is the classic failure: the next student opens the laptop and finds someone else's homework.
The problem
A web server answers requests that each run a few database queries. The straightforward code opens a connection, runs the query and closes it. This is the Before version in the visualizer above.
class Connection {
private open = true;
private user = "";
setUser(u: string) { this.user = u; }
query(sql: string) { return this.user + ": " + sql; }
close() { this.open = false; }
}
class Database {
private opened = 0;
open() {
// slow: network, TLS, login
this.opened++;
return new Connection();
}
}
const db = new Database();
const a = db.open(); // request 1
a.setUser("asha");
a.query("orders");
a.close();
const b = db.open(); // request 2: another open()
b.setUser("ravi");
b.query("cart");
b.close();Run Before and watch the objects view: two Connection objects appear (c1 and c2) and db.opened ends at 2. Each was used for one query and thrown away. The opened counter stands in for the real cost: opening a database connection means a TCP handshake, often a TLS handshake, authentication and a server-side session (PostgreSQL even starts a new server process per connection). That is typically milliseconds, against well under a millisecond for a simple indexed query on the same machine.
- Latency. Every request pays the connection setup before doing any real work.
- No limit. A traffic spike opens as many connections as there are concurrent requests. Databases cap connections (PostgreSQL's
max_connectionsdefaults to 100), and each one costs server memory, so the spike becomes an outage. - Churn. Creating and destroying heavy objects all the time costs CPU on both ends, and for large buffers it adds garbage-collection pressure.
The pattern
Intent: reuse a limited set of initialized objects that are expensive to create, by lending them out and taking them back, instead of creating and destroying them on demand. Object Pool is not one of the 23 Gang of Four patterns; it is usually listed with the creational patterns because it controls how objects come into existence.
- Pool (
ConnectionPool) - Owns the reusable objects. Keeps the free ones in
idleand tracks the borrowed ones ininUse. Decides when to create a new object and what happens when none is free. - Reusable object (
Connection) - Expensive to create, cheap to reset. It must be possible to put it back into a clean state (
reset()) so the next borrower cannot see the previous one's data. - Creator (
Database.open()) - Makes a new reusable object when the pool has to grow. In libraries this is a factory you pass to the pool.
- Client (
acquire()/release()) - Borrows an object, uses it and returns it. The client must not keep using it after
release().
acquire() takes an object from idle if there is one; otherwise it creates a new one (up to a maximum, if the pool has one). release(c) resets the object and moves it from inUse back to idle. The pool aggregates its objects (hollow diamond in the class diagram): they exist independently of any one request.
What the visualizer shows
- Objects at runtime:
poolshows itsidleandinUselists with arrows to the connections in them. With the pool there is only oneConnectionbox,c1, and the client gets that same box twice.db.openedstays at 1. - The reset: inside
release(),c1.usergoes from"asha"back to""beforec1moves toidle. That one line is what keeps request 2 from running asasha. - Sequence of calls: only the first
acquire()sendsopen()todb; the second comes straight back with the idle connection. - Change request (At most 2 connections): three requests arrive at once; the third
acquire()throwspool exhausted, and after onerelease()the retry gets the returned connection without opening a new one.
Walkthrough
- 1
Set up
With With Object Pool selected, the client creates
db(opened = 0) andpool, whoseidleandinUselists start empty. - 2
First acquire: create once
pool.acquire()findsidleempty, so it callsdb.open().db.openedbecomes 1 anddbcreatesc1. The pool recordsc1ininUseand returns it. - 3
Use it
Request 1 calls
c1.setUser("asha")(session state, like a database role or tenant) andc1.query("orders"), which returns"asha: orders". - 4
Release: reset, then put back
pool.release(c1)first callsc1.reset(), sousergoes back to"". Thenc1moves frominUsetoidle. The connection is still open; only its session state was cleared. - 5
Second acquire: reuse
Request 2 calls
pool.acquire().idleholdsc1, so the pool takes it: noopen()call, no new object.bis the samec1thataused, anddb.openedis still 1. - 6
Clean state
Request 2 sets
raviand its query returns"ravi: cart". Compare Before: two connections anddb.opened = 2for the same two requests. - 7
Change request: cap at 2
Apply At most 2 connections.
aandbborrowc1andc2. The thirdacquire()findsidleempty andinUsefull, and throwspool exhausted; the caller answers "busy, try again". Afterpool.release(a), the retry getsc1back. Three requests,db.opened = 2.
Before and after
New connection per request
- Every request pays
open(): 2 requests,db.opened = 2 - Objects are created and thrown away after one use
- Nothing limits how many connections exist at once
- No shared state between requests, so nothing to reset
With Object Pool
- Only the first request pays
open(): 2 requests,db.opened = 1 - The same
c1object serves both requests - One class decides how many connections exist and what happens when all are busy
- The pool must reset each object, and callers must give it back (and stop using it)
| Change request: at most 2 connections | Before | With Object Pool |
|---|---|---|
| Existing classes edited | 2 (Database, Connection) | 1 (ConnectionPool) |
| New classes | 0 | 0 |
| Lines changed in existing classes | 14 (+13 −1) | 11 (+9 −2) |
db.opened after the burst and the retry | 3 | 2 |
db.opened from the objects view at the last step.The line counts are close; the difference is where the change lands. Without a pool nothing owns the open connections, so Database has to count them (active, max, a check in open(), a new closed() method) and every Connection needs a reference back to report its own close(). With the pool, the check goes into acquire(), the one place that creates connections, and the client only passes 2. And the capped Before version still opens a brand-new c3 for the retry: counting connections is not reusing them.
Variations
Size: fixed, growing, or both
A fixed pool has a hard maximum, like the change request's 2. A growing pool, like the visualizer's plain version, creates whenever nothing is idle and never refuses; that protects latency but not the database. Most real pools sit in between: a minimum number kept ready, a maximum that is never exceeded, and sometimes a temporary overflow that is closed again when returned (SQLAlchemy's pool_size and max_overflow).
Creation: lazy or eager
Lazy pools create on first demand, as in the visualizer, so the first requests after startup are slow. Eager pools pre-fill (warm up) to a minimum at startup, so the first requests are fast and configuration errors (a wrong password) surface immediately instead of on the first user request.
Exhaustion policy
| Policy | What the caller sees | Typical use |
|---|---|---|
| Block with a timeout | acquire() waits until something is released, and fails if nothing comes back in time | Database connection pools: HikariCP's connectionTimeout, Commons Pool's maxWait (which waits forever unless you set it) |
| Fail fast | acquire() throws at once, as in the change request | Load shedding: answer "busy" (HTTP 503) instead of queuing more work |
| Grow | A new object is created beyond the normal size | Cheap objects, or a temporary overflow that is closed on return |
| Run in the caller | No pooled worker; the caller does the work itself | Thread pools (Java's CallerRunsPolicy), which naturally slows the producer down |
acquire() without a timeout turns a leak or a traffic spike into requests that hang; counted timeouts are the first sign of a leak or an undersized pool.Validation and eviction
A pooled connection can die while idle (the server restarted, a firewall dropped the TCP session). Pools therefore validate on borrow (a cheap check or ping before handing it out), validate on return, or test while idle in a background task. They also evict objects idle for too long and retire objects after a maximum lifetime, so connections are recycled before the server or network drops them.
Who resets, and leasing so nobody forgets to return
Reset belongs in the pool (or in a reset callback it is given), not in each caller, so it cannot be skipped. Returning should also be automatic: wrap the borrowed object in a lease whose scope ends with release(). Java's try-with-resources (closing a pooled JDBC Connection returns it to the pool), C#'s using, Python's with and C++ RAII all do this. Without it, every early return or exception is a potential leak.
// dataSource is a pooling DataSource, e.g. a HikariDataSource.
try (Connection c = dataSource.getConnection();
PreparedStatement st = c.prepareStatement(
"SELECT total FROM orders WHERE id = ?")) {
st.setLong(1, orderId);
try (ResultSet rs = st.executeQuery()) {
// ...
}
} // c.close() here returns the connection to the poolIn real code
| Where | What is pooled | Notes |
|---|---|---|
| HikariCP (Java) | JDBC connections | maximumPoolSize (default 10), connectionTimeout for how long getConnection() waits (default 30 seconds), maxLifetime and idleTimeout for recycling. Closing the borrowed Connection returns it. |
| Apache Commons Pool (Java) | Any object | GenericObjectPool with borrowObject() / returnObject(). You supply a factory with makeObject, validateObject, activateObject, passivateObject (the reset) and destroyObject. maxTotal defaults to 8, and by default a borrower blocks when the pool is exhausted. |
Java ExecutorService | Threads | Executors.newFixedThreadPool(n) keeps n worker threads and feeds them tasks from a queue. A ThreadPoolExecutor that cannot accept a task applies a rejection policy (the default AbortPolicy throws). See Thread Pool. |
Go sync.Pool | Temporary objects (buffers) | Get() / Put(); the pool may drop idle items at any time (around garbage collection), so it is a cache of allocations, not a connection pool. The standard library's fmt uses one for its print buffers. Go's database/sql DB is a separate, real connection pool (SetMaxOpenConns, SetMaxIdleConns). |
.NET ArrayPool<T> | Arrays | ArrayPool<T>.Shared.Rent(n) returns an array of at least n elements, and Return(array) does not clear it unless you pass clearArray: true: the stale-state bug, by design, for speed. ADO.NET pools database connections automatically; Close() or Dispose() returns them. |
Node.js pg (node-postgres) | PostgreSQL connections | pool.connect() gives a client that you must release(); pool.query() acquires and releases for you. max defaults to 10. |
| Python SQLAlchemy | Database connections | The default QueuePool has pool_size 5, max_overflow 10 and pool_timeout 30 seconds. pool_pre_ping=True validates each connection on checkout, and connections are reset (rolled back) when returned. |
| Game engines | Bullets, particles, enemies | Unity's UnityEngine.Pool.ObjectPool<T> takes create, on-get, on-release and on-destroy callbacks. Reusing short-lived game objects avoids allocation and garbage-collection pauses in the middle of a frame. |
Pools also live outside your process: PgBouncer is a separate server that pools PostgreSQL connections for many application instances, and HTTP clients keep pools of open keep-alive connections per host. The pattern is the same: borrow, use, reset, return, with a limit.
When to use it, and when not to
Use a pool when
- Creating the object is expensive compared with using it (network handshakes, process or thread start-up, large allocations)
- Objects can be reset to a clean state cheaply and reliably
- You need a hard limit on how many exist (database connections, threads, licenses)
- Allocation pauses matter (games, low-latency systems) and profiling shows them
Avoid it when
- Objects are cheap: modern allocators and generational garbage collectors make short-lived objects nearly free, and a pool can be slower
- State is complex or hard to reset completely: one missed field leaks data between users
- Lifetimes are unclear and callers may hold objects indefinitely
- A library or framework already pools the thing for you (your database driver, HTTP client, thread executor)
- Pooling cheap objects backfires. A pool keeps objects alive for a long time, so a generational garbage collector promotes them to the old generation, and writes into old objects cost more. Pool synchronization can cost more than the allocation it saves. Measure first.
- Sizing is a trade-off, not "bigger is better". A database with 8 cores does not run 500 queries in parallel; extra connections mostly queue inside the database and add contention. HikariCP's guide on pool sizing argues for small pools for exactly this reason.
- Leaks are silent until they are not. A forgotten
release()shrinks the pool by one each time, and the symptom (timeouts under load) appears far from the cause. Use leases, and turn on leak detection if the pool offers it.
Object Pool vs similar patterns
| Pattern | What is shared or reused | Ownership while used | Main difference from Object Pool |
|---|---|---|---|
| Object Pool | A set of mutable, expensive objects | Exclusive: one borrower at a time | The reference point for this table |
| Flyweight | Immutable intrinsic state | Shared by everyone at once | No checkout or return; objects are never reset because nobody can change them |
| Singleton | Exactly one instance | Shared by everyone at once | One object for the whole program; a pool manages many, and the pool itself is often a single injected instance |
| Prototype | A configured template object | Each caller gets its own copy | Makes new objects by cloning; nothing is returned or reused |
| Factory Method | Nothing | Each caller gets a new object | Decides which class to create; a pool decides whether to create at all, and often uses a factory to do it |
| Cache | Results or values | Usually shared, read-only | Keyed lookups of data; a pool hands out interchangeable objects, not values by key |
Implementation
The scenario with the change request applied: a pool with idle and in-use sets and a maximum, acquire that reuses an idle connection or opens a new one and fails fast when the pool is full, and release that rejects objects it did not lend and resets the session state. A withConnection helper (a context manager in Python) guarantees the release. TypeScript runs on one thread, so it needs no lock; Java, Python and C++ guard the pool with a lock. For brevity they open the connection while holding the lock; production pools open outside it so a slow handshake does not block other borrowers.
import threading
from contextlib import contextmanager
from itertools import count
_ids = count(1)
class Connection:
def __init__(self):
self.id = next(_ids)
self._user = ""
def set_user(self, user):
self._user = user
def query(self, sql):
return f"{self._user}: {sql} (on c{self.id})"
def reset(self):
self._user = ""
class Database:
def __init__(self):
self.opened = 0
def open(self):
self.opened += 1 # the expensive part: network, TLS, login
return Connection()
class PoolExhausted(Exception):
pass
class ConnectionPool:
def __init__(self, db, max_size):
self._db = db
self._max = max_size
self._idle = []
self._in_use = set()
self._lock = threading.Lock() # many threads share one pool
def acquire(self):
with self._lock:
if self._idle:
c = self._idle.pop()
else:
if len(self._in_use) >= self._max:
raise PoolExhausted("pool exhausted")
c = self._db.open()
self._in_use.add(c)
return c
def release(self, c):
with self._lock:
if c not in self._in_use:
raise ValueError("not borrowed from this pool")
self._in_use.remove(c)
c.reset() # forget this and the next borrower inherits it
self._idle.append(c)
@contextmanager
def connection(self):
c = self.acquire()
try:
yield c
finally:
self.release(c) # runs even if the body raises
db = Database()
pool = ConnectionPool(db, 2)
with pool.connection() as c:
c.set_user("asha")
print(c.query("orders")) # asha: orders (on c1)
with pool.connection() as c:
c.set_user("ravi")
print(c.query("cart")) # ravi: cart (on c1)
print(db.opened) # 1
# Three requests at once: the third fails fast.
a = pool.acquire()
b = pool.acquire()
try:
pool.acquire()
except PoolExhausted as e:
print(e) # pool exhausted
pool.release(a)
c = pool.acquire() # gets a's connection back
print(c is a, db.opened) # True 2
pool.release(b)
pool.release(c)Key takeaways
- Object Pool lends out a bounded set of expensive objects:
acquire()takes an idle one or creates one (up to a maximum),release()resets it and puts it back. - In the visualizer, two requests cost two
open()calls and twoConnectionobjects without a pool, and oneopen()with the pool: the samec1serves both. - Reset on return is part of the pattern: skip it and the next borrower inherits the previous one's state. Never use an object after releasing it.
- The pool is the one place that controls how many objects exist. Capping connections at 2 edited 1 class with the pool and 2 without, and the capped Before version still opened a third connection.
- Decide the exhaustion policy explicitly (wait with a timeout, fail fast, grow) and make returning automatic with leases (try-with-resources,
using,with, RAII). - Pool only what is truly expensive; for cheap objects modern allocators and garbage collectors make pooling useless or harmful. Prefer the pool your driver or framework already provides.
Common pitfalls
- Not resetting state on release (session settings, open transactions, buffer contents), so data leaks from one user to the next. .NET's
ArrayPool<T>.Returndoes not clear arrays unless asked. - Leaking objects: a missing
release()on an early return or exception slowly drains the pool until every request times out. Use a lease orfinally. - Using an object after releasing it, or releasing it twice, so two callers end up sharing one connection or buffer.
- Waiting without a timeout, or sizing the pool far larger than the database can serve in parallel. More connections usually means more contention, not more throughput.
- Pooling cheap objects "for performance" without measuring: the pool's locking and the long-lived objects can make things slower.
Interview tips
- For "design a connection pool", cover idle and borrowed sets, max and min size,
acquirewith a timeout, reset and validation on return, thread safety (lock plus condition variable, or semaphore plus concurrent queue), idle eviction, maximum lifetime and leak detection. - Name concrete pools: HikariCP or Apache Commons Pool in Java,
ExecutorServicethread pools, Go'ssync.Pool, .NET'sArrayPool<T>, and object pools in game engines. Mention that a thread pool reuses workers and queues tasks rather than lending objects. - Be ready to say when not to pool: cheap objects with a modern garbage collector, or objects whose state cannot be reset reliably.
Real-world applications
- Database connection pools in every server framework (HikariCP, ADO.NET, SQLAlchemy, node-postgres, Go's
database/sql). - Thread pools and executors that reuse worker threads for many tasks.
- Byte buffers and arrays in high-throughput I/O and serialization (
ArrayPool<T>, Go'ssync.Pool, Netty's pooled buffers). - Bullets, particles and enemies in games, to avoid allocation and garbage-collection pauses mid-frame.
- HTTP keep-alive connection pools in HTTP clients, and external poolers such as PgBouncer.
Test yourself
In the visualizer's With Object Pool run, why is db.opened still 1 after two requests?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.