Connection Pool Leaks

Borrowing a book from the library and never returning it.

The idea

Opening a new TCP connection to a database is slow, so web servers keep a "Pool" of pre-opened connections. When a web request arrives, it borrows a connection, runs a query, and returns it to the pool. But if your code throws an error and forgets to return the connection, it is permanently lost ("leaked"). If this happens 10 times in a pool of 10 connections, your entire web server freezes, unable to talk to the database.

Step 1: The Pool has 3 connections available.

How it works (try/finally or with)

To prevent leaks, you must guarantee that the connection is released even if an exception is thrown during the query. In modern languages, you use Context Managers (like Python's with) or try/finally blocks.

# THE BAD WAY (Leaks on Error)
def get_user():
    conn = pool.get_connection()
    # If this query throws an Error, we skip the release line!
    data = conn.execute("SELECT * FROM bad_table")
    conn.release() # ⚠ Never reached. Leak!
    
# THE GOOD WAY (Context Manager)
def get_user():
    # 'with' guarantees release() is called, even on Exceptions
    with pool.get_connection() as conn:
        data = conn.execute("SELECT * FROM bad_table")
        return data

Cost

The pattern is simple, but missing it in a single obscure error path can take down a server weeks later as the leak slowly accumulates. Modern ORMs (like Hibernate, Prisma, or SQLAlchemy) handle this for you automatically, which is a major reason to use them over raw SQL drivers.

Watch out for