Skip to content

Unit of Work

Spicy — senior dev territoryBackend

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."

Made with passive-aggressive love by manoga.digital. Powered by Claude.