← Back to Django, page 5

django-0086 · Hard senior

How do custom Django signals work, and what are the pitfalls: dispatch_uid, weak references, send_robust, ordering and transactions?

A Signal object keeps receivers that are called synchronously by send(). Use dispatch_uid to prevent duplicate registration when a module is imported twice, remember receivers are held by weak reference by default (lambdas and local functions can vanish), choose send_robust() when one failing receiver must not break the sender, and never assume receiver order or transactional safety: post_save fires before the transaction commits, so use transaction.on_commit() for external effects.

Full answer

Signals decouple senders from receivers, but they hide control flow. Use them for cross-app notifications where the sender should not know the listeners; use plain function calls when you own both sides.

Custom signal:

python
fee_paid = Signal()                 # Django 3.0+ takes no providing_args
fee_paid.send(sender=Fee, instance=fee, amount=500)

@receiver(fee_paid, dispatch_uid="send_receipt_v1")
def send_receipt(sender, instance, amount, **kwargs): ...

Pitfalls:

  1. Duplicate registration: if the module that registers the receiver is imported under two names, or ready() runs twice in tests, the receiver is called twice. dispatch_uid makes the pair (signal, uid) unique.
  2. Weak references: connect() stores receivers weakly by default. A lambda or nested function is garbage-collected right away and never fires. Use module-level functions, or weak=False.
  3. Exceptions: send() stops at the first receiver exception and re-raises it, so one bad listener breaks the sender. send_robust() catches exceptions, returns [(receiver, response_or_exception)], and you should log failures.
  4. Order: receivers run in connection order, which depends on import order. Do not rely on it.
  5. Transactions: post_save runs inside the open transaction. If it sends an email or queues a task and the transaction later rolls back, the side effect already happened. Wrap external effects in transaction.on_commit().
  6. Bulk operations: bulk_create, update() and QuerySet.delete() fast paths skip many signals (post_save), so signals are not a complete audit mechanism.
  7. Registration location: connect receivers in AppConfig.ready() so they are imported once at startup.
  8. Performance: each signal adds calls on hot paths; filter early with sender=.

Alternatives: explicit service functions, model save() overrides for logic that is truly part of the model, and an outbox table for reliable events.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import gc

from django.db import models, connection, transaction
from django.db.models.signals import post_save
from django.dispatch import Signal, receiver

fee_paid = Signal()
log = []


def receipt(sender, **kwargs):
    log.append("receipt")


def broken(sender, **kwargs):
    raise RuntimeError("mail server down")


def ledger(sender, **kwargs):
    log.append("ledger")


fee_paid.connect(receipt, dispatch_uid="receipt_v1")
fee_paid.connect(receipt, dispatch_uid="receipt_v1")          # duplicate import: ignored
fee_paid.connect(broken, dispatch_uid="broken_v1")
fee_paid.connect(ledger, dispatch_uid="ledger_v1")

print("receivers:", len(fee_paid.receivers))
try:
    fee_paid.send(sender="Fee")
except RuntimeError as exc:
    print("send() raised:", exc, "| log:", log)
log.clear()
results = fee_paid.send_robust(sender="Fee")
print("send_robust log:", log, "| errors:", [type(r).__name__ for _, r in results if isinstance(r, Exception)])

fee_paid.connect(lambda sender, **kw: log.append("lambda"), dispatch_uid="lam")   # weak reference to a temporary
gc.collect()
log.clear()
fee_paid.send_robust(sender="Fee")
print("lambda fired:", "lambda" in log)


class Fee(models.Model):
    amount = models.IntegerField()

    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Fee)

emails = []


@receiver(post_save, sender=Fee, dispatch_uid="email_on_save")
def email_receipt(sender, instance, created, **kwargs):
    emails.append(f"sent immediately for {instance.amount}")                     # fires before commit
    transaction.on_commit(lambda: emails.append(f"sent after commit for {instance.amount}"))


try:
    with transaction.atomic():
        Fee.objects.create(amount=500)
        raise RuntimeError("payment gateway failed")
except RuntimeError:
    pass
print(Fee.objects.count(), emails)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. In a test run on_commit callbacks are discarded by TestCase unless captured; here autocommit mode is used outside the failing atomic block. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): receivers: 3 send() raised: mail server down | log: ['receipt'] send_robust log: ['receipt', 'ledger'] | errors: ['RuntimeError'] lambda fired: False 0 ['sent immediately for 500']

Key points

  • send() is synchronous and stops on the first exception; send_robust() collects them
  • dispatch_uid prevents duplicate receivers
  • Receivers are weak references by default
  • post_save fires inside the transaction; use on_commit for side effects
  • Bulk operations skip many signals

Common mistakes

  • Registering receivers inside functions or with lambdas and losing them to garbage collection
  • Sending emails or tasks from post_save inside a transaction
  • Relying on receiver order or on signals for bulk operations
  • Letting one failing receiver break the sender without choosing send_robust

Follow-ups

  • When would you replace signals with an explicit service call?
  • Where should receivers be connected, and why?
  • What do pre_save and post_save get as arguments?

Tips

  • List 4 pitfalls
  • Say on_commit for side effects
  • Differentiate send and send_robust