Django 6.1.3

9.1 Connections, transactions, and migrations

Connection handlers, CONN_MAX_AGE, and teardown

How does ConnectionHandler isolate one connection per thread or coroutine, when does Django actually open a socket to the database, and what runs at request_finished?

Importing "from django.db import connection, connections" during Django startup opens zero database sockets. Even touching "connections['default']" only instantiates a Python wrapper whose underlying driver handle is None. Django stays completely lazy until the first SQL query or transaction call demands a live cursor — and then ties that socket’s lifetime tightly to the thread and the HTTP request cycle.

ConnectionHandler, Local(thread_critical=True), and lazy sockets

In django/db/__init__.py, Django exposes two module-level singletons: "connections", an instance of ConnectionHandler, and "connection", a thin ConnectionProxy forwarding every attribute lookup to "connections['default']".

ConnectionHandler subclasses BaseConnectionHandler, storing per-alias wrappers inside asgiref.local.Local with "thread_critical = True". Setting "thread_critical = True" guarantees two invariants simultaneously: separate OS threads never share the same database socket (protecting non-thread-safe DB-API drivers), and separate async coroutines do not accidentally interleave transactions over one socket (BaseDatabaseWrapper.validate_thread_sharing enforces thread ownership unless a test explicitly calls BaseDatabaseWrapper.inc_thread_sharing).

When code first indexes "connections['default']", BaseConnectionHandler.__getitem__ calls ConnectionHandler.create_connection, which dynamically imports "<ENGINE>.base" via load_backend and constructs that backend’s BaseDatabaseWrapper subclass. Still no socket opens! Look at the exact moment a socket is created inside BaseDatabaseWrapper._cursor:

  1. BaseDatabaseWrapper.close_if_health_check_failed checks whether an existing persistent connection passed its per-request health probe ("CONN_HEALTH_CHECKS").
  2. BaseDatabaseWrapper.ensure_connection checks if self.connection is None: and calls BaseDatabaseWrapper.connect.
  3. BaseDatabaseWrapper.connect resets transaction state ("in_atomic_block = False", "savepoint_ids = []", "needs_rollback = False", "run_on_commit = []"), computes "close_at = None if max_age is None else time.monotonic() + max_age", calls backend-specific get_new_connection and set_autocommit, runs init_connection_state, and fires the connection_created signal.

"CONN_MAX_AGE", "CONN_HEALTH_CHECKS", and request_finished

At module import time, django/db/__init__.py wires two receivers onto Django’s HTTP request signals: reset_queries on request_started, and close_old_connections on both request_started and request_finished. Notice both functions iterate "connections.all(initialized_only=True)" — so a view that never touched the database pays zero teardown cost and never initializes a wrapper just to close it.

For every initialized connection, close_old_connections calls BaseDatabaseWrapper.close_if_unusable_or_obsolete, which resets "health_check_done = False" and runs three checks in order:

Watch lazy connection creation, request-signal receivers, and DatabaseErrorWrapper’s selective "errors_occurred" flag live on "desk/":

Recorded on Django 6.1.3 ch09-database script
1. ConnectionHandler laziness, request signals, and DatabaseErrorWrapper
  before_query: connection_is_none=True autocommit=False CONN_MAX_AGE=0 CONN_HEALTH_CHECKS=False
  after_ensure_connection: connection_is_none=False close_at_is_set=True health_check_done=True
  request_started_db_receivers = ['django.db.reset_queries', 'django.db.close_old_connections']
  request_finished_db_receivers = ['django.db.close_old_connections']
  errors_occurred: after_IntegrityError=False after_OperationalError=True

Notice two practical consequences straight from that trace. First, close_old_connections runs only on HTTP requests — long-lived background workers and custom management commands never fire request_started or request_finished, so worker loops must call close_old_connections() explicitly between jobs or they will eventually hit idle-connection timeouts! Second, multi-database routing lives right beside ConnectionHandler in ConnectionRouter, which walks "DATABASE_ROUTERS" for db_for_read, db_for_write, allow_relation, and allow_migrate before falling back to "default".

Each BaseDatabaseWrapper created by ConnectionHandler is only the thin entry point to a much larger backend plug-in. We open the five-class anatomy that separates SQLite, PostgreSQL, MySQL, and Oracle next in How database backends diverge beneath one API.