Skip to content

Commit 9647751

Browse files
authored
perf: run the single-statement deck writes at AUTOCOMMIT (#99)
POST /decks and PUT /decks/{id} each send one statement, so a BEGIN and COMMIT around it only add two round trips. They now use an AUTOCOMMIT Transaction, the same pattern chat-app uses for its single-statement reads.
1 parent ee237fd commit 9647751

5 files changed

Lines changed: 93 additions & 2 deletions

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ CI (`.github/workflows/main.yml`) runs `ruff format --check`, `ruff check --no-f
4747
- `dynamic_engine` — `Scope.REQUEST`; `choose_sa_engine` returns the read engine for `GET`/`HEAD` requests, the primary otherwise (including when there is no request). GET handlers cannot write, and a read right after a write may see replica lag.
4848
- `session` — `Scope.REQUEST`, bound to `dynamic_engine`, finalized by `close_session`.
4949
- `transaction` — `Scope.REQUEST`, a `db_retry.Transaction` over `session`. Leaving its block rolls back anything uncommitted and closes the session.
50+
- `autocommit_transaction` — the same `Transaction`, opened at `AUTOCOMMIT` (`autocommit_isolation_level`). `CreateDeckUseCase` and `UpdateDeckUseCase` use it because each sends exactly one statement, which Postgres runs atomically on its own. The asyncpg adapter then sends no BEGIN or COMMIT, so those writes cost one round trip instead of three. A use case with two or more statements, or one that relies on rolling back after a check, as `UpdateCardsUseCase` does, keeps `transaction`. The `db_session` fixture overrides `autocommit_isolation_level` to `None`, because switching the shared test connection to `AUTOCOMMIT` would roll back its outer transaction. `tests/test_autocommit_writes.py` runs both use cases against a real engine instead.
5051

5152
`Repositories` (`Scope.REQUEST`): `decks_repository` and `cards_repository`, on `Database.session` with `auto_commit=False`. The use case commits through `transaction.commit()`.
5253

‎app/ioc.py‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
from app.repositories import CardsRepository, DecksRepository
77
from app.resources.db import (
8+
autocommit_isolation_level,
89
choose_sa_engine,
910
close_sa_engine,
1011
close_session,
@@ -49,6 +50,13 @@ class Database(Group):
4950
creator=Transaction,
5051
kwargs={"session": session},
5152
)
53+
autocommit_isolation_level = providers.Factory(creator=autocommit_isolation_level, bound_type=None)
54+
autocommit_transaction = providers.Factory(
55+
scope=Scope.REQUEST,
56+
creator=Transaction,
57+
bound_type=None,
58+
kwargs={"session": session, "isolation_level": autocommit_isolation_level},
59+
)
5260

5361

5462
class Repositories(Group, scope=Scope.REQUEST):
@@ -65,8 +73,12 @@ class Repositories(Group, scope=Scope.REQUEST):
6573
class UseCases(Group, scope=Scope.REQUEST):
6674
list_decks_use_case = providers.Factory(creator=ListDecksUseCase)
6775
get_deck_use_case = providers.Factory(creator=GetDeckUseCase)
68-
update_deck_use_case = providers.Factory(creator=UpdateDeckUseCase)
69-
create_deck_use_case = providers.Factory(creator=CreateDeckUseCase)
76+
update_deck_use_case = providers.Factory(
77+
creator=UpdateDeckUseCase, kwargs={"transaction": Database.autocommit_transaction}
78+
)
79+
create_deck_use_case = providers.Factory(
80+
creator=CreateDeckUseCase, kwargs={"transaction": Database.autocommit_transaction}
81+
)
7082
list_cards_use_case = providers.Factory(creator=ListCardsUseCase)
7183
get_card_use_case = providers.Factory(creator=GetCardUseCase)
7284
create_cards_use_case = providers.Factory(creator=CreateCardsUseCase)

‎app/resources/db.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import typing
44

55
import fastapi
6+
from sqlalchemy.engine.interfaces import IsolationLevel
67
from sqlalchemy.engine.url import URL, make_url
78
from sqlalchemy.ext import asyncio as sa
89

@@ -39,6 +40,10 @@ def create_read_sa_engine() -> sa.AsyncEngine:
3940
)
4041

4142

43+
def autocommit_isolation_level() -> IsolationLevel | None:
44+
return "AUTOCOMMIT"
45+
46+
4247
async def close_sa_engine(engine: sa.AsyncEngine) -> None:
4348
await engine.dispose()
4449

‎tests/conftest.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ async def db_session(di_container: modern_di.Container) -> typing.AsyncIterator[
5353
connection = await engine.connect()
5454
transaction = await connection.begin()
5555
di_container.override(ioc.Database.dynamic_engine, connection)
56+
# Switching the shared connection to AUTOCOMMIT would roll back the outer transaction.
57+
di_container.override(ioc.Database.autocommit_isolation_level, None)
5658

5759
try:
5860
yield create_session(connection)

‎tests/test_autocommit_writes.py‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import contextlib
2+
import typing
3+
import uuid
4+
5+
import modern_di
6+
import pytest
7+
import sqlalchemy as sa
8+
from advanced_alchemy.exceptions import NotFoundError
9+
from sqlalchemy import event
10+
11+
from app import ioc, models, schemas
12+
from app.resources.db import create_primary_sa_engine
13+
14+
15+
if typing.TYPE_CHECKING:
16+
from sqlalchemy.ext.asyncio import AsyncEngine
17+
18+
19+
@pytest.fixture
20+
async def primary_engine(di_container: modern_di.Container) -> typing.AsyncIterator[AsyncEngine]:
21+
engine = create_primary_sa_engine()
22+
di_container.override(ioc.Database.dynamic_engine, engine)
23+
try:
24+
yield engine
25+
finally:
26+
di_container.reset_override(ioc.Database.dynamic_engine)
27+
await engine.dispose()
28+
29+
30+
@contextlib.contextmanager
31+
def record_in_transaction(engine: AsyncEngine) -> typing.Iterator[list[bool]]:
32+
in_transaction: typing.Final[list[bool]] = []
33+
34+
def record(connection: sa.Connection, *_: object) -> None:
35+
driver_connection = connection.connection.driver_connection
36+
assert driver_connection is not None
37+
in_transaction.append(driver_connection.is_in_transaction())
38+
39+
event.listen(engine.sync_engine, "after_cursor_execute", record)
40+
try:
41+
yield in_transaction
42+
finally:
43+
event.remove(engine.sync_engine, "after_cursor_execute", record)
44+
45+
46+
async def test_create_deck_sends_no_begin_or_commit(
47+
di_container: modern_di.Container, primary_engine: AsyncEngine
48+
) -> None:
49+
key: typing.Final = uuid.uuid4()
50+
try:
51+
with record_in_transaction(primary_engine) as in_transaction:
52+
async with di_container.build_child_container(scope=modern_di.Scope.REQUEST) as container:
53+
use_case = container.resolve_provider(ioc.UseCases.create_deck_use_case)
54+
await use_case(data=schemas.DeckCreate(name="autocommit", idempotency_key=key))
55+
finally:
56+
async with primary_engine.begin() as connection:
57+
await connection.execute(sa.delete(models.Deck).where(models.Deck.idempotency_key == key))
58+
59+
assert in_transaction == [False]
60+
61+
62+
async def test_update_deck_sends_no_begin_or_commit(
63+
di_container: modern_di.Container, primary_engine: AsyncEngine
64+
) -> None:
65+
with record_in_transaction(primary_engine) as in_transaction:
66+
async with di_container.build_child_container(scope=modern_di.Scope.REQUEST) as container:
67+
use_case = container.resolve_provider(ioc.UseCases.update_deck_use_case)
68+
with pytest.raises(NotFoundError):
69+
await use_case(deck_id=-1, data=schemas.DeckUpdate(name="autocommit"))
70+
71+
assert in_transaction == [False]

0 commit comments

Comments
 (0)