Django 6.1.3

14.2 Where Django leaks

Production outages that cross layer boundaries

Why do the worst Django bugs happen at the seams between two subsystems that each look clean on their own?

Code review almost always checks one file at a time: the view looks clean, the template looks clean, the task looks clean, the middleware looks clean. Yet when a request stitches them together at runtime, hidden laziness, ambient state, or transaction boundaries leak straight across the seam. Below are the five cross-layer failures that show up most reliably in production — each reproduced live on "desk/" with its exact Django 6.1.3 fix.

Figure 14.2 Every SQL count, ghost job count, and cache result is verified directly against ch14-leaks.

1. ORM × Template: lazy relations evaluated inside {% for %}

Because a QuerySet is lazy until iterated (Chapter 7), a view that passes "Story.objects.filter(edition=edition)" into render(...) executes zero queries inside the view function itself — every SQL statement fires later inside ForNode.render and Variable._resolve_lookup (Chapter 10) while rendering "newsroom/edition.html"!

Watch what happens on 25 stories in "desk/": healthy select_related("desk", "reporter").prefetch_related("corrections") renders in 2 SQL queries (once "edition" is loaded); removing them explodes to 80 SQL queries! Look too at what Django 6.1’s new QuerySet.fetch_mode reveals:

Recorded on Django 6.1.3 ch14-leaks script
1. ORM x Template seam: lazy N+1, FETCH_PEERS, and FETCH_RAISE
  edition_25_stories: healthy_sql=2 lazy_template_n1_sql=80 fetch_peers_sql=32
  fetch_raise_caught = 'Fetching of Story.desk blocked.'

2. Transaction × Tasks: ghost jobs leaking out of rolled-back atomic()

Database transactions only roll back database state — never external brokers, emails, HTTP calls, or task queues (Chapters 9 and 12). Calling "build_edition_digest.enqueue(edition.pk)" directly inside django.db.transaction.atomic causes two failure modes: an external worker can wake up before COMMIT and fail with "DoesNotExist", OR a later exception rolls back the transaction while the enqueued task still runs as a ghost job! Wrapping enqueueing inside django.db.transaction.on_commit eliminates both:

Recorded on Django 6.1.3 ch14-leaks script
2. Transaction x Tasks seam: ghost job on rollback vs on_commit
  rollback_task_leak: direct_enqueue_ghost_jobs=1 on_commit_ghost_jobs=0

3. Middleware × ASGI: one synchronous middleware trapping async endpoints

As we traced inside BaseHandler.load_middleware in Chapter 3, ASGI only runs end-to-end on the event loop when every middleware between ASGIHandler and your async def view sets "async_capable = True". One legacy synchronous middleware (like "desk/"'s "TimingHeaderMiddleware") forces BaseHandler.adapt_method_mode to wrap the boundary in sync_to_async thread hops — adding +3.1 ms per request in our Chapter 14 ladder and risking thread-pool saturation under high concurrency!

Recorded on Django 6.1.3 ch14-leaks script
3. Middleware x ASGI seam: sync middleware traps async views
  pure_async_stack: chain_is_coro=True sync_only_middleware=[]
  mixed_stack_with_sync_mw: chain_is_coro=True sync_only_middleware=['TimingHeaderMiddleware']

4. QuerySet × Memory: if qs: hydrating an entire table before slicing

Because QuerySet.__bool__ calls QuerySet._fetch_all (Chapter 7), writing "if qs:" before taking the first page "qs[:5]" fetches and hydrates every matching row into "qs._result_cache" (25 models in memory on "desk/" — or 250,000 models in production, blowing up worker RAM before slicing 5!). Calling QuerySet.exists runs SELECT 1 ... LIMIT 1 and leaves "_result_cache" at None:

Recorded on Django 6.1.3 ch14-leaks script
4. QuerySet x Memory seam: `if qs:` before `qs[:5]` vs `exists()`
  if_qs_then_slice: sql=1 rows_hydrated=25 page_len=5
  exists_then_slice: sql=2 base_qs_cache=None page_len=5

5. Cache × Auth/ORM: stale in-memory caches surviving database writes

Finally, two invisible per-object Python caches do not invalidate when the database changes underneath them (Chapters 7 and 11): ModelBackend caches every permission string on "user._perm_cache" for the lifetime of that User instance, and an evaluated QuerySet caches its hydrated rows in "qs._result_cache" even after an external QuerySet.update modifies the row in SQL!

Recorded on Django 6.1.3 ch14-leaks script
5. Cache x Auth/ORM seam: stale _perm_cache and _result_cache
  stale_perm_cache: before=False after_grant_same_obj=False fresh_user=True
  stale_qs_cache: before=1 after_db_update_same_qs=1 fresh_get=9

Look at both lines: "after_grant_same_obj=False" while "fresh_user=True", and "after_db_update_same_qs=1" while "fresh_get=9"! Whenever a view or test mutates permissions or runs bulk SQL updates, re-fetch a fresh instance or build a fresh QuerySet.

Now that the five cross-layer seams are concrete, we gather every modern Django 5.x/6.1.3 architectural shift we uncovered across the book into one quick-reference guide in Django 6.x shifts that trip up older mental models.