Django transaction.on_commit(): Safe Post-Commit Hooks

Why firing background tasks or webhooks inside Django transaction.atomic() causes race conditions, and how transaction.on_commit() fixes them safely.

Django transaction.on_commit(): Safe Post-Commit Hooks
In this essay

Enqueueing a background job, mutating a cache, or calling a webhook directly inside Django's transaction.atomic() breaks atomicity because external systems react before the database commits. Wrapping those side effects in transaction.on_commit() aligns external actions with actual data visibility—provided you account for nested savepoints, callback exceptions, and TestCase rollbacks.

Two Ways In-Transaction Side Effects Break

Consider a typical checkout service wrapped in @transaction.atomic—or running on a project with ATOMIC_REQUESTS = True, which silently wraps every HTTP view in a transaction. Even post_save model signals fall into this bucket, because Model.save() emits signals synchronously inside whatever transaction is currently active. Suppose the function creates an Order row, enqueues a Celery worker to generate an invoice, and then deducts inventory:

from django.db import transaction

@transaction.atomic
def place_order(cart, user):
    order = Order.objects.create(user=user, total=cart.total)
    # Bug: queued before the database transaction commits
    generate_invoice.delay(order.id)
    deduct_inventory(cart)
    return order

This pattern introduces two distinct failure modes in production. First is the visibility race. A background worker runs in a separate OS process with its own database connection. Under PostgreSQL's default READ COMMITTED isolation level, other connections cannot see order until the web process finishes deduct_inventory(cart) and commits. Whenever the broker dispatches the message faster than the web transaction finishes, Order.objects.get(id=order_id) inside the worker raises Order.DoesNotExist. Local development rarely triggers the gap, whereas production load exposes it intermittently whenever downstream queries slow down.

Second is the unrollable side effect. If deduct_inventory(cart) raises an exception because an item went out of stock, PostgreSQL cleanly rolls back the Order insert. Yet the message broker already received the job, an email API already sent a receipt, or Redis already cached uncommitted state. Worse, performing synchronous network I/O inside atomic() stretches transaction duration, holding database connections and row locks open while waiting on external sockets.

Deferring Execution with transaction.on_commit()

Interlocking matte ceramic blocks and an optical glass prism arranged in sequence on raw architectural concrete

Django's transaction.on_commit() fixes the timing mismatch by attaching a callback queue to the active database connection. Instead of firing mid-transaction, registered callables wait until the outermost transaction commits cleanly:

from functools import partial
from django.db import transaction

@transaction.atomic
def place_order(cart, user):
    order = Order.objects.create(user=user, total=cart.total)
    transaction.on_commit(partial(generate_invoice.delay, order.id))
    deduct_inventory(cart)
    return order

If deduct_inventory(cart) fails and triggers a rollback, Django discards the queued callback before anything leaves the process. Conversely, if place_order runs when no transaction is open—for instance, in Django's default autocommit mode outside any atomic() block—on_commit() executes the function immediately so shared helpers behave predictably in both contexts. On multi-database setups, always pass using="analytics" (matching the target database alias) so the hook tracks the connection that actually wrote the row rather than defaulting to "default".

Notice the use of functools.partial instead of an inline lambda. When registering hooks inside a loop, lambda: notify_item.delay(item.id) binds the loop variable item by reference; by the time the transaction commits, every callback fires with the final iteration's ID. partial(notify_item.delay, item.id) captures the exact value eagerly at registration time.

Savepoints, Callback Crashes, and the Outbox Boundary

Non-trivial codebases frequently nest @transaction.atomic blocks as service functions call lower-level helpers, creating SQL savepoints inside the outer transaction. Django tracks which savepoint stack was active when each hook was added:

  • A callback registered inside a nested atomic() block still waits for the outermost transaction to commit, because inner savepoints remain invisible to other database connections.
  • If an inner atomic() block raises an exception and rolls back its savepoint, Django drops the callbacks registered inside that inner block—even if outer code catches the exception and commits the surrounding transaction.

Once the outer COMMIT succeeds, you cross an important boundary: errors inside callbacks can no longer roll back the committed rows. By default, Django runs callbacks sequentially with robust=False. If the first callback raises an unhandled exception—say, a transient Redis timeout during cache invalidation—subsequent callbacks in the queue are aborted, silently skipping your background task. Pass robust=True on independent or non-critical hooks to isolate failures:

transaction.on_commit(
    partial(invalidate_user_cache, user.id),
    robust=True,
)

With robust=True, Django catches any subclass of Python's Exception, logs the traceback to the django.db.backends.base logger, and continues running the remaining callbacks. Still, remember that on_commit() holds its callback list in Python process memory. If the web worker receives SIGKILL or loses power in the milliseconds after PostgreSQL commits and before the Python loop finishes, those queued calls are lost. For notifications, cache eviction, and retryable jobs, on_commit() hits the sweet spot of simplicity; for strict financial workflows that cannot drop an event on process crash, write an outbox row inside the same SQL transaction instead.

Why Tests Stay Silent Without captureOnCommitCallbacks

Moving side effects into on_commit() routinely surprises teams when existing tests suddenly report zero mocked task calls. Django's standard django.test.TestCase wraps every test method inside an outer transaction and rolls it back on teardown to keep the database clean without slow table truncation. Because that outer wrapper never commits, on_commit() hooks stay queued and get discarded when the test exits.

Switching to TransactionTestCase forces real commits, but flushing tables after every test drags suite runtime down as models grow. Stay on TestCase and wrap the call under test with captureOnCommitCallbacks(execute=True):

from django.test import TestCase

class CheckoutTests(TestCase):
    def test_invoice_queued_after_checkout(self):
        with self.captureOnCommitCallbacks(execute=True) as callbacks:
            place_order(self.cart, self.user)

        self.assertEqual(len(callbacks), 1)

When the context manager exits cleanly, Django emulates a commit by executing the captured list in order—including any nested on_commit() callbacks scheduled while the first batch runs—giving you realistic post-commit verification at TestCase speed.

Sources

  1. docs.djangoproject.com
  2. docs.djangoproject.com

AI-assisted · Reviewed by PKN

0

Responses

Loading comments…