Database Connection Pooling

A snippet showing how to set up database connection pooling.


# Example: pgbouncer in front of Postgres
# Configure your DATABASES['default']['HOST'] to point to pgbouncer host:port.
      

# settings.py (django-db-geventpool or similar third-party, optional)

# Example with django-db-geventpool (third-party)
# pip install django-db-geventpool

DATABASES = {
    "default": {
        "ENGINE": "django_db_geventpool.backends.postgresql_psycopg2",
        "NAME": "app",
        "USER": "app",
        "PASSWORD": "secret",
        "HOST": "127.0.0.1",
        "PORT": "6432",  # pgbouncer port
        "CONN_MAX_AGE": 0,
        "OPTIONS": {"MAX_CONNS": 20},
    }
}
      
Explanation:
  • Connection pooling allows Django to reuse database connections, avoiding the overhead of creating a new connection for every request.
  • Tools like pgbouncer or third-party Django database backends manage pools of connections efficiently.
  • Especially critical for large sites, serverless, or asynchronous environments where connection churn can impact performance and stability.
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.