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.
Shows how coroutines wait for a released connection when pool capacity is occupied. section 5.5.2
