duckdb and postgres connection management and thread safety in a multithreaded, long lived process #319
|
I'm trying to optimise DuckDB + Postgres connection handling in a long-lived, multithreaded application, but, after reading the docs, I'm not quite sure what the best way is to put all the moving parts together, so I'm looking for some advice. Preface I only ever want to perform reads, through DuckDB into postgres, e.g. Postgres side The two methods to connect to postgres:
From what I can tell, I'm assuming (couldn't find anything about this in the docs, and a cursory look into the source also didn't yield a result) that DuckDB side According to this, the connection is inherently not thread safe. It does mention
This seems to imply that within the same However, there's also this guide, which does show using threads and Baring this guide, I would have concluded that what I actually want is some sort of connection pool, with one I would appreciate any insights in how this is supposed to be handled, or corrections if I'm missing something really obvious :) |
Replies: 2 comments
|
Two points resolve most of the apparent contradiction. First, Second, use one DuckDB client context per Python worker: root = duckdb.connect(...)
root.execute("""
ATTACH 'host=... dbname=...' AS pg
(TYPE postgres, READ_ONLY)
""")
def worker(sql, params=()):
local = root.cursor()
try:
return local.execute(sql, params).fetchall()
finally:
local.close()The cursors share the database/catalog attachment, but each has independent query and transaction state. Do not concurrently execute through For a long-lived service, I would prefer the attached catalog over repeating credentials in every The current extension overview lists |
|
To reiterate: yes, one cursor per thread is safe because each cursor gets independent query state. |
Two points resolve most of the apparent contradiction.
First,
ATTACH ... TYPE postgresdoes not force every query through one permanent PostgreSQL connection. The extension has its own connection pool and can open multiple PostgreSQL connections, including several for a single parallel table scan. Current controls includepg_connection_limitand the pool settings documented under PostgreSQL connection pooling.Second, use one DuckDB client context per Python worker: