Django 6.1.3

9.3 Connections, transactions, and migrations

Autocommit, atomic, and savepoints

How does Django run in autocommit mode by default, how does django.db.transaction.atomic nest via SQL savepoints, and why does catching a DatabaseError inside atomic poison the outer block?

By default, every Django database connection runs in autocommit mode ("AUTOCOMMIT = True" in ConnectionHandler.configure_settings). Every standalone Model.save, QuerySet.update, or QuerySet.delete executes inside its own implicit transaction and commits to disk immediately. That default keeps single writes simple and avoids idle-in-transaction locks — but as our ch09-bench benchmark showed, running 100 inserts in autocommit on file-backed SQLite costs 559.239 ms (100 separate disk fsyncs) versus 23.796 ms inside a single atomic block (23.50x faster).

How Atomic manages transactions and nested savepoints

Django’s transaction API in django/db/transaction.py centers on atomic, a factory returning an Atomic instance — a contextlib.ContextDecorator usable as both "with transaction.atomic():" and "@transaction.atomic".

Instead of tracking a simple depth counter, Atomic.__enter__ and Atomic.__exit__ maintain four fields directly on the thread-local BaseDatabaseWrapper: "in_atomic_block", "savepoint_ids" (a stack of active savepoint identifiers or None), "atomic_blocks" (a stack of active Atomic instances), and needs_rollback.

Look at what Atomic.__enter__ does in the two possible states:

  1. Outermost block (in_atomic_block == False): Calls BaseDatabaseWrapper.set_autocommit with autocommit=False and force_begin_transaction_with_broken_autocommit=True — a workaround specifically for Python’s sqlite3 module, which otherwise waits to start a transaction and breaks savepoints, so SQLite’s _start_transaction_under_autocommit issues an explicit "BEGIN" immediately! Then Atomic.__enter__ flips "in_atomic_block = True".
  2. Nested block (in_atomic_block == True): We are already inside a live SQL transaction, so Django cannot issue a second "BEGIN". Instead, if savepoint=True (the default) and not connection.needs_rollback, it calls BaseDatabaseWrapper.savepoint, which increments "savepoint_state", formats "s<thread_id>_x<n>", executes "SAVEPOINT \"s<tid>_x1\"", and pushes that ID onto "savepoint_ids". (Note that in Django 6.1, the standalone manual helper savepoint emits RemovedInDjango2028Warning in favor of savepoint_create.) Passing savepoint=False skips the SQL savepoint and pushes None onto "savepoint_ids" instead.

On exit, Atomic.__exit__ pops the top "sid" from "savepoint_ids" (or sets "in_atomic_block = False" if the stack is empty). When an exception occurs or needs_rollback is True:

Figure 9.2 Every SQL statement, savepoint transition, run_on_commit count, and exception is verified directly against ch09-database. Notice that rolling back an inner savepoint simultaneously undoes its SQL writes, resets "needs_rollback = False", and prunes any on_commit callbacks queued inside that savepoint.

The poisoned-block trap (needs_rollback) and durable=True

Why does catching an IntegrityError directly inside an atomic block blow up the next query with TransactionManagementError?

Because PostgreSQL puts an entire transaction into an aborted state the instant any SQL statement raises a database error — rejecting all further queries until "ROLLBACK" or "ROLLBACK TO SAVEPOINT". To guarantee identical cross-backend safety even on SQLite and MySQL (which do not abort the whole transaction on a constraint failure), Django’s ORM write paths wrap database operations inside mark_for_rollback_on_error: whenever an exception escapes while "in_atomic_block" is True, Django sets needs_rollback = True and saves "rollback_exc = exc". Every subsequent query executed via CursorWrapper calls BaseDatabaseWrapper.validate_no_broken_transaction, which sees "needs_rollback == True" and immediately raises TransactionManagementError chained from the original exception!

The fix is always the same: never put a try ... except DatabaseError: around a failing write inside an atomic block without wrapping the failing write in an inner with transaction.atomic(): so the savepoint rollback clears "needs_rollback".

Finally, Django provides durable=True (with transaction.atomic(durable=True):) for service functions that must guarantee their changes are physically committed when the function returns (for example, right before notifying an external payment gateway). Inside Atomic.__enter__ (lines 196–204), if "self.durable" is True and "connection.atomic_blocks" is already non-empty (excluding the special "_from_testcase" wrapper used by TestCase), Django immediately raises RuntimeError rather than silently demoting your transaction into an uncommitted savepoint.

Watch nested savepoint SQL, the poisoned-block trap, and nested durable=True execute live on "desk/":

Recorded on Django 6.1.3 ch09-database script
3. Autocommit, nested atomic() savepoints, needs_rollback, and durable=True
  nested_savepoint_sql:
    BEGIN
    INSERT INTO "newsroom_desk" ("name", "slug", "section_code") VALUES (%s, %s, %s) RETURNING "newsroom_desk"."id"
    SAVEPOINT "s<tid>_x1"
    INSERT INTO "newsroom_desk" ("name", "slug", "section_code") VALUES (%s, %s, %s) RETURNING "newsroom_desk"."id"
    ROLLBACK TO SAVEPOINT "s<tid>_x1"
    RELEASE SAVEPOINT "s<tid>_x1"
  after_nested_atomic: science_exists=True temp_exists=False
  poisoned_block: needs_rollback=True
  poisoned_next_query = TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.
  nested_durable_error = RuntimeError: A durable atomic block cannot be nested within another atomic block.

And look at the full transaction-mode comparison from ch09-bench on file-backed SQLite — showing that even 100 nested savepoints inside one transaction (30.377 ms) add only 6.58 ms total (~66 us per savepoint) while avoiding 529 ms of redundant autocommit fsyncs:

Recorded on Django 6.1.3 ch09-bench script
1. 100 Correction inserts on file-backed SQLite (7 trials, median ms)
  mode                              commits  median_ms   speedup
  autocommit (100 commits)              100    559.239     1.00x
  1 atomic() + 100 savepoints             1     30.377    18.41x
  1 atomic() (0 savepoints)               1     23.796    23.50x
  1 atomic() + bulk_create(100)           1      8.738    64.00x

Database writes are only half of an atomic workflow: the other half is external side effects — queueing a task, sending an email, invalidating a cache — that cannot be rolled back by SQL. We open on_commit next in transaction.on_commit and post-commit ordering.