Django DB Connection Pool

1.2.6 · active · verified Thu Apr 16

django-db-connection-pool is a Python library that provides database connection pooling components for Django, supporting MySQL, Oracle, PostgreSQL, and JDBC-compatible databases. It is based on SQLAlchemy's connection pooling mechanisms, designed to improve performance and resource management in multiprocessing and multithreading Django projects by reusing database connections. The current version is 1.2.6, and it sees active maintenance.

Common errors

Warnings

Install

Imports

Quickstart

To quickly integrate `django-db-connection-pool`, update your `DATABASES` setting in `settings.py` by changing the `ENGINE` to the appropriate `dj_db_conn_pool.backends` path. It is crucial to set `CONN_MAX_AGE` to `0` or `None` to prevent Django's built-in persistent connection logic from conflicting with the connection pool. You can further customize pooling behavior using the `POOL_OPTIONS` dictionary, which accepts parameters like `POOL_SIZE`, `MAX_OVERFLOW`, `RECYCLE`, and `TIMEOUT`.

import os

# settings.py

DATABASES = {
    'default': {
        'ENGINE': 'dj_db_conn_pool.backends.postgresql',
        'NAME': os.environ.get('DB_NAME', 'mydatabase'),
        'USER': os.environ.get('DB_USER', 'myuser'),
        'PASSWORD': os.environ.get('DB_PASSWORD', 'mypassword'),
        'HOST': os.environ.get('DB_HOST', 'localhost'),
        'PORT': os.environ.get('DB_PORT', '5432'),
        # Important: Set CONN_MAX_AGE to 0 or None when using an external pooler to avoid conflicts
        'CONN_MAX_AGE': 0,
        'POOL_OPTIONS': {
            'POOL_SIZE': 10,
            'MAX_OVERFLOW': 5,
            'RECYCLE': 3600, # Recycle connections after 1 hour
            'TIMEOUT': 30 # Connection checkout timeout
        }
    }
}

# Example of using a connection (standard Django ORM operations apply)
# from django.db import connections
# from myapp.models import MyModel
#
# try:
#    obj = MyModel.objects.first()
#    print(obj)
# except Exception as e:
#    print(f"Database error: {e}")

view raw JSON →