Unit of Work
ELI5 — The Vibe Check
A unit of work tracks all database changes during a business operation and commits them as a single transaction. Instead of saving each entity change separately, it batches everything and does one commit at the end. It's like a shopping cart — add items throughout, then checkout once.
Real Talk
The Unit of Work pattern maintains a list of objects affected by a business transaction and coordinates the writing out of changes. It tracks new, modified, and deleted entities, then persists all changes in a single database transaction. This ensures atomicity and reduces database round trips. SQLAlchemy's Session and Entity Framework's DbContext implement this pattern.
Show Me The Code
async function transferFunds(fromId, toId, amount) {
const uow = new UnitOfWork();
try {
const from = await uow.accounts.get(fromId);
const to = await uow.accounts.get(toId);
from.debit(amount);
to.credit(amount);
await uow.commit(); // Single transaction
} catch (e) {
await uow.rollback();
}
}
When You'll Hear This
"The unit of work commits all entity changes in a single transaction." / "SQLAlchemy's session IS a unit of work — it tracks dirty objects and flushes them together."
Related Terms
ACID (Atomicity, Consistency, Isolation, Durability)
ACID is the four guarantees a reliable database makes about transactions. It is the reason you trust a bank's database with your money.
ORM (Object-Relational Mapper)
An ORM is like a translator between your code and your database. Instead of writing scary SQL, you just write normal code like `User.
Repository Pattern
Repository Pattern puts a layer between your business logic and your database, so your business code never writes SQL directly.
Transaction
A transaction groups multiple database operations into one all-or-nothing bundle. Either ALL of them succeed, or NONE of them happen.