Django 6.1.3

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/dispatch/dispatcher.py 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):

  1. Why local-function receivers vanish silently: Because "weak=True" by default, Signal holds only a weakref.ref (or weakref.WeakMethod for bound methods) so garbage-collected objects do not leak memory inside a global signal registry. If you define a receiver function inside AppConfig.ready() or a helper function and pass it to "signal.connect(handler)" without "weak=False", the local function has zero strong references left the instant the enclosing function returns — Python’s garbage collector reclaims it, _flag_dead_receivers marks it dead, and "signal.send(...)" returns [] with zero errors or warnings!
  2. Why "dispatch_uid" matters on startup: In development or complex import graphs, a module can be imported through two paths, executing "post_save.connect(...)" twice and running your side effects (like charging a card or appending duplicate audit rows!) twice per save! Passing a hashable "dispatch_uid" (as "desk/"'s "newsroom/signals.py" passes dispatch_uid="newsroom.story_post_save") keys registration by (dispatch_uid, _make_id(sender)) so duplicate connect() 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:

And remember two critical ORM caveats from Chapters 6 and 7: bulk ORM operations (QuerySet.update, QuerySet.bulk_create, QuerySet.bulk_update) 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!

Figure 12.2 Every failure path and millisecond bar is parsed directly from 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:

Recorded on Django 6.1.3 ch12-services script
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
Recorded on Django 6.1.3 ch12-bench script
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.contrib.auth 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.