#!/usr/bin/env python3 """Flagship end-to-end latency and query ladder benchmark for Chapter 14 (Where Django leaks). Measures: 1. Per-layer component breakdown of one healthy `GET /editions/2026-11-25/` over 25 stories: URLResolver.resolve, WSGI middleware overhead, 3 ORM queries, and cached template render. 2. End-to-end endpoint cost across five real production modes over the same 25 stories: page-cache hit, healthy request, uncached templates, sync-middleware ASGI crossing, and lazy template N+1 leak (76 SQL queries). Writes recordings/ch14-bench.txt. """ from __future__ import annotations import asyncio import statistics import sys import time from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from harness import Recorder, boot_desk def median_us(fn, *, trials: int = 7, loops: int = 40) -> float: fn() # warmup samples = [] for _ in range(trials): t0 = time.perf_counter() for _ in range(loops): fn() samples.append((time.perf_counter() - t0) * 1e6 / loops) return statistics.median(samples) def main() -> None: seeded = boot_desk() from django.core.cache import cache from django.core.handlers.asgi import ASGIHandler from django.core.handlers.wsgi import WSGIHandler from django.http import HttpResponse from django.middleware.cache import FetchFromCacheMiddleware, UpdateCacheMiddleware from django.shortcuts import render from django.template import Engine from django.template.loader import get_template from django.test import RequestFactory, override_settings from django.urls import resolve from newsroom.models import Desk, Edition, Reporter, Story from newsroom.views import EditionListView rec = Recorder( "ch14-bench", "Django 6.1.3 benchmark on SQLite (in-memory): full-stack cost ladder (25 stories)", ) rf = RequestFactory() # Seed 21 extra published stories -> 25 stories in 2026-11-25 ed_today = seeded["editions"]["2026-11-25"] desks = list(Desk.objects.all()) reporters = list(Reporter.objects.all()) Story.objects.bulk_create( [ Story( headline=f"Ladder wire item #{i:02d}", slug=f"ladder-wire-{i:02d}", body="Dispatch paragraph for full-stack latency ladder.", priority=2, status=Story.Status.PUBLISHED, desk=desks[i % len(desks)], reporter=reporters[i % len(reporters)], edition=ed_today, ) for i in range(1, 22) ] ) # 1. Per-layer component breakdown of healthy GET /editions/2026-11-25/ with rec.block("1. Layer-by-layer breakdown of healthy GET /editions/2026-11-25/ (25 stories, 7 trials, us)"): # A. URL routing t_route = median_us(lambda: resolve("/editions/2026-11-25/"), trials=7, loops=500) # B. Full middleware stack overhead (with a no-op inner view) wsgi_noop = WSGIHandler() wsgi_noop.load_middleware() # Measure middleware chain alone by swapping _get_response_none -> noop view from django.conf import settings from django.utils.module_loading import import_string chain = lambda req: HttpResponse(b"ok") for mw_path in reversed(settings.MIDDLEWARE): chain = import_string(mw_path)(chain) def run_mw_only(): req = rf.get("/editions/2026-11-25/") chain(req) t_mw = median_us(run_mw_only, trials=7, loops=200) # C. ORM 3 queries (Edition + Story select_related + prefetch_related corrections) def run_orm_3(): ed = Edition.objects.get(slug="2026-11-25") rows = list( Story.objects.filter(edition=ed, status=Story.Status.PUBLISHED) .select_related("desk", "reporter") .prefetch_related("corrections") ) assert len(rows) == 25 t_orm = median_us(run_orm_3, trials=7, loops=40) # D. Cached template render over pre-fetched 25 stories prefetched_stories = list( Story.objects.filter(edition=ed_today, status=Story.Status.PUBLISHED) .select_related("desk", "reporter") .prefetch_related("corrections") ) tpl = get_template("newsroom/edition.html") def run_tpl_cached(): html = tpl.render({"edition": ed_today, "stories": prefetched_stories}) assert len(html) > 1000 t_tpl = median_us(run_tpl_cached, trials=7, loops=40) # E. Uncached template compile + render (disk + Lexer + Parser + render) uncached_engine = Engine( dirs=[str(Path(__file__).resolve().parents[1] / "desk" / "newsroom" / "templates")], debug=False, loaders=["django.template.loaders.filesystem.Loader"], ) def run_tpl_uncached(): from django.template import Context t = uncached_engine.get_template("newsroom/edition.html") html = t.render(Context({"edition": ed_today, "stories": prefetched_stories})) assert len(html) > 1000 t_tpl_uncached = median_us(run_tpl_uncached, trials=7, loops=20) total_healthy = t_route + t_mw + t_orm + t_tpl rec.emit(f"{'layer':<40s} {'median_us':>10s} {'share':>8s}") rec.emit(f"{'1. URLResolver.resolve()':<40s} {t_route:10.1f} {100.0 * t_route / total_healthy:7.1f}%") rec.emit(f"{'2. 8-layer MIDDLEWARE stack':<40s} {t_mw:10.1f} {100.0 * t_mw / total_healthy:7.1f}%") rec.emit(f"{'3. ORM (3 optimized SQL queries)':<40s} {t_orm:10.1f} {100.0 * t_orm / total_healthy:7.1f}%") rec.emit(f"{'4. Cached template render (25 rows)':<40s} {t_tpl:10.1f} {100.0 * t_tpl / total_healthy:7.1f}%") rec.emit(f"{' [sum of healthy layers]':<40s} {total_healthy:10.1f} {100.0:7.1f}%") rec.emit(f"{' [uncached template render alone]':<40s} {t_tpl_uncached:10.1f} {t_tpl_uncached / t_tpl:7.2f}x") # 2. End-to-end request ladder across 5 deployment/bug modes with rec.block("2. End-to-end GET /editions/2026-11-25/ across 5 modes (25 stories, 7 trials, us)"): edition_view = EditionListView.as_view() # Mode 1: Page cache hit (FetchFromCacheMiddleware) def rendered_healthy(request): resp = edition_view(request, issue_date="2026-11-25") resp.render() return resp cache.clear() cached_mw = UpdateCacheMiddleware(FetchFromCacheMiddleware(rendered_healthy)) cached_mw(rf.get("/editions/2026-11-25/")) # warm def run_cache_hit(): resp = cached_mw(rf.get("/editions/2026-11-25/")) assert resp.status_code == 200 t_hit = median_us(run_cache_hit, trials=7, loops=200) # Mode 2: Healthy WSGI end-to-end (3 SQL + cached templates) wsgi_app = WSGIHandler() wsgi_app.load_middleware() wsgi_env = rf.get("/editions/2026-11-25/").META.copy() wsgi_env["wsgi.url_scheme"] = "http" def run_wsgi_healthy(): req = rf.get("/editions/2026-11-25/") resp = wsgi_app.get_response(req) if hasattr(resp, "render"): resp.render() assert resp.status_code == 200 with rec.capture_sql(log=False) as sql_healthy: run_wsgi_healthy() t_healthy = median_us(run_wsgi_healthy, trials=7, loops=30) # Mode 3: Uncached templates end-to-end (3 SQL + disk/lex/parse per request) def run_uncached_e2e(): from django.template import Context req = rf.get("/editions/2026-11-25/") ed = Edition.objects.get(slug="2026-11-25") stories = list( Story.objects.filter(edition=ed, status=Story.Status.PUBLISHED) .select_related("desk", "reporter") .prefetch_related("corrections") ) t = uncached_engine.get_template("newsroom/edition.html") html = t.render(Context({"edition": ed, "stories": stories})) assert len(html) > 1000 t_uncached_e2e = median_us(run_uncached_e2e, trials=7, loops=20) # Mode 4: ASGI with sync-only TimingHeaderMiddleware crossing sync_to_async from asgiref.sync import async_to_sync from django.test import AsyncClient async def _run_asgi_batch(n: int): ac = AsyncClient() for _ in range(n): resp = await ac.get("/editions/2026-11-25/") assert resp.status_code == 200, f"got {resp.status_code}" async_to_sync(_run_asgi_batch)(1) # warmup asgi_samples = [] for _ in range(7): t0 = time.perf_counter() async_to_sync(_run_asgi_batch)(15) asgi_samples.append((time.perf_counter() - t0) * 1e6 / 15) t_asgi_sync = statistics.median(asgi_samples) # Mode 5: Lazy template N+1 leak (no select_related/prefetch_related -> 76 SQL) def run_n1_e2e(): req = rf.get("/editions/2026-11-25/") ed = Edition.objects.get(slug="2026-11-25") stories = Story.objects.filter(edition=ed, status=Story.Status.PUBLISHED) resp = render(req, "newsroom/edition.html", {"edition": ed, "stories": stories}) assert resp.status_code == 200 with rec.capture_sql(log=False) as sql_n1: run_n1_e2e() t_n1 = median_us(run_n1_e2e, trials=7, loops=10) rec.emit(f"{'endpoint_mode':<40s} {'sql':>4s} {'median_us':>10s} {'vs_healthy':>11s}") rec.emit(f"{'page cache hit (FetchFromCache)':<40s} {0:4d} {t_hit:10.1f} {t_hit / t_healthy:10.2f}x") rec.emit(f"{'healthy WSGI (SR+PR + cached tmpl)':<40s} {sql_healthy.count:4d} {t_healthy:10.1f} {1.00:10.2f}x") rec.emit(f"{'uncached templates (no cached.Loader)':<40s} {sql_healthy.count:4d} {t_uncached_e2e:10.1f} {t_uncached_e2e / t_healthy:10.2f}x") rec.emit(f"{'ASGI trapped by sync middleware':<40s} {sql_healthy.count:4d} {t_asgi_sync:10.1f} {t_asgi_sync / t_healthy:10.2f}x") rec.emit(f"{'lazy template N+1 leak (unprefetched)':<40s} {sql_n1.count:4d} {t_n1:10.1f} {t_n1 / t_healthy:10.2f}x") out = rec.write() print(f"wrote {out.relative_to(Path.cwd()) if out.is_relative_to(Path.cwd()) else out}") if __name__ == "__main__": main()