Commit First, Notify Later: Transaction Boundaries in Django
Keep Django database changes consistent with transaction.atomic, then schedule follow-up work with on_commit. Understand where database guarantees stop.
A service creates an order, sends a confirmation email, and then fails while writing an audit row. The database can roll back the order. It cannot unsend the email. The customer now has a confirmation for a record that does not exist.

Transaction boundaries belong around a business operation. External side effects need an equally explicit timing decision. In Django, transaction.atomic groups database work, while transaction.on_commit delays a callback until the surrounding transaction succeeds.
The Problem: Side Effects in the Middle of a Write
# Unsafe ordering: the email can outlive a rolled-back order.
with transaction.atomic():
order = Order.objects.create(customer=customer)
send_confirmation(order.pk)
AuditEntry.objects.create(order=order, action="created")Wrapping this code in atomic does not make the mail system transactional. Treat the database and notification service as separate systems with separate failure modes.
Step 1: Put the Write Boundary in a Service
from functools import partial
from django.db import transaction
from orders.models import Order, AuditEntry
from orders.notifications import send_confirmation
def create_order(*, customer):
with transaction.atomic():
order = Order.objects.create(customer=customer)
AuditEntry.objects.create(order=order, action="created")
transaction.on_commit(
partial(send_confirmation, order.pk)
)
return orderOrder, AuditEntry, and send_confirmation are application-specific dependencies. Pass a stable identifier to the callback so its implementation can reload the committed record. Keep authorization and input validation at the application boundary before invoking this service.
Step 2: Understand the Outer Transaction
When this service runs inside another atomic block, the callback waits for the outer transaction to commit. If the transaction rolls back, the registered callback is discarded. Outside any transaction, on_commit runs the callable immediately. These rules are described in Django’s transaction documentation.
Handle a database exception outside the atomic block whose failure you are handling. Catching it inside the block and continuing to query can leave you operating within a broken transaction.
Step 3: Test Callback Timing
from unittest.mock import patch
from django.test import TestCase
from orders.services import create_order
class CreateOrderTests(TestCase):
# self.customer is provided by this test suite's fixtures.
@patch("orders.services.send_confirmation")
def test_notification_runs_after_commit(self, notify):
with self.captureOnCommitCallbacks(execute=True):
order = create_order(customer=self.customer)
notify.assert_not_called()
notify.assert_called_once_with(order.pk)Add a separate failure test that forces the audit write to raise, then asserts the order was rolled back and no callback was executed. Test the business boundary rather than the number of nested context managers.
When on_commit Is Not Enough
A successful database commit does not guarantee callback delivery. The process can stop after committing, or the email provider can fail. Callback failure also cannot undo the completed transaction. For an essential event, consider an outbox row stored alongside the order, then a worker that retries delivery and records progress.
An outbox adds operational work: polling or event capture, retry limits, monitoring, and idempotent consumers. Use it when missed delivery would violate a business requirement. For a best-effort notification, a documented on_commit callback can be the smaller, clearer choice.
Related: Thin Views, Fat Services