---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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`** (`django/dispatch/dispatcher.py:Signal`) is an in-process list of callbacks invoked in a plain synchronous `for` loop.

## Weak references and duplicate registration

Look at `Signal.connect` (`django/dispatch/dispatcher.py:Signal.connect`):

```python
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` (`django/dispatch/dispatcher.py:Signal.send`):

```python
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 of `Model.save()` (rolling back any enclosing `django.db.transaction.atomic` block!). If async receivers are connected, `send()` runs them after sync receivers via `async_to_sync` inside an `asyncio.TaskGroup` (`_run_parallel`).
- **`Signal.send_robust` (`django/dispatch/dispatcher.py:Signal.send_robust`):** Wraps each receiver call in `try ... except Exception as err:`, logs the traceback via `Signal._log_robust_failure`, records `(receiver, err)` in the returned list, and **continues executing every remaining receiver**.
- **`Signal.asend` (`django/dispatch/dispatcher.py:Signal.asend`):** Runs sync receivers behind one `sync_to_async` hop and runs all async receivers concurrently via `asyncio.TaskGroup` while preserving `contextvars`.

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!

```text figure=signal-fanout-and-cost
Signal.send() synchronous dispatch, weakrefs, and post_save cost on desk/ (Django 6.1.3, 7 trials)

1. Signal.connect() & Signal.send() mechanics (verified on desk/):
   weak=True & dispatch_uid -> local fn GC'd (responses=[]); dispatch_uid deduplicates (receivers=1)
   send() is sync for-loop  -> receiver #1 raises -> receiver #2 NEVER runs; bulk_update skips post_save
   send_robust() & asend()  -> catches Exception, runs receiver #2; async receivers run in TaskGroup

2. 25 Story updates across signal configurations (7 trials, median ms):
   bulk_update (skips post_save entirely)      3.17 ms  (0.79x)
   0 receivers (signals disconnected)          4.00 ms  (1.00x baseline)
   1 Python receiver (record_story_save)       4.15 ms  (1.04x)
   5 Python receivers (sync loop)              4.24 ms  (1.06x)
   1 receiver + 1 DB query (hidden N+1)       11.29 ms  (2.82x slower!)
```

*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:

```text recording=ch12-services
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
```

```text recording=ch12-bench
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](tasks.md).
