11.1 Sessions, auth, and the admin
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 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. 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 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:
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 simply stores "session_key" and initializes "self and "self.
Storage is touched only when code reads or writes a key ("request, "key in request, or "request), which routes through SessionBase:
- First read sets
"accessed = True"and loads"selfonce from the configured backend (._session_cache" load()), caching the decoded dict in memory for the remainder of the request. - 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) bypasses.session['cart'].append(item)" SessionBase, so.__setitem__ "modified"staysFalseand your change is silently discarded unless you assign"requestexplicitly!.session .modified = True"
On the way out, SessionMiddleware inspects "accessed", "modified", and "request:
- 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", butpatch_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: Calls.status_code < 500" "request(skipping saves on.session .save()" 5xxserver 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,UpdateErroris caught and converted intoSessionInterrupted. - Session emptied while browser still holds
"sessionid": Calls"responseand adds.delete_cookie(...)" "Vary: Cookie".
Comparing Django’s four session backends
Every backend subclasses SessionBase and swaps how load() and save() persist the dictionary encoded by SessionBase (SessionBase, which uses django with JSONSerializer by default):
- Database: Stores rows in
"django_session". Durable across restarts, supports server-side revocation, and runs1SQL"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) rather than purged automatically..now() - Cached DB: Subclasses the DB store with write-through caching:
load()checks the configured cache first (0SQL queries on warm reads!), falls back to"django_session"on a cache miss and repopulates the cache, andsave()writes to both DB and cache. Best default for high-read sites that cannot lose sessions on a cache restart. - Cache: Cache-only (
0DB queries), fastest writes, but evicting cache memory or restarting Redis logs users out immediately. - Signed cookies: Zero backend storage —
save()encodes and HMAC-signs the entire session dictionary directly into the"sessionid"cookie value viasigning.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":
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 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 until a view actually reads "request.user" — which we trace next in LazyObject, get_user, and session hash verification.