Learn

Architecture & pattern guides

Read the idea, build it on a Grid, prove it in a challenge. Short, practical guides — illustrated with RodGrid's own nodes — on system design, design patterns, flow modeling, and how to get the most out of the app.

All articles

Unit of Work

Why a use case that writes as it goes can leave half its changes in the database, and how a unit of work records what was added, changed and removed, then lets the application service commit it all in one transaction: the order of the writes, version checks at commit, and why it lives for one request and one database.

Four transactions for one Save

A driving school's online course has a quiz on motorway rules, quiz 31, with thirty questions. On Tuesday evening an instructor reworks it: she rewrites question 12, deletes question 9, which tested a rule that has since changed, adds two new questions about the new rule, and presses Save. The editor's code saves as it goes, each repository call writing at once, each in its own transaction:

  1. The quiz repository updates the text of question 12.
  2. It deletes question 9 and its four answer choices.
  3. It inserts the first new question and its choices.
  4. The second new question fails a database check, because one of its choices is longer than the column allows.
  5. The editor shows an error, and the instructor closes the tab to try again in the morning.

The database now holds a quiz she never saved: the old rule's question gone, the first new question in, the second missing. Learners who take the quiz that evening get that version, though every write was correct. The use case, save the quiz edits, was spread over four transactions, so a failure in the fourth could not undo the first three.

Keep a list, write it at the end

A Unit of Work keeps track of every object a use case loads, adds, changes or removes, and sends the writes at the end, in one transaction, so that all of them take effect or none does. The quiz repository still reads, but it no longer writes when it is called. It registers what happened with the unit of work: the two new questions are new, question 12 is dirty (changed since it was loaded), and question 9 is removed. Some implementations are told about each change like this; others find the dirty objects themselves, by comparing each loaded object with a copy taken when it was loaded.

In this editor, when the use case is done, one call to commit() opens a transaction, issues every write and commits. Replay Tuesday with it: the long choice fails inside commit(), the transaction rolls back, and quiz 31 is still the thirty questions it had before she pressed Save. The instructor sees the same error. The learners see the old quiz, whole.

The promise covers the writes this commit sends to this database, and nothing else. An email sent from inside the use case is not taken back by the rollback, and neither is anything written to another service.

One commit for the whole use case

Repositories only register what changed. The application service calls commit once, and the unit of work turns its lists into one transaction.

Who calls commit

The object that knows where the use case ends is the application service that runs it, here SaveQuizEdits. It loads the quiz through the repository, applies the instructor's edits through the quiz's own methods, and calls commit() once, at the end. If the repository committed inside its own save, the edits would be one transaction per repository call again, which is Tuesday's bug; and in a use case that uses two repositories, each committing on its own, a failure in the second leaves the first one's writes in place. Application Service (DDD) describes that thin coordinator.

A unit of work commits whatever it was given. Whether one use case should change two aggregates in one transaction at all is a separate design rule, and Aggregate owns it.

In what order the writes go

The writes do not go out in the order things happened. A new question needs its row before its choices can point at it through a foreign key, and a removed question's choices have to go before the question unless the foreign key deletes them by cascade. So the unit of work orders the writes at commit: parents inserted before their children, children deleted before their parents.

Two instructors, version 7

On Wednesday two instructors open quiz 31 a minute apart. The quiz row carries a version number, and each Save sends back the version its instructor opened; the unit of work checks that one at commit, not whatever version it loads when the request arrives.

  1. Keiko opens quiz 31 at version 7 and rewrites question 4.
  2. Tomás opens quiz 31, also at version 7, and rewrites question 4 differently.
  3. Keiko saves. Her commit writes question 4 and runs UPDATE quizzes SET version = 8 WHERE id = 31 AND version = 7, which matches one row.
  4. Tomás saves. His commit runs the same update, which now matches no row, so the unit of work rolls his transaction back instead of committing and the service tells him the quiz changed after he opened it.

That check is optimistic concurrency. Nothing is locked while the instructors edit, which can take twenty minutes, and the conflict is caught at commit, where both versions finally meet the database. Without it, Tomás's commit would silently overwrite Keiko's question, a lost update. Why that happens, and the conditional update this check is a form of, are in Transactions & isolation levels.

The check protects only what carries the version. Here the version is on the quiz, so a change anywhere in the quiz has to bump it. Check the question rows alone, and two edits to different questions both pass, even when a rule spans them, such as points that must add up to 100.

One request, one database

Those twenty minutes of editing are not inside a unit of work. The browser holds the changes, and the Save request carries them with the version the instructor started from. The unit of work is created when that request starts, lives while SaveQuizEdits runs, and is discarded when it ends, whether the commit succeeded or rolled back.

Watch outKeep the unit of work short. The database holds locks only while a transaction is open, and the unit of work's memory grows with every object it tracks, so one kept alive across unrelated use cases keeps growing. It scopes one use case (typically one request), never several requests.

Most implementations keep an Identity Map next to the lists, one object per row within the unit of work, so loading question 12 twice returns the same object, not two copies that drift apart. Hibernate's Session, JPA's EntityManager and Entity Framework's DbContext implement the pattern: they track what they load, and a flush, or EF's SaveChanges, sends the changes as writes inside a transaction, which the commit makes durable (SaveChanges opens and commits one itself unless one is already open); how they map objects to rows is the other half of Active Record vs Data Mapper.

And it commits in one database. The notice telling enrolled learners that quiz 31 changed is outside the transaction: sent before the commit it may announce a change that then fails, sent after it can be lost to a crash in between, and writing it as a row in the same transaction, for a separate process to deliver, is the Transactional Outbox. A use case that changes data owned by several services, each with its own database, rarely has a single commit it can make, and coordinating their local transactions is what a Saga does.

Commit once, on a Grid

In the DDD Tactical Building Blocks Challenge, the Unit of Work is one of six building blocks around a single use case, and the requirement for it is that it commits all of that use case's changes atomically. Choose a use case that changes more than one row, as saving quiz edits does, and draw what each repository registers as an edge into the unit of work, with commit coming only from the application service. Before you finish, ask of your Grid the question Tuesday's bug asks: if the last write failed, which node would undo the first?

Practice this