Django 6.1.3

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.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. 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.process_request:

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__ 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:

  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 inspects "accessed", "modified", and "request.session.is_empty()":

Comparing Django’s four session backends

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

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":

Recorded on Django 6.1.3 ch11-auth script
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.