← Concepts

阅读中文版本

Unit of Work

A unit of work tracks changes during a business transaction and writes them out in one coordinated commit, centralising transaction and concurrency handling.

architecture

Definition

A unit of work maintains a list of objects affected by a business transaction and coordinates the writing of those changes and the resolution of concurrency problems in a single commit.

Context and scope

It is used to group several repository operations into one atomic transaction and to defer writes until the end of a request.

Common misconceptions

  • a unit of work is just a database transaction wrapper
  • changes are written as soon as they occur

Anti-patterns

  • committing inside each repository call and losing atomicity
  • keeping one unit of work open across a whole long-lived process

Related concepts

Related examples

Authoritative source

https://martinfowler.com/eaaCatalog/unitOfWork.html

Definition

A unit of work maintains a list of objects affected by a business transaction and coordinates the writing of those changes and the resolution of concurrency problems in a single commit.

It is used to group several repository operations into one atomic transaction and to defer writes until the end of a request. Compared to simpler alternatives, this concept fits best when the trade-off it represents is the one the system actually cares about.

When to use it

A common use case is applying it at the boundary where the cost of getting it wrong is highest, and the scenario usually involves a concrete guarantee the system must uphold. Unlike an ad hoc approach, it makes that guarantee explicit, reviewable, and testable.

How it works

Changes accumulate in memory and are flushed at commit, so several aggregates can be persisted together and either all succeed or all roll back.

It centralises concurrency handling, such as optimistic version checks, rather than scattering those checks across individual writes.

Trade-offs and alternatives

A unit of work is scoped to a transaction and should live no longer than that, since a long-lived one accumulates state and holds connections unnecessarily. The main drawback is the extra complexity it introduces, so the benefit should clearly outweigh that cost before a team adopts it.

Common misconceptions

A persistent misconception is that a unit of work is just a database transaction wrapper. Another is that changes are written as soon as they occur. For example, an engineer who assumes otherwise may design around a guarantee that does not actually exist, which only becomes obvious under load or failure.

Anti-patterns to avoid

Two recurring anti-patterns are to committing inside each repository call and losing atomicity and to keeping one unit of work open across a whole long-lived process. Both tend to surface as hard-to-debug production issues rather than obvious test failures. Related concepts include Publish-Subscribe Messaging, Message Broker, Layered Architecture.