Object Pool Pattern

An Object Pool keeps a bounded set of expensive, reusable objects alive and lends them out one at a time. A caller acquires one, uses it, hands it back, and the pool gives that same object to the next caller. Once the pool is at its ceiling nothing new gets constructed – a caller arriving then waits, or is told no.

Worth saying up front: this is not a GoF pattern. It post-dates the book and is usually credited to the pattern literature of the late nineties, later formalised as Pooling in the resource-management pattern work. The distinction matters, because unlike every other creational pattern its motivation is not a construction concern at all. It is a resource limit. A database connection is expensive to create and the database only permits so many, and the second constraint is what makes a pool mandatory rather than an optimisation.

💡 Acquire, borrow and check out all mean “take an object out for exclusive use”; release, return and check in all mean “give it back, scrubbed”.

Why this matters: pools turn up in more machine-coding prompts than candidates expect – a rate limiter handing out tokens, a scheduler reusing workers, an ORM lending sessions – and the pattern is unusually easy to half-know. Nearly everyone can draw the idle queue. What gets graded is the part either side of it: that acquire can fail instead of blocking forever, that release resets the object before the next borrower inherits it, that a connection the server already closed gets discarded rather than handed out, and that pool size is a number you can derive. The deadlock question below is a favourite senior follow-up with a clean answer almost nobody gives.


Prerequisites

  • Singleton Pattern – a pool is almost always one shared instance, so every Singleton lifecycle and testability problem is also a pool problem
  • Concurrency – acquire and release run from many threads at once, which makes this one of the few LLD classes that has to be genuinely thread-safe
  • Exception Handling – the release step has to run on the failure path too, so this is a finally and RAII lesson as much as a pattern one

The Problem: a database connection per request

The handler everyone writes first. It is correct JDBC: it closes what it opens, it uses a prepared statement, it handles its exception.

public class OrderHandler {

    private static final String URL = "jdbc:postgresql://db.internal:5432/orders";

    public OrderResponse handle(OrderRequest req) {
        // A fresh connection per request. Nothing leaks. Still wrong.
        try (Connection c = DriverManager.getConnection(URL, user, pass);
             PreparedStatement ps = c.prepareStatement(
                     "SELECT status FROM orders WHERE id = ?")) {
            ps.setLong(1, req.orderId());
            ResultSet rs = ps.executeQuery();
            return rs.next() ? OrderResponse.of(rs.getString("status"))
                             : OrderResponse.notFound(req.orderId());
        } catch (SQLException e) {
            throw new DataAccessException("order lookup failed", e);
        }
    }
}

Three costs, and an interviewer will go after all three:

  1. The setup cost is paid per request, and it dwarfs the work. Spell out what getConnection does before it returns: a TCP handshake, a TLS negotiation, an authentication exchange (SCRAM is itself several round trips), then session setup – and on Postgres the server forks a backend process for you. Typically tens of milliseconds, in front of one indexed primary-key lookup that is sub-millisecond.

  2. max_connections is a server-side limit, so this does not get slower – it starts failing. Postgres accepts connections up to a configured ceiling and refuses the rest outright. A pool-less service has no ceiling of its own, so concurrency at the database is whatever arrived at the app, times the instance count. Cross the line and you do not see a latency graph bending upwards, you see FATAL: sorry, too many clients already – and because every caller races for the same scarce thing, that error reaches all of them inside the same second. Autoscaling makes it worse: more instances, one ceiling.

  3. There is nowhere to put a wait, so the system has no backpressure. Admission control only exists if something can say “not yet”. Here every request converts immediately into load, and the handler’s only outcomes are connected or failed. A pool is where a wait can live, turning an overload into a bounded queue plus a timeout you chose.

💡 Backpressure = letting a slow downstream component slow its callers down, rather than letting callers pile work on until something breaks. Learn more →


Class Diagram

classDiagram
    class ObjectPool {
        <<interface>>
        +acquire(Duration timeout) Lease
    }
    class ConnectionPool {
        -Semaphore permits
        -BlockingQueue~Connection~ idle
        +acquire(Duration timeout) Lease
        -release(Connection c)
        -reset(Connection c)
        -isAlive(Connection c) boolean
        -evictIdle()
    }
    class Lease {
        -Connection conn
        +connection() Connection
        +close()
    }
    class ConnectionFactory {
        <<interface>>
        +create() Connection
    }

    ObjectPool <|.. ConnectionPool
    ConnectionPool --> ConnectionFactory
    ConnectionPool ..> Lease : issues
    Lease ..> ConnectionPool : returns on close

Two things here are the lesson. release is private, so the only way to give a connection back is to close its Lease – returning it becomes the language’s job. And the Semaphore sits beside the idle queue, not inside it, because capacity and reuse are separate concerns.


Real-World Example: a bounded database connection pool

import java.sql.*;                // Connection, SQLException, Statement
import java.time.Duration;
import java.util.concurrent.*;    // Semaphore, BlockingQueue, TimeUnit

public final class ConnectionPool implements ObjectPool {
    private final Semaphore permits;                // capacity
    private final BlockingQueue<Connection> idle;   // reuse
    private final ConnectionFactory factory;
    private final int maxSize;
    // permits = new Semaphore(maxSize, true) -- FAIR, so no waiter starves.

    /** TIMEOUT -- blocking forever would turn database saturation into a thread
     *  leak here, so an unservable caller is told while its own deadline still
     *  has room for a fallback. */
    @Override
    public Lease acquire(Duration timeout) throws InterruptedException {
        if (!permits.tryAcquire(timeout.toNanos(), TimeUnit.NANOSECONDS)) {
            throw new PoolTimeoutException(maxSize, timeout);
        }
        // A permit in hand means a connection is ours, so the idle queue is
        // never waited on: empty just means "create one".
        try {
            while (true) {
                Connection c = idle.poll();
                if (c == null) return new Lease(this, factory.create());  // lazy
                if (!isAlive(c)) {
                    close(c);          // the server closed it while it sat idle
                    continue;          // the permit is still ours: try again
                }
                return new Lease(this, c);
            }
        } catch (RuntimeException | SQLException e) {
            permits.release();         // never leak a permit on a failure path
            throw new PoolException("could not produce a connection", e);
        }
    }

    /** Private: the only caller is Lease.close, and that is the point. */
    private void release(Connection c) {
        try {
            reset(c);
            if (!idle.offer(c)) close(c);
        } catch (SQLException e) {
            close(c);                  // cannot scrub it, cannot reuse it
        } finally {
            permits.release();         // ALWAYS, even if it was binned
        }
    }

    /** RESET -- the next borrower inherits nothing from the last one. */
    private void reset(Connection c) throws SQLException {
        if (!c.getAutoCommit()) {
            c.rollback();              // an abandoned transaction dies HERE
            c.setAutoCommit(true);
        }
        c.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        try (Statement s = c.createStatement()) {
            s.execute("DISCARD ALL");  // SET vars, temp tables, prepared stmts
        }
    }

    /** VALIDATE -- isValid is the driver's cheap liveness check, not a query. */
    private boolean isAlive(Connection c) {
        try { return !c.isClosed() && c.isValid(1); }
        catch (SQLException e) { return false; }
    }

    private void close(Connection c) {
        try { c.close(); } catch (SQLException ignored) { }
    }

    /** The borrow handle. Closing it is the only release path. */
    public static final class Lease implements AutoCloseable {
        private final ConnectionPool pool;
        private Connection conn;       // nulled on close: double-close no-ops

        private Lease(ConnectionPool pool, Connection conn) {
            this.pool = pool; this.conn = conn;
        }

        public Connection connection() { return conn; }  // null once closed

        @Override public void close() {
            if (conn == null) return;
            Connection returning = conn;
            conn = null;               // flip BEFORE release: no double return
            pool.release(returning);
        }
    }
}

// Usage -- no path out of this block skips the release.
try (ConnectionPool.Lease lease = pool.acquire(Duration.ofMillis(250))) {
    orders.markShipped(lease.connection(), orderId);  // return, throw, break:
}                                                     // close() still runs
import contextlib, queue, threading

class PoolTimeout(RuntimeError):
    pass

class ConnectionPool:
    """queue.Queue holds the idle objects. The semaphore holds the capacity."""

    def __init__(self, connect, max_size=10):
        self._connect = connect
        # LIFO, so the coldest connections stay idle long enough to be reaped.
        self._idle = queue.LifoQueue(maxsize=max_size)
        # Bounded: an over-release raises ValueError rather than silently
        # growing the pool past max_size.
        self._permits = threading.BoundedSemaphore(max_size)

    @contextlib.contextmanager
    def acquire(self, timeout=0.25):
        """with pool.acquire() as conn: ..."""
        if not self._permits.acquire(timeout=timeout):          # TIMEOUT
            raise PoolTimeout(f"no connection within {timeout}s at max_size")
        conn = None
        try:
            conn = self._check_out()
            yield conn
        finally:
            if conn is not None:
                self._check_in(conn)
            self._permits.release()       # ALWAYS, even if conn was discarded

    def _check_out(self):
        while True:
            try:
                conn = self._idle.get_nowait()   # we hold a permit: never block
            except queue.Empty:
                return self._connect()           # lazy creation, up to max_size
            try:
                conn.cursor().execute("SELECT 1")    # VALIDATE on borrow
                return conn
            except Exception:
                self._discard(conn)                  # dropped while it sat idle

    def _check_in(self, conn):
        try:
            conn.rollback()                       # RESET: kill an open transaction
            conn.cursor().execute("DISCARD ALL")  # SET vars, temp tables, prepares
            self._idle.put_nowait(conn)           # queue.Full if at max_size
        except Exception:
            self._discard(conn)                   # unreusable: retire it

    def _discard(self, conn):
        with contextlib.suppress(Exception):
            conn.close()
#include <chrono>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <vector>

class ConnectionPool;

/** Move-only borrow handle. The destructor is the ONLY release path, so a leaked
 *  borrow is not a bug you avoided -- it is a program you cannot write. */
class Lease {
    ConnectionPool* pool_ = nullptr;
    std::unique_ptr<Connection> conn_;
    Lease(ConnectionPool* p, std::unique_ptr<Connection> c)
        : pool_(p), conn_(std::move(c)) {}
    friend class ConnectionPool;

public:
    Lease(const Lease&) = delete;      // one owner, always
    Lease(Lease&&) noexcept = default; // a move passes the duty on
    ~Lease();
    Connection* operator->() const { return conn_.get(); }
};

class ConnectionPool {
    std::mutex m_;
    std::condition_variable cv_;
    std::vector<std::unique_ptr<Connection>> idle_;
    std::size_t inUse_ = 0, maxSize_;

public:
    Lease acquire(std::chrono::milliseconds timeout) {
        std::unique_lock<std::mutex> lock(m_);
        // Predicate wait_for: absorbs spurious wakeups, and returns false on
        // the deadline instead of parking the thread forever.
        if (!cv_.wait_for(lock, timeout, [this] {
                return !idle_.empty() || inUse_ < maxSize_; })) {
            throw PoolTimeout(maxSize_, timeout);
        }
        ++inUse_;                        // claim the slot BEFORE the slow connect
        if (idle_.empty()) { lock.unlock(); return Lease(this, connect()); }
        auto c = std::move(idle_.back());   // validate here too, as in Java
        idle_.pop_back();
        return Lease(this, std::move(c));
    }

private:
    friend class Lease;

    // Scrub, re-queue if reusable, --inUse_, notify_one. As in the Java tab,
    // and noexcept because a destructor calls it.
    void release(std::unique_ptr<Connection> c) noexcept;
    std::unique_ptr<Connection> connect();
};

inline Lease::~Lease() {
    if (pool_ && conn_) pool_->release(std::move(conn_));  // moved-from: null
}

All three tabs make one point: the release is written by the language, not the borrower – try-with-resources, the finally inside a @contextmanager generator, a destructor on a move-only handle. C++ is strongest, because there “forgot to release” is not a program you can express. The terse C++ alternative is a shared_ptr whose custom deleter checks the object back in rather than deleting it: same guarantee, but it costs a control block per borrow and lets a copy outlive its intended scope.

Two lifecycle rules separate a toy pool from one you would run, and neither is in the snippets. A maxLifetime check retires a healthy connection on purpose, because something between the app and the database will eventually close it without telling you – a NAT entry expiring, a load balancer’s idle timeout, a failover – which you would rather discover in the pool than mid-query. Set it below the shortest timeout in the network path. Second, the evictIdle sweep in the diagram lets the pool shrink back down after a spike: a burst grows it to maxSize and without a reaper it stays there holding backends nobody uses, so a periodic pass destroys anything idle past a threshold while keeping a minIdle floor warm. The Python tab’s LIFO queue is what makes that possible, since FIFO rotation keeps every connection just-used so nothing ever qualifies.


A pool is a semaphore that happens to hand you an object

Look at what acquire does first: before it touches the idle queue, it takes a permit. Everything after is bookkeeping about which object you get; whether you get one was already settled. That ordering is what a pool is: admission control, with object reuse attached.

Which reframes sizing. Pool size is a concurrency limit on the resource behind it, so the number comes from queueing theory rather than taste. Little’s Law gives the shape – in-flight work equals arrival rate times service time, N = λ × W – so your queries per second and the time the database holds each one tell you how many connections can be busy at once. Measure your own λ and W; what matters is that the number is derived.

The failure of intuition runs one way: people size pools too large. A pool bigger than the database can serve adds no throughput, it moves the queue to the worse place. Present a few hundred concurrent queries to a machine with eight cores and all of them sit in its run queue, competing for the same cores and row locks – every query gets slower, and the waiting now happens somewhere you can neither see nor time out. The classic heuristic for a CPU-bound backend is a small multiple of core count, not hundreds: a connection only makes progress while a core or a disk is serving it, so connections past that count are queue rather than capacity.

The deadlock that gets asked about

Now the trap, and it is the best interview content in this pattern. A request that needs two connections from a pool of N can deadlock. A handler acquires one, and somewhere deeper – a nested service call, an audit write, a lazy association – acquires a second. If N such requests arrive together, each holds one connection and waits for a second that cannot exist. Nobody releases, because releasing requires finishing and finishing requires the connection nobody will give up. All N wait out their timeout and fail together. It is load-triggered, so it survives testing. Four fixes, in preference order:

  1. Never hold two. Restructure so the nested acquire happens after the first is released. This is the real fix, and usually possible.
  2. Acquire both atomically at the top, and accept that your effective capacity halves.
  3. Use a separate pool for the nested use, so the two borrows do not compete for the same permits.
  4. Size around it. With T threads each holding up to C connections, N ≥ T × (C - 1) + 1 guarantees at least one thread can always complete. Quoting that classic bound shows you understand why it deadlocks, not just that it does.

See Connection Pooling for the operational side, and Backpressure for what the wait in front of a full pool buys you.


Object Pool vs Flyweight vs Singleton vs Cache vs Thread Pool

All five hand you an object you did not construct. What separates them is whether you must give yours back, and whether you may write to it:

Pattern Intent Tell
Object Pool Lend a bounded set of expensive mutable objects and reclaim them There is a return step, and forgetting it breaks the system
Flyweight Share one immutable instance per distinct value to cut memory Shares immutable objects with no return step – the opposite contract
Singleton Exactly one instance, globally reachable One instance, never lent out. The pool itself is usually a singleton
Cache Avoid recomputing a result, keyed by input Keyed by input, and free to evict any entry at any moment
Thread Pool Bound concurrency by reusing a fixed set of workers An object pool whose objects are workers, so sizing is the same

Pool versus cache is the distinction that matters in review, because they look alike and their invariants are opposites. A cache holds results and may drop any entry whenever it likes – a miss is a slow path, not a bug. A pool holds capacity and must not lose an entry: every leaked borrow permanently shrinks it. Eviction in a cache is a tuning knob; “eviction” in a pool is a leak. Flyweight is the other contrast worth rehearsing: a pooled object is mutable and exclusively borrowed, which is exactly why release needs a reset step and a flyweight does not – nobody can write to a flyweight, which is also why one serves a thousand callers while a pooled connection is held by one.


When to Use vs When to Avoid

Use Object Pool When Avoid When
The resource has a hard external ceiling – max_connections, a license count, file descriptors The object is cheap to construct, so pooling adds contention and loses to new
Creation cost is dominated by I/O: handshakes, TLS, auth, session setup A complete reset is impossible, so borrowers inherit state
The object is reusable by any caller after a cheap, total scrub The objects are immutable and shareable – that is a Flyweight
You want in-flight work bounded, so overload becomes a timeout you chose The borrow is user-scoped, so one slow client holds capacity
The object wraps something the runtime does not manage: a socket, a native handle The resource is elastic and metered per call

Two failure modes, and the first is the one that takes down production. The leaked borrow is this pattern’s signature bug: one code path returns early, or throws past the release, and that permit is gone for the life of the process, so the pool shrinks silently to zero. The symptom is a PoolTimeoutException in some unrelated request minutes later, which makes it one of the hardest bugs to attribute – the stack trace names the victim, never the culprit. Three mitigations: make the language do the release, add a leak detector that logs the acquiring stack trace when a borrow outlives a threshold, and put a metric on in-use count, because a count that only rises is the unambiguous signature of a leak. The second is quieter: pooling things that were never expensive. A pool of plain objects puts a lock in front of an allocation a modern JVM does in nanoseconds, so it is slower than what it replaced.


Interview Questions

  1. “How do you size a connection pool?” – Derive it, do not pick it. In-flight connections equal arrival rate times how long the database holds each query (N = λ × W), so measure those two and treat the result as the concurrency limit it is. Then say that oversizing is the common error and is not harmless: it moves the queue out of your app, where it is bounded and timeout-able, into the database’s run queue, where every query slows and nothing can be shed.

  2. “A request needs two connections from the pool. What can go wrong?” – It can deadlock. With a pool of N, if N requests each hold one connection and wait for a second, none can release because none can finish, and they all time out together. It only happens under load, so it ships. Fixes in preference order: restructure so no path holds two at once, acquire both up front, or give the nested use its own pool; failing those, size for N ≥ T × (C - 1) + 1.

  3. “Object Pool vs Flyweight?” – Mutability and the return step. A flyweight is immutable and shared concurrently by everyone with no handback, so there is no borrow accounting, no timeout and no reset. A pooled object is mutable and exclusively lent, so it needs all three. The one-glance test: if you must give it back, it is a pool.

  4. “What must release do, and what breaks if it does not?” – Scrub the object completely – roll back any open transaction, restore autocommit and isolation level, clear session variables, temp tables and prepared statements – then validate it and either return or destroy it, giving the permit back on every path. Skip the rollback and the next borrower inherits an open transaction: its first write silently joins a stranger’s transaction, so it either vanishes when something rolls that back or commits inside a unit of work it never agreed to. No error is raised anywhere.

  5. “Should you pool objects in a garbage-collected language?” – Only for resources with an external limit or a genuinely expensive handle: connections, sockets, threads, large direct byte buffers, native handles. For ordinary objects it is a pessimisation – allocation on a modern JVM is close to a pointer bump, young-generation collection is cheap because most objects die young, and a pool replaces all that with a concurrent queue, a reset step you can get wrong and a leak you can create. Name the exception: in a pause-sensitive context, pooling to avoid allocation is a real technique.


See It in Action

  • Multilevel Cache – the backing store sits behind a bounded pool, so a miss storm queues up
  • Task Scheduler – a worker pool is this pattern with threads as the pooled object
  • Mini ORM – sessions are lent per unit of work, where reset-on-release earns its place
  • Rate Limiter – bounded permits with no object attached: the semaphore under a pool