12.4 Caching, signals, tasks, and files
Django 6’s django.tasks framework
How does Django 6’s built-in django.tasks separate task definition from execution backend, and what actually runs when you call Task.enqueue under ImmediateBackend vs. DummyBackend?
For fifteen years, every Django project had to couple its application code directly to Celery, RQ, Dramatiq, or Huey — making even reusable Django apps unable to enqueue background work without hard-coding a third-party broker API. Starting in Django 6.0 (refined in 6.1), Django ships django/tasks/: a standardized task definition, validation, and result protocol backed by pluggable execution backends configured in "settings.TASKS" — using the exact same BaseConnectionHandler architecture as DATABASES and CACHES!
TaskBackendHandler, @task, and frozen Task validation
Open TaskBackendHandler: it subclasses BaseConnectionHandler with "settings_name = 'TASKS'", exposing task_backends and default_task_backend (a ConnectionProxy to alias "default").
When "desk/"'s "newsroom/ decorates "build_edition_digest" with task:
@task(queue_name="default", priority=0)
def build_edition_digest(edition_id: int) -> dict[str, object]:
...
Django wraps the function into a frozen, slotted dataclass Task. Look closely at Task and BaseTaskBackend:
- Module-level importability check:
validate_taskimmediately rejects nested or local functions (InvalidTask: "Task function must be defined at a module level.") so external worker processes can always resolveTask.module_pathviaimport_string! - Backend capability checks:
validate_taskchecks whether the configured backend supportspriority,run_after(supports_defer), orasync defcoroutines (supports_async_task), failing fast at definition or enqueue time instead of silently ignoring options! Notice too that@taskexplicitly forbids passing a static"run_after"at decoration time (TypeError) — scheduling a deferred run must be done dynamically per invocation viaTask.using("build_edition_digest, which returns a new frozen.using(priority=5, run_after=...)" Taskviadataclasses!)..replace - JSON normalization on arguments and return values: Calling
Task.enqueueconstructs a frozenTaskResultwhose__post_init__passesargsandkwargsthroughnormalize_json! That means even when running locally onImmediateBackend, passing an unserializable ORM model instance (like"build_edition_digestinstead of.enqueue(edition)" "edition.pk") fails immediately in development rather than crashing later on a production broker!
TaskResultStatus, ImmediateBackend vs. DummyBackend, and on_commit
Django 6.1 ships two built-in backends (leaving persistent queue storage and worker processes to external backends like database or Redis workers):
ImmediateBackend: Default development backend (used by"desk/"). InsideImmediateBackend→.enqueue _execute_task, it constructs aTaskResultwith statusTaskResultStatus, sends.READY task_enqueued, transitions status toRUNNING, appendsImmediateBackend, sends.worker_id task_started, runsTask.callsynchronously right insideenqueue(), normalizes the return value as JSON, and transitions toSUCCESSFUL(or catches anyBaseExceptionexceptKeyboardInterruptintoTaskError, setting statusFAILED!) before sendingtask_finished. Notice two vital contract details: task exceptions do NOT propagate out ofenqueue(), and accessingTaskResultraises.return_value ValueErrorunless status isSUCCESSFUL(cleanly distinguishing a failed or pending task from a successful task that returnedNone!).DummyBackend: Built for tests.DummyBackendvalidates the task, appends the.enqueue READYTaskResultto"self.results", firestask_enqueued, and returnscopywithout ever executing the function (.deepcopy(result) attempts == 0), so tests can assert exact enqueued arguments and priorities via"task_backends['default'].results".
on_commit count is verified directly against ch12-services. Notice why pairing Task.enqueue with django.db.transaction.on_commit is non-negotiable in production: enqueueing directly inside django.db.transaction.atomic lets an external worker run before the database "COMMIT" finishes — or even after a "ROLLBACK"!Watch "desk/"'s "build_edition_digest" execute on ImmediateBackend (both success and "Edition failure), queue cleanly on DummyBackend with Task.using ("priority=5"), and respect django rollback safety live:
4. Django 6.1 django.tasks: ImmediateBackend vs DummyBackend
task_meta: name='build_edition_digest' queue='default' priority=0 backend=ImmediateBackend proxy=ConnectionProxy
immediate_enqueue: status=SUCCESSFUL is_finished=True attempts=1 return_edition='2026-11-25' story_count=4
immediate_failure: status=FAILED error_class='newsroom.models.Edition.DoesNotExist' return_value_raises='Task failed'
dummy_backend: status=READY priority=5 attempts=0 stored=1
on_commit_safety: queued_after_rollback=0 queued_after_commit=1
Notice line 21 ("immediate_failure"): "build_edition_digest returned cleanly with status=FAILED and error_class='newsroom, and only reading "res_fail raised ValueError('Task failed')!
With caching, signals, and tasks open, we turn to Django’s fourth horizontal service — how StorageHandler and FieldFile decouple model attributes from filesystems and object stores without opening files prematurely — next in Storage, FieldFile, and lazy file opening.