---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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`** (`django/db/utils.py:ConnectionHandler`), and `"connection"`, a thin `ConnectionProxy` (`django/utils/connection.py:ConnectionProxy`) forwarding every attribute lookup to `"connections['default']"`.

`ConnectionHandler` subclasses `BaseConnectionHandler` (`django/utils/connection.py:BaseConnectionHandler`), storing per-alias wrappers inside `asgiref.local.Local` (`asgiref:asgiref/local.py: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` (`django/db/utils.py:ConnectionHandler.create_connection`), which dynamically imports `"<ENGINE>.base"` via `load_backend` (`django/db/utils.py:load_backend`) and constructs that backend's **`BaseDatabaseWrapper`** (`django/db/backends/base/base.py:BaseDatabaseWrapper`) subclass. Still no socket opens! Look at the exact moment a socket is created inside `BaseDatabaseWrapper._cursor` (`django/db/backends/base/base.py: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` (`django/db/backends/base/base.py:BaseDatabaseWrapper.ensure_connection`) checks `if self.connection is None:` and calls `BaseDatabaseWrapper.connect` (`django/db/backends/base/base.py: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 (`django/db/backends/signals.py:connection_created`).

## `"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` (`django/db/__init__.py:reset_queries`) on `request_started`, and `close_old_connections` (`django/db/__init__.py: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` (`django/db/backends/base/base.py:BaseDatabaseWrapper.close_if_unusable_or_obsolete`), which resets `"health_check_done = False"` and runs three checks in order:

- **Autocommit drift:** If `BaseDatabaseWrapper.get_autocommit` no longer matches `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:** `DatabaseErrorWrapper` (`django/db/utils.py:DatabaseErrorWrapper`) translates every PEP-249 driver exception into Django's hierarchy (`DataError`, `IntegrityError`, `OperationalError`, `ProgrammingError`, `InterfaceError`) and sets `"errors_occurred = True"` on every error **except `DataError` and `IntegrityError`** (lines 92–93 — because constraint violations leave the socket healthy!). If `"errors_occurred"` is `True`, Django probes `BaseDatabaseWrapper.is_usable` and drops the connection if the probe fails.
- **Persistent connection age (**`"CONN_MAX_AGE"`**):** **`"CONN_MAX_AGE"`** defaults to **`0`** (`django/db/utils.py:ConnectionHandler.configure_settings`). When `"CONN_MAX_AGE = 0"`, `"close_at"` equals `"time.monotonic() + 0"`, so `"time.monotonic() >= self.close_at"` is **always `True`** at `"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"` tells `close_if_health_check_failed` to call `is_usable()` before the *first* query of each new request on a reused persistent connection, catching silently severed sockets before user code sees an `OperationalError`.

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

```text recording=ch09-database
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` (`django/db/utils.py: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](backends.md).
