Django 6.1.3

Part III · Presentation and systems

Chapter 12: Caching, signals, tasks, and files

The promiseBuilt-in services stay out of your way.

The machineryCache middleware ordering traps, the hidden synchronous cost of Signal.send, Django 6’s native django.tasks framework, file storage backends, and thread-local localisation.

Beyond requests, the ORM, templates, forms, and auth, every production Django application leans on five horizontal services that ship inside core: django/core/cache/, django/dispatch/, Django 6’s brand-new django/tasks/, django/core/files/, and django/utils/translation/ + django/utils/timezone.py. On the surface they look like effortless helpers — drop in a cache middleware, connect a post_save receiver, decorate a background task with @task, attach a FileField, or flip a timezone.

Open the source and each service reveals one sharp operational constraint that routinely bites production teams. UpdateCacheMiddleware and FetchFromCacheMiddleware must wrap "MIDDLEWARE" at opposite ends of the onion so "Vary" headers are learned after SessionMiddleware and LocaleMiddleware finish; Signal.send is a strictly synchronous Python loop (and weak=True silently garbage-collects local receivers); Django 6.1’s Task and TaskResult enforce JSON normalization and module-level importability across ImmediateBackend and DummyBackend; FileDescriptor wraps paths into lazy FieldFile proxies and intentionally never deletes files when rows are deleted; and active languages and timezones live in asgiref.local.Local ambient state.

Why whole-site caching splits into two opposite middleware

Figure 12.1 Every SQL count and microsecond bar is parsed directly from ch12-services and ch12-bench. When the two middleware sit at opposite ends of "MIDDLEWARE", a cache hit serves "desk/"'s front edition in 91.1 us (24.50x faster and 0 SQL queries vs. 3), while UpdateCacheMiddleware still sees "Vary: Cookie" plus "Set-Cookie" on personalized responses and refuses to cache them!

Five horizontal services in six stops

We start inside CacheHandler, BaseCache.make_key, and LocMemCache pickling, then trace the two-piece page-cache middleware and learn_cache_key. Next we open Signal and measure the hidden N+1 cost of synchronous "post_save" receivers on "desk/".

Then we examine Django 6’s native django/tasks/ architecture — running "desk/"'s "build_edition_digest" through ImmediateBackend, DummyBackend, and django.db.transaction.on_commit — before finishing Part III with StorageHandler, FieldFile laziness, and asgiref.local.Local language and timezone boundaries.

We start with cache backends and key versioning in Cache backends, key versioning, and stampedes.