You register a new user, create the record inside transaction.atomic(), then immediately fire a Celery task to send the welcome email — but the worker runs before the transaction commits, so it can’t find the user, and the email fails or is sent with wrong data. Django’s answer is transaction.on_commit(): register a callback that runs only after the transaction commits successfully, and gets cancelled automatically if the transaction rolls back. It’s the correct way to “run background work only after the data is safely in the database”.
The Problem
A very common situation: in the registration view, you wrap user creation in transaction.atomic() for atomicity, then immediately fire a Celery task to send the email:
from django.db import transactionfrom django.contrib.auth.models import Userdef register(request): with transaction.atomic(): user = User.objects.create(username="linh", email="linh@example.com") send_welcome_email.delay(user.pk) # Celery runs NOW, before commit! # Worker queries the DB now -> user does NOT exist yet -> DoesNotExist / wrong send
The problem is timing: the Celery worker is a separate process that queries the database as soon as the task is enqueued — while the user record is still sitting in the uncommitted transaction, invisible to the worker. Worse, if a later line inside the atomic() block raises an exception, the transaction rolls back but the email has already been sent — data that doesn’t exist, yet the email went out. This is the classic race condition between a transaction and background work.
The Solution
Django provides transaction.on_commit() to register a callback function — Django calls it only after the outermost transaction commits successfully. Rewriting the view above:
from django.db import transactionfrom django.contrib.auth.models import Userdef register(request): with transaction.atomic(): user = User.objects.create(username="linh", email="linh@example.com") # Runs only AFTER successful commit, worker always sees the user transaction.on_commit(lambda: send_welcome_email.delay(user.pk)) # On exception -> rollback -> callback cancelled, no misfired email
Why this is better: first, the callback runs after the commit, so the worker always reads finalized data — the race condition is gone. Second, if the transaction rolls back for any error, Django automatically discards the registered callbacks — you never send an email for a record that doesn’t exist. Third, when no transaction is open (default autocommit mode), on_commit runs the callback immediately, so the code still works in any view. One small note: callbacks take no arguments — pass data with a lambda or functools.partial like the example above.
Apply It to Your Project
The rule of application is simple: whenever you trigger an “external effect” that depends on just-written data — sending email, firing a webhook, enqueueing a Celery task, clearing a cache, syncing to Elasticsearch — and the data write sits inside transaction.atomic() (even indirectly via @transaction.atomic on the view), wrap that call in transaction.on_commit(). Search your codebase for .delay(), requests.post(), or cache.delete() calls right after Model.objects.create() in the same function: those are the first spots to fix, and each one costs just one extra wrapping line.
Related Posts
- Django Signals: Automatically Create a Profile for New Users with post_save in 5 Minutes — combine signals with on_commit to avoid running background work before commit.
- Django: Writing Custom Management Commands — Seed Data and Run Background Tasks in 5 Minutes — management commands and tasks running outside the request.
- Django: Use get_or_create() and update_or_create() Correctly — Get or Create a Record in One Line — safely get-or-create records in a single statement.
Frequently Asked Questions
How is on_commit different from calling the task right after create()?
Calling immediately runs the task in parallel with the still-open transaction — the outside worker can’t see uncommitted data. on_commit defers the call until after the commit, so the worker always reads the final, consistent data.
If the transaction rolls back, does the callback still run?
No. Django tracks callbacks per transaction; on rollback, all unrun callbacks of that transaction are discarded. That’s exactly what makes on_commit safer than calling directly.
Why do on_commit callbacks never run in tests using TestCase?
Because Django’s TestCase wraps each test in an atomic() and rolls back at the end to clean up data — the transaction never commits, so callbacks never run. To test on_commit logic, use TransactionTestCase (real commits, slower) or captureOnCommitCallbacks to capture and run callbacks manually.
Can I register multiple on_commit callbacks in one transaction?
Yes. Callbacks run in registration order after the commit. Each callback is independent — if one raises, the remaining ones still run.
References
- Django documentation — Database transactions: django.db.transaction.on_commit
- Django documentation — Testing transactions: TransactionTestCase and captureOnCommitCallbacks
