liveBook · Manning

Create_pool

As explained in Python Concurrency with asyncio

create_pool is an asyncpg coroutine that creates and configures a pool of database connections.

create_pool is asyncpg’s coroutine for establishing a configurable pool of database connections. Use it instead of connect when several coroutines need to run queries concurrently. section 5.5.2

Configure the pool around the concurrency your application and database can support:

  • Set min_size to the number of connections established when the pool is ready. section 5.5.2
  • Set max_size to the largest number of connections the pool may contain. section 5.5.2
  • Create the pool with async with, then acquire connections with pool.acquire(); released connections return to the pool. section 5.5.2
  • Benchmark pool sizes for the target hardware because a larger pool is not always better. section 5.5.2

Concurrent product queries

Create a pool with six connections, acquire one inside query_product, and use asyncio.gather to run multiple product queries concurrently. When all connections are busy, additional coroutines wait until one is released.

Figure 5.2 Coroutines 1 and 2 acquire connections to run their queries while Coroutine 3 waits for a connection. Once either Coroutine 1 or 2 finishes, Coroutine 3 will be able to use the newly released connection and will be able to execute its query.
05-02

Shows how coroutines wait for a released connection when pool capacity is occupied. section 5.5.2

How Python Concurrency with asyncio covers it

How deep it goes
Explains configuration, context-manager usage, acquisition, release, and sizing, but defers deeper pool design considerations.
Examples
Uses product queries, a six-connection pool, waiting coroutines, and synchronous-versus-concurrent timing comparisons.
What you can do after
Apply it via asyncpg to configure a pool, acquire connections safely, and run database queries concurrently.
How it connects
Connects asynchronous context managers, connection acquisition, coroutines, SQL queries, and asyncio.gather.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.