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

# Session stores, cookies, and dirty tracking

How does `SessionMiddleware` avoid hitting the session store on requests that never touch the session, and when does `SessionBase.modified` force a write?

HTTP is stateless, so Django carries per-browser state across requests through a single cookie (named `"sessionid"` by default) wired into **`SessionMiddleware`** (`django/contrib/sessions/middleware.py:SessionMiddleware`). If Django loaded and re-saved the session row on every static asset, JSON API call, or health check, the session table would become an immediate database bottleneck. Instead, **`SessionBase`** (`django/contrib/sessions/backends/base.py:SessionBase`) uses lazy loading and two boolean flags — `"accessed"` and `"modified"` — to do the minimum storage work required.

## Lazy loading and the `accessed` / `modified` state machine

Open `SessionMiddleware.process_request` (`django/contrib/sessions/middleware.py:SessionMiddleware.process_request`):

```python
session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
request.session = self.SessionStore(session_key)
```

Notice what does **not** happen: no SQL query, no cache lookup, and no cookie decoding. `SessionBase.__init__` (`django/contrib/sessions/backends/base.py:SessionBase.__init__`) simply stores `"session_key"` and initializes `"self.accessed = False"` and `"self.modified = False"`.

Storage is touched only when code reads or writes a key (`"request.session.get(...)"`, `"key in request.session"`, or `"request.session[key] = value"`), which routes through `SessionBase._get_session` (`django/contrib/sessions/backends/base.py:SessionBase._get_session`):

1. **First read sets `"accessed = True"`** and loads `"self._session_cache"` once from the configured backend (`load()`), caching the decoded dict in memory for the remainder of the request.
2. **Any top-level mutation sets `"modified = True"`** (`__setitem__`, `__delitem__`, `pop`, `update`, `clear`). Notice the classic Python dict trap: mutating a *nested* list or dict in place (`"request.session['cart'].append(item)"`) bypasses `SessionBase.__setitem__`, so `"modified"` stays `False` and your change is silently discarded unless you assign `"request.session.modified = True"` explicitly!

On the way out, `SessionMiddleware.process_response` (`django/contrib/sessions/middleware.py:SessionMiddleware.process_response`) inspects `"accessed"`, `"modified"`, and `"request.session.is_empty()"`:

- **Session untouched (`accessed=False, modified=False`):** Zero queries, no `"Set-Cookie"` header, and **no `"Vary: Cookie"` header** — leaving downstream CDNs and reverse proxies free to cache the response across users!
- **Session read only (`accessed=True, modified=False`):** One read query, no write, no `"Set-Cookie"`, **but `patch_vary_headers(response, ("Cookie",))` adds `"Vary: Cookie"`** because the response may have branched on session data (such as checking whether a user is logged in).
- **Session modified (or `"SESSION_SAVE_EVERY_REQUEST=True"`) and `"response.status_code < 500"`:** Calls `"request.session.save()"` (skipping saves on `5xx` server errors so a crashing view does not corrupt session state!), emits `"Set-Cookie"` with `"HttpOnly"` and `"SameSite"` flags, and adds `"Vary: Cookie"`. If a concurrent request deleted the session row in the meantime, `UpdateError` (`django/contrib/sessions/backends/base.py:UpdateError`) is caught and converted into `SessionInterrupted` (`django/contrib/sessions/exceptions.py:SessionInterrupted`).
- **Session emptied while browser still holds `"sessionid"`:** Calls `"response.delete_cookie(...)"` and adds `"Vary: Cookie"`.

## Comparing Django's four session backends

Every backend subclasses `SessionBase` and swaps how `load()` and `save()` persist the dictionary encoded by `SessionBase.encode` (`django/contrib/sessions/backends/base.py:SessionBase.encode`, which uses `django.core.signing.dumps(..., compress=True)` with `JSONSerializer` by default):

- **Database (`django/contrib/sessions/backends/db.py:SessionStore`):** Stores rows in `"django_session"`. Durable across restarts, supports server-side revocation, and runs `1` SQL `"SELECT"` on first read plus `"UPDATE"`/`"INSERT"` on save. Requires periodic `"clearsessions"` cleanup because expired rows are filtered at read time (`expire_date__gt=timezone.now()`) rather than purged automatically.
- **Cached DB (`django/contrib/sessions/backends/cached_db.py:SessionStore`):** Subclasses the DB store with write-through caching: `load()` checks the configured cache first (`0` SQL queries on warm reads!), falls back to `"django_session"` on a cache miss and repopulates the cache, and `save()` writes to *both* DB and cache. Best default for high-read sites that cannot lose sessions on a cache restart.
- **Cache (`django/contrib/sessions/backends/cache.py:SessionStore`):** Cache-only (`0` DB queries), fastest writes, but evicting cache memory or restarting Redis logs users out immediately.
- **Signed cookies (`django/contrib/sessions/backends/signed_cookies.py:SessionStore`):** Zero backend storage — `save()` encodes and HMAC-signs the entire session dictionary directly into the `"sessionid"` cookie value via `signing.dumps` (`django/core/signing.py:dumps`). Zero DB/cache latency, *but* payload size is capped by browser cookie limits (`~4 KB`), data is visible (signed, **not** encrypted — anyone can base64-decode it!), and you cannot revoke an old cookie server-side without changing `"SECRET_KEY"` or invalidating `"HASH_SESSION_KEY"`.

Watch untouched, read-only, and modified requests pass through `SessionMiddleware` on `"desk/"`, alongside SQL counts for `"cached_db"` (cold miss vs. warm hit) and `"signed_cookies"`:

```text recording=ch11-auth
1. SessionMiddleware lazy access, modified flag, and stores
  untouched: sql=0 accessed=False modified=False vary=None set_cookie=False
  read_only: sql=1 accessed=True modified=False vary='Cookie' set_cookie=False
  modified:  sql=3 accessed=True modified=True vary='Cookie' set_cookie=True
  stores: cached_db_miss_sql=1 cached_db_hit_sql=0 signed_cookie_sql=0 values=['metro', 'metro', 'metro']
```

Look closely at line 5 (`"read_only"`): merely calling `"request.session.get(...)"` flipped `"accessed=True"` and stamped `"Vary: Cookie"` onto the response! That is why Django's authentication layer goes out of its way to avoid even *touching* `"request.session"` until a view actually reads `"request.user"` — which we trace next in [LazyObject, get_user, and session hash verification](lazy-user.md).
