Django Django

What does `transaction.atomic()` actually guarantee?

Dima Nov 15, 2026

Short Answer

That the block either takes effect completely or not at all, decided by one question: did an exception leave the block? Exit normally and Django commits; let an exception propagate out and it rolls back everything written inside. Nested atomic() blocks do not create nested transactions — the inner one opens a savepoint, so an inner failure can be caught and discarded while the outer block goes on to commit. The guarantee has a sharp edge: once a database error has occurred, the transaction is unusable until the block ends, so catching that error and carrying on raises TransactionManagementError rather than continuing.


How It Works

Outside any atomic() block Django runs in autocommit: each query is its own transaction and takes effect immediately. atomic() turns that off for the duration of the block. Entering the outermost block opens a real database transaction; leaving it normally issues COMMIT, and leaving it because an exception is propagating issues ROLLBACK. Nothing else decides — not the kind of exception, not whether you logged it. An exception that escapes the block rolls it back, and an exception caught inside the block does not.

Nesting behaves differently from what the syntax suggests. Databases do not support transactions inside transactions, so an inner atomic() does not start one. It creates a savepoint — a named marker in the current transaction — and on failure rolls back to that marker rather than discarding everything. The outer block continues with its earlier writes intact and can still commit. This is what makes atomic() safe to use in a function that might be called from inside another atomic(): the block adapts to whichever position it finds itself in.

The edge case follows from how databases treat errors. When a statement fails — a constraint violation, a type error — the transaction enters a state where no further statements are accepted until it is rolled back. Django tracks this and marks the transaction as needing rollback. If you catch that error inside the atomic block and then run another query, Django refuses with TransactionManagementError instead of letting the database reject it more obscurely.

The fix is the savepoint. Wrapping the statement that might fail in its own inner atomic() means the failure rolls back to that savepoint, which restores a usable transaction, and the outer block carries on. So the rule is not "never catch database errors inside a transaction" but "catch them at a savepoint boundary".

One consequence worth holding on to: because the commit happens at the end of the block, anything that must not run until the data is durable — sending mail, queueing a job, invalidating a cache — belongs in transaction.on_commit() rather than inline, where it would fire even if the block later rolled back.


Seeing It Run

These steps share a fixture. Create depot/models.py and bootstrap.py as shown in the first step, plus an empty depot/__init__.py, then replace main.py for each later step. Run with:

python3 main.py

Commit or roll back, decided by the exception

Two blocks writing one row each. One raises on the way out, one does not.

# depot/models.py
from django.db import models


class Shipment(models.Model):
    reference = models.CharField(max_length=20, unique=True)
    status = models.CharField(max_length=20, default="booked")


# bootstrap.py
import django
from django.conf import settings

settings.configure(
    DEBUG=True,
    INSTALLED_APPS=["depot"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
    DEFAULT_AUTO_FIELD="django.db.models.AutoField",
    USE_TZ=False,
)
django.setup()

from django.db import connection, transaction

from depot.models import Shipment


def seed():
    with connection.schema_editor() as editor:
        editor.create_model(Shipment)
    connection.queries_log.clear()


# main.py
from bootstrap import Shipment, seed, transaction

seed()

try:
    with transaction.atomic():
        Shipment.objects.create(reference="SHP-4471")
        raise ValueError("carrier rejected the booking")
except ValueError:
    pass
print("after the block that raised:", Shipment.objects.count(), "rows")

with transaction.atomic():
    Shipment.objects.create(reference="SHP-4408")
print("after the block that exited:", Shipment.objects.count(), "rows")


after the block that raised: 0 rows
after the block that exited: 1 rows


The first create() genuinely ran — the row existed inside the transaction — and the rollback removed it, so the count is zero. Note where the try sits: outside the with. That placement is what lets the exception leave the block and trigger the rollback. Moving the try inside would swallow it before atomic() ever saw it, and the row would commit.

Try it: Move the try/except ValueError inside the first with transaction.atomic(): block, so the exception is caught before it reaches the edge of the block. How many rows will the two print calls report? You now get 1 rows and 2 rows: atomic() only rolls back when an exception crosses its exit. An exception caught inside never reaches __exit__, so the block ends normally and commits.


Nested blocks are savepoints

Replace main.py. An outer block with two writes and a failing inner block between them.

# main.py
from bootstrap import Shipment, seed, transaction

seed()

with transaction.atomic():
    Shipment.objects.create(reference="SHP-4471")

    try:
        with transaction.atomic():
            Shipment.objects.create(reference="SHP-4408")
            raise ValueError("scan feed rejected this leg")
    except ValueError:
        print("inner block rolled back, outer still running")

    Shipment.objects.create(reference="SHP-3157")

print("committed rows:", sorted(Shipment.objects.values_list("reference", flat=True)))


inner block rolled back, outer still running
committed rows: ['SHP-3157', 'SHP-4471']


Two rows survive and one does not. SHP-4408 was written inside the inner block, which rolled back to its savepoint when the exception left it; SHP-4471, written before the savepoint, was untouched, and SHP-3157 was written after the recovery. The outer block committed normally because its own exit was clean — the inner exception was caught before reaching it. This is partial rollback inside a single transaction, and it is why a helper function can safely open atomic() without knowing whether a caller already did.

Try it: Delete the inner with transaction.atomic(): line and dedent the two lines under it, so create and raise sit directly in the try. The exception is caught exactly as before; which references will be committed? The result is ['SHP-3157', 'SHP-4408', 'SHP-4471']. Without the inner block there is no savepoint to roll back to, so SHP-4408 stays written in the outer transaction: catching an exception undoes nothing, only an atomic() does.


A database error poisons the block until it ends

Replace main.py. The same duplicate insert, handled two ways.

# main.py
from bootstrap import Shipment, seed, transaction
from django.db import IntegrityError
from django.db.transaction import TransactionManagementError

seed()
Shipment.objects.create(reference="SHP-4471")

try:
    with transaction.atomic():
        try:
            Shipment.objects.create(reference="SHP-4471")
        except IntegrityError:
            print("caught IntegrityError inside the block, then queried...")
            Shipment.objects.count()
except TransactionManagementError as exc:
    print("->", type(exc).__name__)
    print("  ", exc)

with transaction.atomic():
    try:
        with transaction.atomic():
            Shipment.objects.create(reference="SHP-4471")
    except IntegrityError:
        print("same error, but wrapped in its own atomic():")
    print("   the transaction still works, count =", Shipment.objects.count())


caught IntegrityError inside the block, then queried...
-> TransactionManagementError
   An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.
same error, but wrapped in its own atomic():
   the transaction still works, count = 1


The first half looks like ordinary defensive code and is not. Catching the IntegrityError stopped it reaching atomic(), but the database had already refused the transaction, so the next query raised TransactionManagementError — the error message is Django telling you the block is finished whether you like it or not. The second half changes one thing: the failing create() sits in its own atomic(), so the IntegrityError rolls back to that savepoint and leaves the outer transaction healthy. The count() then runs normally.


Edge Cases and Gotchas

  • atomic() also works as a decorator. @transaction.atomic on a view or function wraps the whole call, which is the usual way to make a request-handling function all-or-nothing.
  • Side effects do not roll back. Only database writes are undone. A file written, an email sent, or a task queued inside the block survives a rollback — use transaction.on_commit() for anything that must wait for durability.
  • ATOMIC_REQUESTS wraps every view. Setting it on a database wraps each request in a transaction, which is simple but holds a transaction open for the whole view, including slow non-database work.
  • select_for_update() depends on the backend. On PostgreSQL and MySQL, calling it outside an atomic() block raises TransactionManagementError, since there is no transaction for the lock to belong to. On SQLite has_select_for_update is False, so the same call is a silent no-op that neither errors nor locks — the quieter and more dangerous outcome.
  • A caught exception commits. try inside the with means atomic() sees a clean exit and commits the partial work — usually the opposite of the intent. Put the try outside the block, or re-raise.

Summary

atomic() opens a transaction and decides its fate by whether an exception escapes the block. Nested calls open savepoints rather than transactions, which allows partial rollback and makes the construct safe to nest. Once a database error has occurred, the transaction accepts nothing further until the block ends, and a savepoint is what restores it.

  • Leaving an atomic() block normally commits; letting an exception propagate out of it rolls back everything written inside.
  • The try must sit outside the block for the rollback to happen — catching inside means a clean exit and a commit.
  • An inner atomic() is a savepoint, so its failure can be caught and discarded while the outer block still commits its own writes.
  • After any database error, further queries in the same block raise TransactionManagementError; wrap the risky statement in its own atomic() so the rollback stops at a savepoint.
  • Only database writes roll back — schedule mail, jobs, and cache invalidation with transaction.on_commit().

You need to be logged in to access the cloud lab.

Log in