9.3 Connections, transactions, and migrations
Autocommit, atomic, and savepoints
How does Django run in autocommit mode by default, how does django 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). 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/ centers on atomic, a factory returning an Atomic instance — a contextlib usable as both "with transaction and "@transaction.
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:
- Outermost block (
in_atomic_block == False): CallsBaseDatabaseWrapperwith.set_autocommit autocommit=Falseandforce_begin_transaction_with_broken_autocommit=True— a workaround specifically for Python’ssqlite3module, which otherwise waits to start a transaction and breaks savepoints, so SQLite’s_start_transaction_under_autocommitissues an explicit"BEGIN"immediately! ThenAtomic.__enter__flips"in_atomic_block = True". - Nested block (
in_atomic_block == True): We are already inside a live SQL transaction, so Django cannot issue a second"BEGIN". Instead, ifsavepoint=True(the default) andnot connection, it calls.needs_rollback BaseDatabaseWrapper, which increments.savepoint "savepoint_state", formats"s<thread_id>_x<n>", executes"SAVEPOINT \"s<tid>_x1\"", and pushes that ID onto"savepoint_ids". (Note that in Django6.1, the standalone manual helpersavepointemitsRemovedInDjango2028Warningin favor ofsavepoint_create.) Passingsavepoint=Falseskips the SQL savepoint and pushesNoneonto"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:
- Inside a nested block with a real
"sid", Django executes"ROLLBACK TO SAVEPOINT"followed immediately by"RELEASE SAVEPOINT"(so the database frees server-side savepoint resources!) and resets"needs_rollback = False"— healing the outer transaction so it can keep working and commit! - Inside a nested block with
"sid is None"(savepoint=False), Django cannot undo partial work locally, so it leaves"needs_rollback = True"to force the enclosing block to roll back. - At the outermost block, Django calls
BaseDatabaseWrapperon clean exit or.commit BaseDatabaseWrapperon failure, and in its.rollback finally:block restoresset_autocommit(True)— which is the exact moment post-commit hooks fire!
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, 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 so the savepoint rollback clears "needs_rollback".
Finally, Django provides durable=True (with transaction) 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 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/":
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:
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.