mirror of
https://github.com/langchain-ai/langchain-postgres.git
synced 2026-07-16 01:33:18 -04:00
PGVector / Postgres connection is not automatically closed, and remains idle #63
Reference in New Issue
Block a user
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Originally created by @Lengo46 on GitHub (Jan 2, 2025).
Checked other resources
Example Code
@Lengo46 commented on GitHub (Jan 10, 2025):
Any help on this?
@m-ibraheem-tkxel commented on GitHub (Feb 6, 2025):
I am working on v0.0.9
We had implemented a custom close function as a temporary measure and ended up using
def close(self):
if self.vectorstore is not None:
if hasattr(self.vectorstore, "__async_engine"):
self.vectorstore.__async_engine.close()
if hasattr(self.vectorstore, "__engine"):
self.vectorstore.__engine.close()
where self.vectorstore is an instance of PGVector.
Please share if there is a better way to do this in the newer versions.
@chunyeah commented on GitHub (May 6, 2025):
Any update with issue plz
@bhavan-kaya commented on GitHub (Jul 20, 2025):
Facing the same issue on our end, is there a way to expose the close method to be used outside so that the connections could be manually stoped
@volkanncicek commented on GitHub (Jul 21, 2025):
Hi @bhavan-kaya and others following this issue,
I've analyzed this problem and found the root cause of the connection leak. I've implemented a fix in my forked repository, which you can review here:
https://github.com/volkanncicek/langchain-postgres
The core of the issue is a global variable,
_classes, used to cache the SQLAlchemy models. My investigation showed that this variable causes the problem because:_classesonly once, during the very firstPGVectorinstantiation.PGVectorinstances, even if they use different database connections or schemas.My solution replaces the problematic global
_classesvariable with a_class_cachedictionary. This new approach uses thetable_schemaas a key, ensuring that a unique set ofEmbeddingStoreandCollectionStoreclasses is generated for each schema. This isolates the models and their corresponding engines, allowing SQLAlchemy to properly manage and close connection pools when they are no longer in use.I believe this permanently resolves the connection leak. Hope this helps
@cmd-AKASH commented on GitHub (Aug 14, 2025):
We ran into the same issue. I subclassed
PGVectorand added a public close() method so the DB connection can be explicitly disposed of after use.Usage:
This only handles the synchronous Engine case.
Works fine for us as a stopgap until the community resolves the issue.
P.S.: If it works, never touch it 😆