Full answer
Opening a PostgreSQL connection costs a TCP handshake, TLS, authentication and a new server process, often a few milliseconds. Doing it on every request adds latency and load.
Django's built-in behaviour:
- Connections are per thread (and per database alias). The first query in a thread opens one.
request_startedandrequest_finishedsignals callclose_old_connections(). WithCONN_MAX_AGE = 0(default) the connection closes after each request.CONN_MAX_AGE = 60keeps the connection open for reuse for up to 60 seconds;Nonemeans forever. Errors also cause a close.CONN_HEALTH_CHECKS = True(Django 4.1+) checks a persistent connection before reusing it in a new request, so a database restart does not cause a failed request.
Native pooling (Django 5.1+, PostgreSQL with psycopg 3):
DATABASES = {"default": {
"ENGINE": "django.db.backends.postgresql",
"OPTIONS": {"pool": {"min_size": 2, "max_size": 10, "timeout": 10}},
}}This uses psycopg_pool inside each process. Do not combine it with a non-zero CONN_MAX_AGE.
Sizing: every process has its own pool or persistent connections. 8 servers x 5 Gunicorn workers x 4 threads = 160 possible connections. PostgreSQL's default max_connections is 100, and each connection uses server memory. That is why teams put PgBouncer (in transaction pooling mode) between apps and the database: thousands of client connections share a small number of server connections. In transaction mode, avoid session-level features (server-side cursors, SET statements, advisory session locks); Django's DISABLE_SERVER_SIDE_CURSORS = True exists for this.
Async and threads: each thread gets its own connection, so thread pools inside views multiply connections. Close connections in long-running background threads with connections.close_all().
import os
import sys
import types
import django
from django.conf import settings
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
# Needs a running PostgreSQL server; connection details come from the usual PG* variables
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": os.environ.get("PGDATABASE", "school"),
"USER": os.environ.get("PGUSER", "postgres"),
"PASSWORD": os.environ.get("PGPASSWORD", ""),
"HOST": os.environ.get("PGHOST", "localhost"),
"PORT": os.environ.get("PGPORT", "5432"),
}},
)
django.setup()
from django.core.signals import request_finished, request_started
from django.db import connection, connections
def backend_pid():
with connection.cursor() as cur:
cur.execute("SELECT pg_backend_pid()")
return cur.fetchone()[0]
def fake_request():
request_started.send(sender=None)
pid = backend_pid()
request_finished.send(sender=None)
return pid
connections["default"].settings_dict["CONN_MAX_AGE"] = 0
connection.close()
a, b = fake_request(), fake_request()
print("CONN_MAX_AGE=0, new connection each request:", a != b)
connections["default"].settings_dict["CONN_MAX_AGE"] = 60
connections["default"].settings_dict["CONN_HEALTH_CHECKS"] = True
connection.close()
a, b = fake_request(), fake_request()
print("CONN_MAX_AGE=60, same connection reused:", a == b)
connection.close()
# Native pool (Django 5.1+, psycopg 3 with the pool extra)
from django.db.backends.postgresql.base import DatabaseWrapper
pooled = DatabaseWrapper({**connections["default"].settings_dict, "CONN_MAX_AGE": 0,
"OPTIONS": {"pool": {"min_size": 1, "max_size": 4}}}, alias="pooled")
print("pool configured:", pooled.pool is not None, "max_size:", pooled.pool.max_size)
pooled.close_pool()
Standalone script that needs PostgreSQL and `pip install "psycopg[binary]"`. Set PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE to point at a scratch database before running it. The pool check needs `pip install "psycopg[binary,pool]"`. Ran on PostgreSQL 17; request start and finish are simulated by sending Django's request signals. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): CONN_MAX_AGE=0, new connection each request: True CONN_MAX_AGE=60, same connection reused: True pool configured: True max_size: 4
Key points
- Connections are per thread and per alias
- CONN_MAX_AGE = 0 closes after each request; > 0 reuses
- CONN_HEALTH_CHECKS validates reused connections
- Django 5.1 adds native PostgreSQL pooling with psycopg 3
- Count connections across all processes; use PgBouncer at scale
Common mistakes
- Raising CONN_MAX_AGE without counting total connections across all workers
- Combining Django's native pool with persistent connections
- Using PgBouncer transaction mode with server-side cursors still enabled
- Leaving connections open in background threads
Follow-ups
- How would you size a connection pool for 20 app servers?
- What changes when you put PgBouncer in transaction mode?
- Why might persistent connections cause errors after a database failover?
Tips
- Explain the per-thread model first
- Do the connection arithmetic out loud
- Mention the Django 5.1 native pool and PgBouncer as options