Lesson 20 of 59Data and storage
Transactions and Concurrency Bugs in Web Apps
Find and fix race conditions in a FastAPI and SQLAlchemy app: atomic updates, ON CONFLICT, row locks, version columns, retries, the outbox and advisory locks.
Two people press "Buy" on the last concert ticket within the same 30 milliseconds. Both get a confirmation email, and one of them gets a refund and an apology on the night. Nothing in your logs looks wrong, every unit test passes, and the bug only appears under real traffic. Concurrency bugs are like that: code that is correct for one request is wrong for two. The SQL & Databases course explains the database side in Transactions and ACID, Isolation Levels and Anomalies and Locks, Deadlocks and Safe Concurrency. This lesson is the application side: how these bugs look in FastAPI and SQLAlchemy code, the fix for each one in SQLAlchemy, and where your transactions should begin and end.
Async code races too
A common belief is that an asyncio app cannot have races because only one coroutine runs at a time. That holds between awaits. At every await, other requests run, and a value you read before the await can be stale after it. And you rarely run one process anyway: several Uvicorn workers and several pods all talk to the same database.
The pattern behind most of these bugs is check, then act: read a value, decide in Python, then write. Here is the last-ticket bug for real, with SQLite. Each request is a generator, and every yield stands for an await where the event loop switches to the other request:
Press Run (⌘ Enter) to see what happens.The naive version sold one copy twice, and the stock still looks perfectly healthy at 0. The atomic version moved the check into the same statement as the write, so the database decides, and only one buyer gets a row back.
Run after the block above. Three buyers, two copies in stock, naive version. What is printed?
reset(2) sold = [] run_concurrently(*(buy_naive(n, sold) for n in ["ana", "ben", "cy"])) print(len(sold), stock_now())
The bug catalogue
Almost every concurrency bug in a web app is one of these five. The theory behind each is in Isolation Levels and Anomalies; what matters here is recognising them in code review.
| Bug | Looks like in code | Symptom | First fix to reach for |
|---|---|---|---|
| Lost update | obj.stock = obj.stock - 1 after a get | Counts drift, edits vanish | Atomic UPDATE |
| Oversell / double spend | if balance >= amount: balance -= amount | Negative stock or balance | Conditional UPDATE ... WHERE stock > 0 |
| Check-then-insert duplicate | if not exists(email): insert(email) | Two accounts for one email | Unique constraint plus ON CONFLICT |
| Write skew | Check a rule over several rows, write one row | Rule broken (nobody on call) | Constraint, lock, or SERIALIZABLE |
| Read-modify-write counter | page.views += 1 | Fewer views than requests | Atomic increment |
Match each bug to the fix that removes it most simply.
Fix 1: let one statement decide
The best fix is the one with no extra machinery. Put the check and the write in one statement, and the database's row lock makes it safe at the default isolation level:
from sqlalchemy import update
from app.models import Product
async def reserve_stock(session: AsyncSession, product_id: int, quantity: int) -> int | None:
result = await session.execute(
update(Product)
.where(Product.id == product_id, Product.stock >= quantity)
.values(stock=Product.stock - quantity)
.returning(Product.stock)
)
return result.scalar_one_or_none() # None means sold out: answer 409The ORM can do atomic increments too. page.views += 1 reads the value into Python and writes back a number, which loses updates. Assigning a SQL expression does not:
page = await session.get(Page, page_id)
page.views = Page.views + 1 # flush sends: UPDATE pages SET views = views + 1 WHERE id = ...Five concurrent requests doing this end at 5. Five doing += 1 can end at 1.
Fix 2: constraints, ON CONFLICT and IntegrityError
"Check if the email exists, then insert" always has a gap between the check and the insert. Close it with a unique constraint, which the database enforces atomically, and handle the conflict.
When a duplicate is a normal outcome, use Postgres's INSERT ... ON CONFLICT through the dialect's insert:
from sqlalchemy.dialects.postgresql import insert
stmt = (
insert(Subscriber)
.values(email=email, list_id=list_id)
.on_conflict_do_nothing(index_elements=["list_id", "email"])
.returning(Subscriber.id)
)
new_id = (await session.execute(stmt)).scalar_one_or_none() # None: already subscribed
upsert = (
insert(DailyStat)
.values(day=today, signups=1)
.on_conflict_do_update(index_elements=["day"], set_={"signups": DailyStat.signups + 1})
)When a duplicate is an error for the user, let the insert fail and translate it. Wrap it in a savepoint with begin_nested(), so the failure rolls back only that insert and the rest of the request's transaction stays usable:
from sqlalchemy.exc import IntegrityError
UNIQUE_VIOLATION = "23505"
async def register(session: AsyncSession, email: str) -> User:
user = User(email=email.lower())
try:
async with session.begin_nested(): # SAVEPOINT
session.add(user)
except IntegrityError as exc:
if getattr(exc.orig, "sqlstate", None) == UNIQUE_VIOLATION:
raise EmailTaken(email) from exc # an exception handler maps this to 409
raise
return userCheck the SQLSTATE rather than the message text, and only map 23505 to 409. A foreign key or NOT NULL failure is a different bug and should not look like "email taken" to the user.
Fix 3: lock the row you are about to change
When the logic cannot be one statement (checking a credit limit, calling a pricing function, validating a state transition), lock the row as you read it. In SQLAlchemy that is with_for_update():
async def approve_refund(session: AsyncSession, order_id: int) -> Order:
order = await session.get(Order, order_id, with_for_update=True) # SELECT ... FOR UPDATE
if order is None:
raise NotFound()
if order.status != "paid":
raise InvalidTransition(order.status, "refunded")
order.status = "refunded"
order.refunded_at = func.now()
return orderA second request for the same order now waits at the get until the first commits, then sees status = "refunded" and is refused. The options map directly to the SQL clauses: with_for_update(nowait=True) fails immediately with SQLSTATE 55P03 (good for "someone else is editing this"), skip_locked=True passes over locked rows (good for queues), of=Order limits locking to one table in a join, and key_share=True takes the weaker FOR NO KEY UPDATE. The SQL & Databases course's Locks, Deadlocks and Safe Concurrency lesson explains the lock strengths.
One SQLAlchemy trap is worth knowing. If the object is already in the session's identity map, a select(Order).with_for_update() takes the lock but hands you back the existing Python object with its old attribute values. You locked the row and then decided based on stale data. Either lock on the first read, use session.get(..., with_for_update=True) (which refreshes the object), or add .execution_options(populate_existing=True) to the select.
Deadlocks in app code come from locking the same rows in different orders. A transfer from account 5 to 9 that locks 5 then 9, running at the same moment as a transfer from 9 to 5, will deadlock, and Postgres kills one with 40P01. The fix is to always lock in a consistent order, which in SQLAlchemy is one query: select(Account).where(Account.id.in_([src, dst])).order_by(Account.id).with_for_update().
Fix 4: optimistic locking with a version column
Row locks cannot span user think-time. An admin who opens an edit form and saves ten minutes later needs an optimistic check instead. SQLAlchemy builds it in:
class Product(Base):
__tablename__ = "products"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
price_cents: Mapped[int]
version: Mapped[int] = mapped_column(nullable=False)
__mapper_args__ = {"version_id_col": version}Every ORM UPDATE now includes WHERE id = :id AND version = :old_version and sets version = version + 1. If no row matched, someone else saved first, and the flush raises StaleDataError ("expected to update 1 row(s); 0 were matched"). Turn it into a status code in one place:
from fastapi import Request
from fastapi.responses import JSONResponse
from sqlalchemy.orm.exc import StaleDataError
async def stale_data_handler(request: Request, exc: StaleDataError) -> JSONResponse:
return JSONResponse(
status_code=409,
content={"type": "about:blank", "title": "Conflict", "detail": "This record was changed by someone else. Reload and try again."},
media_type="application/problem+json",
)
app.add_exception_handler(StaleDataError, stale_data_handler)For a form, the client must send back the version it loaded (in the body, or as an If-Match header holding an ETag, answered with 412 on a mismatch), and the route checks it against the loaded row before applying changes. Otherwise the request just loads the latest version and overwrites it.
Fix 5: SERIALIZABLE and a retry loop
Some rules span many rows and cannot become a constraint: "at least one doctor on call", "total allocations under the budget". SERIALIZABLE makes Postgres detect the dangerous interleaving and abort one transaction with SQLSTATE 40001. Your job is to retry the whole unit of work, with a fresh session, which means the retry loop must sit outside the session, not inside a request-scoped dependency:
import asyncio
import random
from sqlalchemy.exc import DBAPIError
from sqlalchemy.ext.asyncio import async_sessionmaker
from app.db import engine
RETRYABLE = {"40001", "40P01"} # serialization_failure, deadlock_detected
SerializableSession = async_sessionmaker(
engine.execution_options(isolation_level="SERIALIZABLE"), expire_on_commit=False
)
async def run_serializable(work, attempts: int = 5):
for attempt in range(1, attempts + 1):
try:
async with SerializableSession() as session, session.begin():
return await work(session) # the COMMIT runs as the block exits, inside the try
except DBAPIError as exc:
if getattr(exc.orig, "sqlstate", None) not in RETRYABLE or attempt == attempts:
raise
await asyncio.sleep(random.uniform(0, 0.05 * 2 ** attempt))DBAPIError is the base class SQLAlchemy uses for driver errors, so this catches the failure from asyncpg and from psycopg, and exc.orig.sqlstate gives the code with both drivers. Against two concurrent "go off call" requests, the first attempt of one fails with 40001, the retry re-reads, sees only one doctor left, and refuses. The rule holds.
Put one retried attempt of a serializable unit of work in order.
- Tap the steps below in the right order.
Where the transaction begins and ends
There are two workable patterns in FastAPI.
- One transaction per request. The session dependency opens
session.begin()and commits after the route. It is simple and it is what most CRUD services use. Remember from Async Databases that the dependency needsscope="function", or a failed commit happens after the client already got a 200. - The service owns the transaction. The dependency only creates the session, and each use case runs
async with session.begin():around exactly the work that must be atomic. This is the pattern you need for retries, for several transactions in one request, and for anything that calls another service.
The rule from Transactions and ACID applies with full force: never hold a transaction open across an HTTP call, an email send or anything else slow that you do not control. Commit, call, then open a second short transaction to record the result.
The dual-write problem and the outbox
A request that saves an order and then publishes order.placed to a queue (or sends an email, or calls a webhook) writes to two systems. There is no transaction across both. Commit first and crash before publishing, and the event is lost. Publish first and the commit fails, and you announced an order that does not exist.
The transactional outbox fixes it by making the event part of the database transaction:
async def place_order(session: AsyncSession, cart: Cart) -> Order:
async with session.begin():
order = Order(customer_id=cart.customer_id, total_cents=cart.total_cents)
session.add(order)
await session.flush() # get order.id
session.add(OutboxEvent(topic="order.placed", payload={"order_id": order.id}))
return order # the order and its event committed together, or neither did
async def relay_outbox(batch: int = 100) -> int:
async with SessionLocal() as session, session.begin():
events = (await session.scalars(
select(OutboxEvent)
.where(OutboxEvent.published_at.is_(None))
.order_by(OutboxEvent.id)
.limit(batch)
.with_for_update(skip_locked=True) # several relay workers never grab the same rows
)).all()
for event in events:
await broker.publish(event.topic, event.payload, message_id=str(event.id))
event.published_at = func.now()
return len(events)One transaction. If it fails, neither the order nor the event exists. No broker call happens in the request.
A lighter option exists for events you can afford to lose, such as cache invalidation: collect them in session.info during the transaction and send them from SQLAlchemy's after_commit session event, the equivalent of Django's transaction.on_commit. It never fires for a rolled-back transaction, but a crash between the commit and the send still loses the event. For anything that matters, such as emails, payments and integrations, use the outbox.
Advisory locks for one-at-a-time work
Some work must not run twice at once, but it is not about any row: the nightly invoice run when three pods all have the scheduler enabled, or a migration-like backfill. Postgres advisory locks are named locks with a 64-bit integer key that mean whatever your app decides:
NIGHTLY_INVOICES = 7_210_001 # any fixed bigint, documented next to the job
async def run_nightly_invoices() -> None:
async with SessionLocal() as session, session.begin():
got_lock = await session.scalar(select(func.pg_try_advisory_xact_lock(NIGHTLY_INVOICES)))
if not got_lock:
return # another pod is already doing it
await generate_invoices(session)Prefer the _xact_ variants. The lock is released automatically at commit or rollback, and it works behind PgBouncer in transaction mode. The session-level pg_advisory_lock belongs to a server connection that a transaction pooler may hand to someone else, and a forgotten unlock keeps it held until the connection closes.
- check-then-act
- Reading a value, deciding in application code, then writing. Races whenever another request can run in between.
- atomic update
- A single UPDATE that checks and changes a row in one statement, such as SET stock = stock - 1 WHERE stock > 0.
- with_for_update
- SQLAlchemy's way to add FOR UPDATE (with nowait, skip_locked or of) to a SELECT, locking the rows it reads.
- version_id_col
- A SQLAlchemy mapper option that adds an optimistic version check to every UPDATE and raises StaleDataError on a conflict.
- SQLSTATE 40001
- serialization_failure: Postgres aborted the transaction to keep it serializable. Retry the whole unit of work.
- transactional outbox
- Writing outgoing events to a table in the same transaction as the data, then publishing them from a separate relay.
- advisory lock
- A Postgres lock on an app-chosen integer key, used for only-one-at-a-time jobs rather than rows.