Skip to main content

Connection Pooling with Django and SQLAlchemy

Project description


MySQL Connection Pooling with Django(>2.0.0) and SQLAlchemy(>=1.2.7).


If CONN_MAX_AGE not set in you settings, Django will establish a new MySQL connection for each request and close it after the request.

So if where are too many connections to be handled, it will establish too many connections until running out of MySQL max_connections.

Then, MySQL will return the error: ERROR 1040 (08004): Too many connections.

It's necessary to maintain a connection pool for a robust Django project.


Reference: MySQL Connection Pooling with Django and SQLAlchemy

Make MySQLdb Database get_new_connection from connection pool with SQLAlchemy QueuePool.

So all we need to custom a Database managed by connection pool and get new connection from the pool.

pip install mysqlclient
pip install SQLAlchemy

core code:

import MySQLdb as Database
import sqlalchemy.pool as pool
from sqlalchemy.pool import QueuePool
from django.db.backends.mysql.base import DatabaseWrapper as _DatabaseWrapper

Database = pool.manage(Database, poolclass=QueuePool, **settings.SQLALCHEMY_QUEUEPOOL)

class DatabaseWrapper(_DatabaseWrapper):

    def get_new_connection(self, conn_params):
        # return a mysql connection
        databases = settings.DATABASES
        alias = None
        for _alias in databases:
            if databases[_alias]['NAME'] == conn_params['db']:
                alias = _alias
        client_flag = conn_params['client_flag']

        conn_params = databases[alias]
        return Database.connect(


pip install django-conn-pool

    'pool_size': 10,
    'max_overflow': 10,
    'timeout': 5,
    'recycle': 119,

    'default': {
        'ENGINE': 'django_conn_pool.mysql',
        'HOST': '',
        'NAME': 'xxx',
        'USER': 'xxx',
        'PASSWORD': 'xxx',
        'PORT': 3306,
    'other': {
        'ENGINE': 'django_conn_pool.mysql',
        'HOST': '',
        'NAME': 'xxx',
        'USER': 'xxx',
        'PASSWORD': 'xxx',
        'PORT': 3306,


If python runserver is OK, now you can use load testing utility Siege to test.

siege -r 2 -c 1000 -d 0 http://xxx  # siege --help

You can compare the MySQL process list count to the before, and it should work.

Btw, you should get a sqlalchemy.exc.TimeoutError: exception if it does not get a connection during the request.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-conn-pool-2.1.0.tar.gz (3.7 kB view hashes)

Uploaded source

Built Distribution

django_conn_pool-2.1.0-py3-none-any.whl (5.2 kB view hashes)

Uploaded py3

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page