---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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` (`django/db/transaction.py:atomic`), a factory returning an **`Atomic`** (`django/db/transaction.py:Atomic`) instance — a `contextlib.ContextDecorator` usable as both `"with transaction.atomic():"` and `"@transaction.atomic"`.

Instead of tracking a simple depth counter, `Atomic.__enter__` (`django/db/transaction.py:Atomic.__enter__`) and `Atomic.__exit__` (`django/db/transaction.py:Atomic.__exit__`) maintain four fields directly on the thread-local `BaseDatabaseWrapper` (`django/db/backends/base/base.py: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` (`django/db/backends/base/base.py: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` (`django/db/backends/base/base.py: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 `django/db/transaction.py:savepoint` emits `RemovedInDjango2028Warning` in favor of `django/db/transaction.py: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`:

- 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 `BaseDatabaseWrapper.commit` on clean exit or `BaseDatabaseWrapper.rollback` on failure, and in its `finally:` block restores `set_autocommit(True)` — which is the exact moment post-commit hooks fire!

```text figure=atomic-savepoints-oncommit
Nested atomic() savepoint stack, on_commit() discard, and the needs_rollback trap (Django 6.1.3)

1. Nested atomic() savepoints & run_on_commit queue on desk/:
   Outer atomic() [BEGIN, savepoint_ids=[]]:
     Desk.create('science') + on_commit('outer-before', sids={})
     Inner atomic() [SAVEPOINT s<tid>_x1, savepoint_ids=[x1]]:
       Desk.create('temp-desk') + on_commit('inner-rolled-back', sids={x1})
       raise RuntimeError -> ROLLBACK TO SAVEPOINT + RELEASE SAVEPOINT
       run_on_commit drops {x1} (2 -> 1 queued); needs_rollback reset to False
     on_commit('outer-after', sids={}) -> COMMIT -> set_autocommit(True)
     Result: science=True, temp=False; hooks=['outer-before', 'outer-after']

2. Poisoned-block trap (needs_rollback=True):
   TRAP: try: Desk.create(slug='metro') except IntegrityError inside outer atomic()
         -> mark_for_rollback_on_error sets needs_rollback=True -> next query raises TransactionManagementError
   SAFE: wrap risky write in inner with atomic(): -> savepoint rollback resets needs_rollback=False
```

*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` (`django/db/utils.py:IntegrityError`) directly inside an `atomic` block blow up the *next* query with `TransactionManagementError` (`django/db/transaction.py: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` (`django/db/transaction.py: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` (`django/db/backends/utils.py:CursorWrapper`) calls `BaseDatabaseWrapper.validate_no_broken_transaction` (`django/db/backends/base/base.py: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/"`:

```text recording=ch09-database
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:

```text recording=ch09-bench
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` (`django/db/transaction.py:on_commit`) next in [transaction.on_commit and post-commit ordering](on-commit.md).
