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

# 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`** (`django/db/transaction.py: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` (`django/db/backends/base/base.py:BaseDatabaseWrapper.on_commit`) — it is twenty lines of crystal-clear state handling with three branches:

- **Inside an `atomic` block (`in_atomic_block == True`):** Appends the 3-tuple `(set(self.savepoint_ids), func, robust)` onto `"self.run_on_commit"` without executing `"func"`.
- **Manual non-autocommit mode (`not get_autocommit()`):** Raises `TransactionManagementError` (`django/db/transaction.py:TransactionManagementError`) because Django cannot know when manual `commit()` calls will finish.
- **Autocommit mode (outside any transaction):** Executes `"func()"` **immediately**! (That is why calling `"transaction.on_commit(...)"` in a model method or service function works seamlessly whether or not the caller wrapped it in `atomic`, `django/db/transaction.py:atomic`.)

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` (`django/db/backends/base/base.py:BaseDatabaseWrapper.savepoint_rollback`):

```python
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` (`django/db/backends/base/base.py: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` (`django/db/backends/base/base.py:BaseDatabaseWrapper.commit`) and `BaseDatabaseWrapper.set_autocommit` (`django/db/backends/base/base.py: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` (`django/db/backends/base/base.py: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/"`:

```text recording=ch09-database
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` (`django/test/testcases.py: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](project-state.md).
