Why psycopg2 has the same 'psycopg2.extensions.connection' object id in forked processes ? #1408
Replies: 2 comments 4 replies
-
Is psycopg inside has magic to return the same connection object from memory to different forked processes ? |
Beta Was this translation helpful? Give feedback.
-
When a process is forked, the memory allocated is copied for the new process. The id of the python object is its address memory, but that's a virtual address in the process address space. You will see the same with any Python object. Thank you for the assumption that psycopg has magic inside, but unfortunately that's not the case. What you are doing, by the way, will not work, because you are also duplicating the socket. From the libpq docs:
If you are writing a multiprocess program you should create the database connections after forking. |
Beta Was this translation helpful? Give feedback.
-
Good day, first I started discussion here sqlalchemy/sqlalchemy#7515, but we didn't gain answer there and one of maintainers advice me to ask here? because all goes to psycopg2 call.
So the question is when Flask application with SQLAlchemy (with psycopg2-binary) starts in forked processes (Gunicorn sync workers) I see that psycopg2.extensions.connection have the same object ids in different processes PIDs.
So in short words that call returns the same conn id :
https://github.com/psycopg/psycopg2/blob/master/lib/__init__.py#L122
So I worry about if the different processes are trying to use the same connection , its not safe am I right ?
Below I write down minimal app to reproduce issue and logs with my comments:
Environment
Linux Mint 20.1
Linux matrix 5.4.0-91-generic #102-Ubuntu SMP Fri Nov 5 16:31:28 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
Python 3.9.9 (main, Nov 16 2021, 03:08:02)
Flask==2.0.2
gunicorn==20.1.0
psycopg2-binary==2.9.3
SQLAlchemy==1.4.29
gunicorn_example.py
App starts with command:
And below logs:
so in some reason I see that psycopg2 conections in both processes have the same addresses (and I tried to get id(conn), beleive me they re the same)
So question - why, is it really the same connection ? If I check postgres opened connections, in fact I see 2 connections as expected, but these identical IDs in logs is very confuse me.
So maybe if here somebody has power to explain me what happening, please will be too appreciated :)
Beta Was this translation helpful? Give feedback.
All reactions