[Python] DB connection pooling

DB Connection Pooling

While implementing a feature to add a new game into DB, I realized that it might be required to create and close the connection to the DB each time to work with the DB, which is not efficient. Among several options, I chose to implement Connection pooling.

Understanding Connection Pooling

 Connection pooling with aiomysql is an efficient way to manage database connections in asynchronous applications. Instead of opening and closing a new connection for every query, a pool of reusable connections is created. This allows the application to borrow connections as needed, minimizing overhead and improving performance.

How Connection Pooling Works

First. Pool Initialization:
A pool is created with a fixed number of connections to the database. The pool manages these connections and ensures they remain active and ready to use.

Connection Borrowing:
When a query needs to access the database, it borrows a connection from the pool. Once the query is complete, the connection is returned to the pool for reuse.

Efficiency:
By reusing existing connections, connection pooling reduces the cost of repeatedly establishing and tearing down database connections.

Syntax (Using aiomysql for Connection Pooling)

Step 1. Initialize the Connection Pool

import aiomysql
import asyncio

async def init_pool():
    pool = await aiomysql.create_pool(
        host='localhost',
        user='root',
        password='your_password',
        db='game_db',
        minsize=1,  # Minimum number of connections
        maxsize=10, # Maximum number of connections
    )
    return pool

Step 2: Execute Queries Using the Pool

Borrow a connection from the pool, execute the query, and return the connection.

async def query_database(pool, query):
    async with pool.acquire() as connection:  # Borrow a connection
        async with connection.cursor() as cursor:  # Create a cursor
            await cursor.execute(query)  # Execute the query
            result = await cursor.fetchall()  # Fetch the results
            return result

Full Example

import aiomysql
import asyncio

# Initialize the connection pool
async def init_pool():
    pool = await aiomysql.create_pool(
        host='localhost',
        user='root',
        password='your_password',
        db='game_db',
        minsize=1,  # Minimum number of connections
        maxsize=10, # Maximum number of connections
    )
    return pool

# Query using the connection pool
async def query_database(pool, query):
    async with pool.acquire() as connection:  # Borrow a connection
        async with connection.cursor() as cursor:  # Create a cursor
            await cursor.execute(query)  # Execute the query
            result = await cursor.fetchall()  # Fetch the results
            return result

# Main program
async def main():
    # Initialize the connection pool
    pool = await init_pool()

    # Run a query
    query = "SELECT * FROM developers"
    result = await query_database(pool, query)
    print(result)

    # Close the pool when done
    pool.close()
    await pool.wait_closed()

# Run the program
asyncio.run(main())

Note: Using close() and wait_closed()

The primary reason for calling close() and wait_closed() is to gracefully clean up resources when the application no longer needs the connection pool.

1. At the End of the Application

  • If the application is shutting down (e.g., a script finishing execution or a web server shutting down), the connection pool is no longer needed.
  • close() is called to stop accepting new connections and wait_closed() to clean up any active connections.

2. When Releasing Resources

  • For long-running applications, it may need may dynamically manage connection pools (e.g., create and destroy them based on specific requirements).
  • When a pool is no longer needed, cleaning is needed up to prevent resource leaks (e.g., open connections using server resources unnecessarily).

Comments