Home » Django » Django multiprocessing and database connections

Django multiprocessing and database connections

Posted by: admin November 30, 2017 Leave a comment



I’m working a project which uses Django with a Postgres database. We’re also using mod_wsgi in case that matters, since some of my web searches have made mention of it. On web form submit, the Django view kicks off a job that will take a substantial amount of time (more than the user would want to wait), so we kick off the job via a system call in the background. The job that is now running needs to be able to read and write to the database. Because this job takes so long, we use multiprocessing to run parts of it in parallel.


The top level script has a database connection, and when it spawns off child processes, it seems that the parent’s connection is available to the children. Then there’s an exception about how SET TRANSACTION ISOLATION LEVEL must be called before a query. Research has indicated that this is due to trying to use the same database connection in multiple processes. One thread I found suggested calling connection.close() at the start of the child processes so that Django will automatically create a new connection when it needs one, and therefore each child process will have a unique connection – i.e. not shared. This didn’t work for me, as calling connection.close() in the child process caused the parent process to complain that the connection was lost.

Other Findings:

Some stuff I read seemed to indicate you can’t really do this, and that multiprocessing, mod_wsgi, and Django don’t play well together. That just seems hard to believe I guess.

Some suggested using celery, which might be a long term solution, but I am unable to get celery installed at this time, pending some approval processes, so not an option right now.

Found several references on SO and elsewhere about persistent database connections, which I believe to be a different problem.

Also found references to psycopg2.pool and pgpool and something about bouncer. Admittedly, I didn’t understand most of what I was reading on those, but it certainly didn’t jump out at me as being what I was looking for.

Current “Work-Around”:

For now, I’ve reverted to just running things serially, and it works, but is slower than I’d like.

Any suggestions as to how I can use multiprocessing to run in parallel? Seems like if I could have the parent and two children all have independent connections to the database, things would be ok, but I can’t seem to get that behavior.

Thanks, and sorry for the length!


Multiprocessing copies connection objects between processes because it forks processes, and therefore copies all the file descriptors of the parent process. That being said, a connection to the SQL server is just a file, you can see it in linux under /proc//fd/…. any open file will be shared between forked processes. You can find more about forking here.

My solution was just simply close db connection just before launching processes, each process recreate connection itself when it will need one (tested in django 1.4):

from django import db
def db_worker():      
Process(target = db_worker,args = ())

Pgbouncer/pgpool is not connected with threads in a meaning of multiprocessing. It’s rather solution for not closing connection on each request = speeding up connecting to postgres while under high load.


To completely remove problems with database connection simply move all logic connected with database to db_worker – I wanted to pass QueryDict as an argument… Better idea is simply pass list of ids… See QueryDict and values_list(‘id’, flat=True), and do not forget to turn it to list! list(QueryDict) before passing to db_worker. Thanks to that we do not copy models database connection.

def db_worker(models_ids):        
    obj = PartModelWorkerClass(model_ids) # here You do Model.objects.filter(id__in = model_ids)

model_ids = Model.objects.all().values_list('id', flat=True)
model_ids = list(model_ids) # cast to list
process_count = 5
delta = (len(model_ids) / process_count) + 1

# do all the db stuff here ...

# here you can close db connection
from django import db

for it in range(0:process_count):
    Process(target = db_worker,args = (model_ids[it*delta:(it+1)*delta]))   


When using multiple databases, you should close all connections.

from django import db
for connection_name in db.connections.databases:


Please use the same as @lechup mentionned to close all connections(not sure since which django version this method was added):

from django import db


For Python 3 and Django 1.9 this is what worked for me:

import multiprocessing
import django
django.setup() # Must call setup

def db_worker():
    for name, info in django.db.connections.databases.items(): # Close the DB connections
    # Execute parallel code here

if __name__ == '__main__':

Note that without the django.setup() I could not get this to work. I am guessing something needs to be initialized again for multiprocessing.


Hey I ran into this issue and was able to resolve it by performing the following (we are implementing a limited task system)


from django.db import connection

def as_task(fn):
    """  this is a decorator that handles task duties, like setting up loggers, reporting on status...etc """ 
    connection.close()  #  this is where i kill the database connection VERY IMPORTANT
    # This will force django to open a new unique connection, since on linux at least
    # Connections do not fare well when forked 


from django.db import connection

def run_task(request, job_id):
    """ Just a simple view that when hit with a specific job id kicks of said job """ 
    # your logic goes here
    # ...
    processor = multiprocessing.Queue()
        target=call_command,  # all of our tasks are setup as management commands in django
        kwargs= {
            'web_processor': processor,
        }.items() + vars(options).items()).start()

result = processor.get(timeout=10)  # wait to get a response on a successful init
# Result is a tuple of [TRUE|FALSE,<ErrorMessage>]
if not result[0]:
    raise Exception(result[1])
   # THE VERY VERY IMPORTANT PART HERE, notice that up to this point we haven't touched the db again, but now we absolutely have to call connection.close()
   # we do some database accessing here to get the most recently updated job id in the database

Honestly, to prevent race conditions (with multiple simultaneous users) it would be best to call database.close() as quickly as possible after you fork the process. There may still be a chance that another user somewhere down the line totally makes a request to the db before you have a chance to flush the database though.

In all honesty it would likely be safer and smarter to have your fork not call the command directly, but instead call a script on the operating system so that the spawned task runs in its own django shell!


(not a great solution, but a possible workaround)

if you can’t use celery, maybe you could implement your own queueing system, basically adding tasks to some task table and having a regular cron that picks them off and processes? (via a management command)


If all you need is I/O parallelism and not processing parallelism, you can avoid this problem by switch your processes to threads. Replace

from multiprocessing import Process


from threading import Thread

The Thread object has the same interface as Procsess


You could give more resources to Postgre, in Debian/Ubuntu you can edit :

nano /etc/postgresql/9.4/main/postgresql.conf

by replacing 9.4 by your postgre version .

Here are some useful lines that should be updated with example values to do so, names speak for themselves :

shared_buffers = 3000MB
temp_buffers = 800MB
effective_io_concurrency = 300
max_worker_processes = 80

Be careful not to boost too much these parameters as it might lead to errors with Postgre trying to take more ressources than available. Examples above are running fine on a Debian 8GB Ram machine equiped with 4 cores.

Leave a Reply

Your email address will not be published. Required fields are marked *