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 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/, 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 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 enforces thread ownership unless a test explicitly calls BaseDatabaseWrapper).
When code first indexes "connections['default']", BaseConnectionHandler calls ConnectionHandler, 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:
BaseDatabaseWrapperchecks whether an existing persistent connection passed its per-request health probe (.close_if_health_check_failed "CONN_HEALTH_CHECKS").BaseDatabaseWrapperchecks.ensure_connection if selfand calls.connection is None: BaseDatabaseWrapper..connect BaseDatabaseWrapperresets transaction state (.connect "in_atomic_block = False","savepoint_ids = []","needs_rollback = False","run_on_commit = []"), computes"close_at = None if max_age is None else time, calls backend-specific.monotonic() + max_age" get_new_connectionandset_autocommit, runsinit_connection_state, and fires theconnection_createdsignal.
"CONN_MAX_AGE", "CONN_HEALTH_CHECKS", and request_finished
At module import time, django/ 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 — 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, which resets "health_check_done = False" and runs three checks in order:
- Autocommit drift: If
BaseDatabaseWrapperno longer matches.get_autocommit settings_dict["AUTOCOMMIT"](for instance, a bug left manual transaction mode on), Django closes the connection immediately rather than handing a dirty transaction to the next request. - Prior driver errors:
DatabaseErrorWrappertranslates every PEP-249 driver exception into Django’s hierarchy (DataError,IntegrityError,OperationalError,ProgrammingError,InterfaceError) and sets"errors_occurred = True"on every error exceptDataErrorandIntegrityError(lines 92–93 — because constraint violations leave the socket healthy!). If"errors_occurred"isTrue, Django probesBaseDatabaseWrapperand drops the connection if the probe fails..is_usable - Persistent connection age (
"CONN_MAX_AGE"):"CONN_MAX_AGE"defaults to0. When"CONN_MAX_AGE = 0","close_at"equals"time, so.monotonic() + 0" "timeis always.monotonic() >= self .close_at" Trueat"request_finished"— closing the database connection at the end of every single HTTP request! Setting"CONN_MAX_AGE = 60"reuses the socket across requests on that worker thread for 60 seconds; setting"CONN_MAX_AGE = None"keeps it open indefinitely until an error or failed health check drops it. Enabling"CONN_HEALTH_CHECKS = True"tellsclose_if_health_check_failedto callis_usable()before the first query of each new request on a reused persistent connection, catching silently severed sockets before user code sees anOperationalError.
Watch lazy connection creation, request-signal receivers, and DatabaseErrorWrapper’s selective "errors_occurred" flag live on "desk/":
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.