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

# 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.

```text figure=cross-layer-leaks
Five cross-layer production leaks reproduced on desk/ and their Django 6.1 guardrails

1. ORM x TEMPLATE:  lazy edition.html fires 80 SQL (vs 2)        -> select_related + prefetch_related + FETCH_RAISE
2. TX x TASKS:      enqueue() inside atomic() -> 1 ghost job     -> transaction.on_commit(task.enqueue) -> 0 ghosts
3. MW x ASGI:       1 sync MW traps async chain on thread hops   -> mark async_capable = True end to end
4. QS x MEMORY:     if qs: before qs[:5] hydrates all 25 rows    -> use qs.exists() before slicing (cache stays None)
5. CACHE x STATE:   stale _perm_cache (False) & _result_cache    -> re-fetch User.objects.get() / fresh QuerySet
```

*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` (`django/db/models/query.py: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` (`django/db/models/query.py:QuerySet.fetch_mode`) reveals:

- **`FETCH_PEERS` (`django/db/models/fetch_modes.py:FETCH_PEERS`):** Automatically batches the `ForeignKey` descriptors (desk and reporter) across all `25` peer instances (`50` queries → `2` batched IN queries!), dropping total SQL from `80` to **`32`** — *but* reverse `ForeignKey` managers like `"story.corrections.all"` still fire per-row queries unless you explicitly add `prefetch_related("corrections")`!
- **`FETCH_RAISE` (`django/db/models/fetch_modes.py:FETCH_RAISE`):** Turns silent N+1 queries into an instant, unmistakable **`FieldFetchBlocked`** (`django/core/exceptions.py:FieldFetchBlocked`) exception (`"Fetching of Story.desk blocked."`) during development and tests!

```text recording=ch14-leaks
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` (`django/db/transaction.py: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` (`django/db/transaction.py:on_commit`) eliminates both:

```text recording=ch14-leaks
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` (`django/core/handlers/base.py: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!

```text recording=ch14-leaks
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__` (`django/db/models/query.py: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` (`django/db/models/query.py:QuerySet.exists`) runs `SELECT 1 ... LIMIT 1` and leaves `"_result_cache"` at `None`:

```text recording=ch14-leaks
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!

```text recording=ch14-leaks
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](modern-django.md).
