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 hold callbacks until the outermost commit succeeds?
Suppose a newsroom editor publishes a "Story" inside "with transaction and immediately calls "notify_subscribers on the very next line. Two bugs hide in those two lines, and both happen silently in production long after unit tests pass:
- 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 theatomicblock and issues"COMMIT". Because MVCC hides uncommitted writes from every other database connection, the worker runs"Storyand crashes with.objects .get(pk=story .pk)" "DoesNotExist"— or reads the old pre-update headline! - The ghost side effect: If a later statement in the same
atomicblock 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 — it is twenty lines of crystal-clear state handling with three branches:
- Inside an
atomicblock (in_atomic_block == True): Appends the 3-tuple(set(selfonto.savepoint_ids), func, robust) "selfwithout executing.run_on_commit" "func". - Manual non-autocommit mode (
not get_autocommit()): RaisesTransactionManagementErrorbecause Django cannot know when manualcommit()calls will finish. - Autocommit mode (outside any transaction): Executes
"func()"immediately! (That is why calling"transactionin a model method or service function works seamlessly whether or not the caller wrapped it in.on_commit(...)" atomic,atomic.)
Look closely at the first element stored in each queued tuple: set(self! 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:
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 simply assigns "self, 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 and BaseDatabaseWrapper:
BaseDatabaseWrappersends.commit "COMMIT"to the database driver and flips"self. Notice it does not run the hooks yet — autocommit is still.run_commit_hooks_on_set_autocommit_on = True" False, so any database write inside a hook would accidentally start a new uncommitted transaction!- In
Atomic.__exit__'sfinally:block,set_autocommit(True)re-enables autocommit first, then checks"run_commit_hooks_on_set_autocommit_on"and invokesBaseDatabaseWrapper..run_and_clear_commit_hooks
Inside run_and_clear_commit_hooks, Django swaps "self to a fresh empty list before popping hooks in strict FIFO order ("current_run_on_commit). 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, 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/":
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 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.