# Asynchronous psycopg2

psycopg2 connections are thread-safe[1], which means that many threads can access the same database, either:

  • Every thread creating its own connection, or
  • Every thread using the same connection but each creating different cursors.

I'd generally recommend, if possible, to have separate connections per thread as that will mean that SQL queries will be executed in different sessions.

# asyncio support in psycopg2

psycopg2 does not support async and await. However, there is another library built on top of psycopg2 that does: aiopg[2].

With aiopg you can use the async and await keywords, and you'll gain the ability to multi-task while waiting for database operations.

If you don't know how asyncio or the async and await keywords work, I'd recommend a section in our Complete Python Course (opens new window) which covers this extensively. This talk (opens new window) by David Beazley is also excellent.

Enjoyed this article?
You'll love the complete video course!

  • Complete video lessons for each topic
  • Get the most out of your learning
  • Master Advanced PostgreSQL
  • Get one-on-one help from a real person

Get the video course

  1. Thread and process safety (psycopg2 Official Documentation) (opens new window) ↩︎

  2. aiopg (Official Documentation) (opens new window) ↩︎