[Fixed]-Psycopg2 disconnects from server


This is a very similar question to the one posted here:

Django + FastCGI – randomly raising OperationalError

I imagine the answer will be the same to both if and when someone eventually figured it out. This same problem has been bothering me for about a month now and I have no idea what could be causing it.


Even though it’s very old question,
Best Solution I’ve found is in this answer.
just do the following:

from django import db

and before calling fork or using multiprocessing execute:



Do you fork() child processes (use preforked FastCGI or something similar)? This might be the reason that connection established in parent process doesn’t work in child. If you use preforked method it’s easy to switch to threading to see whether the problem has gone away. I saw exactly the same floating error in such case.


In my case, my WSGI server, uWSGI, was forking my app processes such that the underlying connection pool was shared. This was causing undefined behavior that (non-deterministically) was sending connections down as OP saw.

I’d recommend ensuring your app processes are eagerly forked. In uWSGI you do that with the option

lazy-apps = true

Leave a comment