The Analogy: The Pharmacy Fulfilment Tray
Walk behind the counter of a dispensing pharmacy and you see two very different places. Along the walls are the shelves: the permanent, authoritative stock of medicines, and beside them the dispensing log that records what was actually handed to whom. Nothing on those shelves changes casually. When a patient's prescription comes in, the pharmacist does not scribble on the shelves; they pull a fulfilment tray to the bench and assemble the whole order there. The tray is a private staging area for one order, and while the work is in progress the official shelves and log are untouched.
On the tray the pharmacist works freely: they set out bottles, count tablets, restage, swap a substitute, change a quantity. A newly staged item immediately gets a fill-ticket number written on its slot, even though nothing has been handed over yet, so the rest of the order can refer to it. Crucially, the tray holds exactly one slot per medication in this order. If the prescription mentions amoxicillin in two places, both references point at the single amoxicillin slot on the tray -- there are never two rival slots for the same drug drifting out of sync. The tray's picture of the order is internally consistent by construction.
Then comes sign-off. When the pharmacist verifies and signs, the entire tray is dispensed and written to the log in one act: every item on that tray, together, or none of it. If something is wrong at the last moment -- an interaction flag, a stock shortfall, a wrong dose -- the tray is swept straight back to the shelves and the log shows that nothing happened. The patient never walks out with three of their five items recorded and two lost; the order is all-or-nothing, and until sign-off it is entirely reversible.
The failure mode appears when two pharmacists work two trays from the same shelf at once. Each glances at the shelf, sees eight boxes of a drug, and each stages six for their patient, because each check passed on its own. Only at sign-off does the shelf go to minus four, oversold, because the "is there enough?" glance and the "take it" step were not a single locked action. A careful pharmacy prevents this with a real reservation at the shelf, not two independent glances. Flask's data layer draws these lines exactly: the shelves and log are the database, the tray is the SQLAlchemy Session as a unit of work, the one-slot-per-drug rule is the identity map, sign-off is a transaction commit, sweeping the tray back is a rollback -- and the two-pharmacists bug is the check-then-write race that no amount of rollback discipline alone can fix.
Syntax or Core Structure
A model is a Python class that maps to a table. In SQLAlchemy 2.0 you declare a DeclarativeBase, then describe columns with typed Mapped annotations and mapped_column. You obtain a Session bound to an engine, stage objects on it, and commit. The examples here run on plain SQLAlchemy against an in-memory SQLite database, which needs no server; Flask-SQLAlchemy is a thin wrapper that gives you a db object and a request-scoped session, but the model, session, and transaction concepts below are identical.
from sqlalchemy import create_engine, select, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
class Base(DeclarativeBase):
pass
class Product(Base):
__tablename__ = "products"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(50))
price: Mapped[float]
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
with Session(engine) as session:
session.add_all([
Product(name="mallet", price=12.5),
Product(name="chisel", price=8.0),
])
session.commit()
with Session(engine) as session:
rows = session.scalars(select(Product).order_by(Product.name)).all()
for p in rows:
print(f"{p.id} {p.name} {p.price}")
Output:
2 chisel 8.0
1 mallet 12.5
The Product class is the label design for a kind of bottle; a Product(...) instance is one staged item. Base.metadata.create_all builds the table from the model. The first Session block stages two products and commits them -- signs off the tray -- and the second opens a fresh session to read them back with a select, ordered by name. Notice the ids: chisel prints first because of the order_by(Product.name), but it carries id 2, the order it was inserted, while mallet is id 1. The database assigned those primary keys at commit, not the Python code.
Technical Depth: The Unit of Work
The Session is not a database connection. It is a workspace that tracks every object you have loaded or staged, decides when to emit SQL, and holds a single transaction open on your behalf. Understanding when it flushes, what the identity map guarantees, and what rollback throws away is the difference between code that quietly loses data and code that does not.
Object states and the identity map
Every mapped object is in one of four states relative to a session. The session moves it between them as you add, flush, and commit.
| State | Meaning | How it gets there |
|---|---|---|
| Transient | A plain instance the session has never seen | Product(name="x") |
| Pending | Staged, no SQL emitted yet, no primary key | after session.add(obj) |
| Persistent | Flushed or committed, has a primary key, in the identity map | after session.flush() |
| Detached | Has an identity but its session is closed | after the with Session block ends |
The identity map is the rule that within one session there is exactly one Python object per primary key. Load row 1 twice and you get the same object back, so a change made through one reference is visible through the other. A flush is what promotes a pending object to persistent: it sends the INSERT and lets the database assign the autoincrement primary key, which is why the id is None before the flush and a real number after.
from sqlalchemy import create_engine, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(50))
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
with Session(engine) as session:
u = User(name="ada")
session.add(u)
print(f"id before flush: {u.id}")
session.flush()
print(f"id after flush : {u.id}")
same = session.get(User, 1)
print(f"identity map same object: {same is u}")
session.commit()
with Session(engine) as session:
fetched = session.get(User, 1)
print(f"committed name: {fetched.name}")
Output:
id before flush: None
id after flush : 1
identity map same object: True
committed name: ada
Flush, commit, and rollback
A flush pushes pending changes into the open transaction so the database can see them; a commit ends the transaction and makes them permanent. They are not the same. Everything you flush is still provisional until the commit, and rollback discards every uncommitted change -- flushed or not -- and returns the database to its last committed state. The autoflush behaviour means a query inside a session usually sees your own pending rows even before you commit, but another session will not, and a rollback erases them entirely.
from sqlalchemy import create_engine, select, func, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
class Base(DeclarativeBase):
pass
class Note(Base):
__tablename__ = "notes"
id: Mapped[int] = mapped_column(primary_key=True)
body: Mapped[str] = mapped_column(String(50))
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
with Session(engine) as session:
session.add(Note(body="kept"))
session.commit()
with Session(engine) as session:
session.add(Note(body="dropped"))
session.flush()
count = session.scalar(select(func.count()).select_from(Note))
print(f"in-session count before rollback: {count}")
session.rollback()
count = session.scalar(select(func.count()).select_from(Note))
print(f"count after rollback: {count}")
bodies = session.scalars(select(Note.body).order_by(Note.id)).all()
print(f"bodies: {bodies}")
Output:
in-session count before rollback: 2
count after rollback: 1
bodies: ['kept']
The flushed dropped row is visible to the counting query inside the same session -- the count is 2 -- because autoflush sends it into the open transaction. But it was never committed, so rollback removes it and the count falls back to 1. Only kept, which a previous session committed, survives.
Real World Example: A Stock Transfer That Must Not Leak Units
The classic reason transactions exist is moving a quantity from one place to another: the total must never change, and a partial move -- decrement one side, fail before crediting the other -- is corruption. The program below models two storage bins and a transfer that debits the source and credits the destination inside a single session. A good transfer commits; a transfer that would overdraw the source raises, the session rolls back, and the world is left exactly as it was.
from sqlalchemy import create_engine, select, func, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
class Base(DeclarativeBase):
pass
class Bin(Base):
__tablename__ = "bins"
id: Mapped[int] = mapped_column(primary_key=True)
label: Mapped[str] = mapped_column(String(10))
stock: Mapped[int]
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
with Session(engine) as session:
session.add_all([Bin(label="A", stock=10), Bin(label="B", stock=0)])
session.commit()
def transfer(session, src_label, dst_label, qty):
src = session.scalars(select(Bin).where(Bin.label == src_label)).one()
dst = session.scalars(select(Bin).where(Bin.label == dst_label)).one()
if qty > src.stock:
raise ValueError("insufficient stock")
src.stock -= qty
dst.stock += qty
def snapshot(session):
a = session.scalars(select(Bin).where(Bin.label == "A")).one().stock
b = session.scalars(select(Bin).where(Bin.label == "B")).one().stock
return a, b
with Session(engine) as session:
print(f"total before: {session.scalar(select(func.sum(Bin.stock)))}")
with Session(engine) as session:
try:
transfer(session, "A", "B", 4)
session.commit()
except ValueError as e:
session.rollback()
print(f"rejected transfer: {e}")
a, b = snapshot(session)
print(f"after ok transfer A,B: {a} {b}")
with Session(engine) as session:
try:
transfer(session, "A", "B", 20)
session.commit()
except ValueError as e:
session.rollback()
print(f"rejected transfer: {e}")
a, b = snapshot(session)
print(f"after failed xfer A,B: {a} {b}")
with Session(engine) as session:
print(f"total after: {session.scalar(select(func.sum(Bin.stock)))}")
Output:
total before: 10
after ok transfer A,B: 6 4
rejected transfer: insufficient stock
after failed xfer A,B: 6 4
total after: 10
The first transfer of 4 units succeeds: the source drops to 6, the destination rises to 4, and the commit makes both changes permanent together. Because the two writes share one transaction, there is no window in which the 4 units exist in neither bin or in both. This atomicity is the entire point -- the session collected both mutations and the commit applied them as a unit.
The second transfer asks for 20 units from a bin holding 6. The if qty > src.stock check raises before any write, but even if it wrote first, the rollback in the handler would undo the debit. The snapshot afterwards still reads 6 and 4, and the grand total is 10 both before and after the whole exercise. Nothing leaked.
Note that each transfer runs in its own session and its own transaction. That is deliberate: a session is a unit of work with a clear beginning and end, not a long-lived object you keep around. Opening a fresh session per operation is exactly what Flask-SQLAlchemy does per request, and it is why a failed request cannot poison the next one.
The genuine flaw is that the guard is a check-then-act, and that is not atomic across concurrent sessions. Two sessions can both read stock as 6, both decide 5 is fine, and both subtract 5 -- the second write clobbers the first and the bin ends at 1 instead of -4, having shipped 10 units it never had. The in-transaction rollback protects a single session against itself, not against a simultaneous one. The correct fix pushes the check into the database: a conditional UPDATE bins SET stock = stock - :qty WHERE label = :src AND stock >= :qty that changes zero rows when the guard fails, a CHECK (stock >= 0) constraint, or explicit row locking with SELECT ... FOR UPDATE. Reading a value into Python and deciding there always races.
Common Mistakes
- Staging objects and never committing.
session.add(obj)only makes the object pending. Without acommit, the enclosing transaction is rolled back when the session closes and nothing is written. The object even had an id after a flush, which makes the loss especially confusing.
- Committing inside a tight loop. Calling
session.commit()on every iteration wraps each row in its own transaction, turning one fast write into thousands of slow round trips. Stage withadd_allor add in the loop and commit once at the end.
- Sharing one Session across threads or requests. A
Sessionis not thread-safe and its identity map is per-unit-of-work. A module-level session shared between requests leaks objects and state between users. Create a session per request and close it.
- Catching an error without rolling back. Once a flush raises, the session is in a failed transaction and every further query errors until you call
rollback. Swallowing the exception without rolling back leaves the session unusable for the rest of its life.
- Reading the primary key before a flush. A pending object's
idisNoneuntil the database assigns it during a flush or commit. Code that stores or logsobj.idimmediately afteraddrecordsNone.
- Guarding an invariant with check-then-act.
if qty > src.stock: raisereads a value into Python and decides there, which two concurrent sessions can both pass before either writes. Enforce the rule in the database with a conditionalUPDATE ... WHERE stock >= :qtyor aCHECKconstraint.
- Touching attributes on a detached instance. After its session closes, an object is detached; accessing a relationship or a deferred column raises
DetachedInstanceErrorbecause there is no session to load it. Read what you need while the session is open, or re-attach it.
- Building SQL by string interpolation. Formatting user input into a raw SQL string is a SQL-injection hole. Use
select(Model).where(Model.col == value)or bound parameters so values are never parsed as SQL.
- Holding one session open for the whole application. A long-lived session keeps a transaction and its locks open, accumulates a stale identity map, and never sees other sessions' committed changes. Sessions are meant to be short.
Best Practices
- Treat a session as one unit of work. Open it, do a coherent piece of work, commit or roll back, and close it. In Flask this maps to one session per request, which Flask-SQLAlchemy sets up for you.
- Use the session as a context manager.
with Session(engine) as session:guarantees the session is closed, and wrapping the body so a failure triggersrollbackkeeps a broken transaction from leaking into the next operation.
- Let the database own primary keys and invariants. Autoincrement ids,
CHECKconstraints, uniqueness, and foreign keys are enforced by the engine under concurrency; Python-side checks are not. Push rules as close to the data as you can.
- Batch writes and commit once. Stage many rows with
add_alland commit a single transaction. Fewer commits mean fewer round trips and one atomic result instead of many partial ones.
- Prefer
session.get()for primary-key lookups. It consults the identity map first and returns the already-loaded object without a query when possible, unlike a freshselect.
- Write queries in 2.0 style.
select(Model)executed throughsession.scalarsis the current API; the legacyQueryobject is deprecated and mixes concerns the new style keeps separate.
- Keep transactions short. Do slow work -- HTTP calls, file I/O, heavy computation -- outside the open transaction so you are not holding locks while you wait.
- Never interpolate values into SQL text. Always pass data through bound parameters or the expression language so input cannot change the meaning of the statement.
Practice Exercises
- Extend the
Productmodel with acreated_atcolumn defaulting to the current time, insert three products a moment apart, and query them ordered newest-first. Confirm the order matches insertion order and not the primary key order.
- Rewrite
transferto be safe under concurrency. Replace the Pythonifcheck with a conditionalUPDATE bins SET stock = stock - :qty WHERE label = :src AND stock >= :qty, inspect the affected row count, and raise only when zero rows changed. Prove an over-large transfer still leaves the total unchanged.
- Demonstrate the identity map. In one session, load the same row twice with
session.get, mutate the attribute through the first reference, and print it through the second. Show they are the same object and that the change is visible through both before any commit.
- Force a mid-batch failure. Add five valid rows and one that violates a
CHECKor uniqueness constraint in a single transaction, catch the flush error, roll back, and query the table to prove that none of the five valid rows survived either.