12.3 Caching, signals, tasks, and files
Signal.send, weak references, and synchronous cost
Why are Django signals strictly synchronous function loops rather than background queues, and why do weak references silently drop local-function receivers?
Because Django calls them signals (pre_save, post_save, request_finished, user_logged_in), newcomers frequently assume they behave like asynchronous pub-sub events — firing off to the side without blocking the caller or sharing its database transaction. Open django/ and that illusion evaporates in ten lines of Python: a Django Signal is an in-process list of callbacks invoked in a plain synchronous for loop.
Weak references and duplicate registration
Look at Signal.connect:
if weak:
ref = weakref.ref
if hasattr(receiver, "__self__") and hasattr(receiver, "__func__"):
ref = weakref.WeakMethod
receiver = ref(receiver, self._flag_dead_receivers)
Notice two sharp consequences of Signal.connect’s default arguments (weak=True, dispatch_uid=None):
- Why local-function receivers vanish silently: Because
"weak=True"by default,Signalholds only aweakref.ref(orweakreffor bound methods) so garbage-collected objects do not leak memory inside a global signal registry. If you define a receiver function inside.WeakMethod AppConfigor a helper function and pass it to.ready() "signalwithout.connect(handler)" "weak=False", the local function has zero strong references left the instant the enclosing function returns — Python’s garbage collector reclaims it,_flag_dead_receiversmarks it dead, and"signalreturns.send(...)" []with zero errors or warnings! - Why
"dispatch_uid"matters on startup: In development or complex import graphs, a module can be imported through two paths, executing"post_savetwice and running your side effects (like charging a card or appending duplicate audit rows!) twice per save! Passing a hashable.connect(...)" "dispatch_uid"(as"desk/"'s"newsroom/passessignals .py" dispatch_uid="newsroom) keys registration by.story_post_save" (dispatch_uid, _make_id(sender))so duplicateconnect()calls are ignored cleanly.
send vs. send_robust vs. asend — and the hidden N+1 cost
Now open Signal.send:
sync_receivers, async_receivers = self._live_receivers(sender)
for receiver in sync_receivers:
response = receiver(signal=self, sender=sender, **named)
responses.append((receiver, response))
Every synchronous receiver runs inline in the caller’s thread and active database transaction before save() returns! Look at the three dispatch variants side by side:
Signal.send: Stops immediately on the first unhandled exception — later receivers never execute, and the exception propagates back out ofModel.save()(rolling back any enclosingdjangoblock!). If async receivers are connected,.db .transaction .atomic send()runs them after sync receivers viaasync_to_syncinside anasyncio(.TaskGroup _run_parallel).Signal: Wraps each receiver call in.send_robust try ... except Exception as err:, logs the traceback viaSignal, records._log_robust_failure (receiver, err)in the returned list, and continues executing every remaining receiver.Signal.asend: Runs sync receivers behind onesync_to_asynchop and runs all async receivers concurrently viaasynciowhile preserving.TaskGroup contextvars.
And remember two critical ORM caveats from Chapters 6 and 7: bulk ORM operations (QuerySet.update, QuerySet, QuerySet) never send pre_save or post_save signals because they bypass Model.save(). Conversely, when a view does save rows inside a loop, a single innocent "post_save" receiver that executes one extra SQL query turns a 25-row save loop into a hidden N+1 latency multiplier!
ch12-services and ch12-bench. Notice the real lesson of that bar chart: pure Python signal dispatch itself is cheap (4.00 ms -> 4.24 ms across five receivers), whereas hiding even one database query inside a "post_save" receiver nearly triples write latency (11.29 ms, 2.82x) and executes invisibly far away from the view!Watch weakref GC dropping an ephemeral local receiver, "dispatch_uid" deduplication, send aborting vs. send_robust continuing, QuerySet.update skipping "desk/"'s "post_save" log, and the exact 25-story timing table:
3. Signal weakref drop, dispatch_uid, and send vs send_robust
weak_local_after_gc: responses=[] dispatch_uid_dedup_receivers=1
send_stops_on_error: raised=True after_fail_ran=False
send_robust_continues: results=[('failing_receiver', 'RuntimeError'), ('after_fail_receiver', 'recovered')]
desk_post_save: after_save=1 after_queryset_update=1
2. Synchronous post_save signal cost across 25 Story.save() calls (7 trials, ms)
save_mode (25 updates) median_ms rel
0 receivers (signals disconnected) 4.00 1.00x
1 Python receiver (record_story_save) 4.15 1.04x
5 Python receivers (sync loop) 4.24 1.06x
1 receiver + 1 DB query (hidden N+1) 11.29 2.82x
bulk_update (skips post_save entirely) 3.17 0.79x
Signals are meant for decoupled in-process notifications (like django hooking user_logged_in to update last_login, or clearing a cache on setting_changed), never for slow side effects like building digests, rendering PDFs, or calling external APIs. For real deferred work, Django 6 introduced a first-class native abstraction: django.tasks. We open it next in Django 6’s django.tasks framework.