Django 6.1.3

9.4 Connections, transactions, and migrations

transaction.on_commit and post-commit ordering

Why does enqueueing a background task or sending an email inside an atomic block cause race conditions, and how does django.db.transaction.on_commit hold callbacks until the outermost commit succeeds?

Suppose a newsroom editor publishes a "Story" inside "with transaction.atomic():" and immediately calls "notify_subscribers.enqueue(story.pk)" on the very next line. Two bugs hide in those two lines, and both happen silently in production long after unit tests pass:

  1. The invisible-row race: A background worker (or a Django 6.0+ task worker running on another connection) can pick up "story.pk" milliseconds before the HTTP thread reaches the end of the atomic block and issues "COMMIT". Because MVCC hides uncommitted writes from every other database connection, the worker runs "Story.objects.get(pk=story.pk)" and crashes with "DoesNotExist" — or reads the old pre-update headline!
  2. The ghost side effect: If a later statement in the same atomic block raises an exception, SQL rolls back the "Story" cleanly — but the email already left the SMTP server and the queued task is already running against a row that never existed.

Django solves both bugs with on_commit, which defers a commit hook callable until the outermost database transaction actually commits.

Inside BaseDatabaseWrapper.on_commit and run_on_commit

Open BaseDatabaseWrapper.on_commit — it is twenty lines of crystal-clear state handling with three branches:

Look closely at the first element stored in each queued tuple: set(self.savepoint_ids)! Snapshotting the exact set of active savepoint IDs at registration time is how Django makes nested savepoint rollbacks drop only the hooks born inside that failed savepoint. Look at BaseDatabaseWrapper.savepoint_rollback:

self.run_on_commit = [
    (sids, func, robust)
    for (sids, func, robust) in self.run_on_commit
    if sid not in sids
]

And if the outermost transaction rolls back instead, BaseDatabaseWrapper.rollback simply assigns "self.run_on_commit = []", discarding every queued callback at once.

Firing order, run_and_clear_commit_hooks, and robust=True

When the outermost Atomic.__exit__ succeeds, look at the exact two-step handoff between BaseDatabaseWrapper.commit and BaseDatabaseWrapper.set_autocommit:

  1. BaseDatabaseWrapper.commit sends "COMMIT" to the database driver and flips "self.run_commit_hooks_on_set_autocommit_on = True". Notice it does not run the hooks yet — autocommit is still False, so any database write inside a hook would accidentally start a new uncommitted transaction!
  2. In Atomic.__exit__'s finally: block, set_autocommit(True) re-enables autocommit first, then checks "run_commit_hooks_on_set_autocommit_on" and invokes BaseDatabaseWrapper.run_and_clear_commit_hooks.

Inside run_and_clear_commit_hooks, Django swaps "self.run_on_commit" to a fresh empty list before popping hooks in strict FIFO order ("current_run_on_commit.pop(0)"). That swap matters if hook #1 itself starts a new atomic block and registers its own on_commit callback — the nested hook queues onto the new list without corrupting the loop currently draining.

One sharp hazard remains: what if hook #1 raises an exception? By default ("robust=False"), the database has already committed, yet the unhandled exception in hook #1 aborts run_and_clear_commit_hooks, silently preventing hook #2, hook #3, and every remaining post-commit hook from ever running! Passing "robust=True" wraps that callback in try ... except Exception:, logs the traceback via "django.db.backends.base", and continues draining the remaining hooks in order.

Watch immediate autocommit execution, nested savepoint hook discard, outer FIFO firing, and robust=True isolation live on "desk/":

Recorded on Django 6.1.3 ch09-database script
4. transaction.on_commit ordering, savepoint discard, and robust=True
  autocommit_on_commit = ['autocommit-immediate']
  queued_hooks: inside_inner=2 after_savepoint_rollback=1 fired_before_commit=[]
  fired_after_outer_commit = ['outer-before', 'outer-after']
  robust_hooks = ['hook-1-runs-and-raises', 'hook-2-still-runs']

One test-suite caveat is worth memorizing right here: Django’s standard TestCase wraps every test method inside an outer atomic block and rolls it back at teardown for speed — which means on_commit callbacks never fire inside a normal TestCase unless you explicitly capture them with TestCase.captureOnCommitCallbacks(execute=True) or use TransactionTestCase!

With connections, backends, transactions, and post-commit hooks in place, we turn to the second half of django/db/: how Django evolves your database schema over time without ever introspecting live tables to guess what changed — starting in How migrations build a historical ProjectState.