Unit of Work
Escrito por Darjus Kazakevic · revisado el
One business operation, one transaction, one flush.
A use case may create, change and delete several objects. A Unit of Work records all of these changes. On commit it turns them into inserts, updates and deletes, runs them in the right order inside one transaction, and rolls everything back if one fails.
It answers one question: who owns the transaction? The answer is the whole business operation, not each repository call. The unit covers one database. An email, a card charge or a call to another service cannot be rolled back, so it stays outside, through an outbox row or a saga.
En esencia — Track every object a business operation touches and commit all the changes together in one transaction, so a half-applied change never reaches the database.
Cuándo recurrir a él
Recurre a él cuando
- One use case writes several objects that must all succeed or all fail
- Several repositories take part in one business operation
- You want one place to run version checks before commit
Reconsidéralo cuando
- A single write, where a plain transaction is enough
- Your ORM's session or DbContext already does this for you
- The work spans two databases or services: use a saga instead
How it works
- Change tracking
- The unit keeps three sets as you work: new, dirty (changed) and removed. Nothing reaches the database until commit. Then it turns the sets into the smallest list of writes.
- The commit boundary
- Commit opens one transaction, flushes every tracked change, and either succeeds as a whole or rolls back as a whole. The boundary is the business operation, not the repository call.
- Concurrency and write order
- Because it sees every write, the unit is the natural place for version checks (optimistic locking) and for ordering writes so foreign keys always hold.
Applying it well
- Keep anything you cannot undo outside
- An email, a card charge or an HTTP call cannot be rolled back. Write an outbox row inside the transaction and do the real thing after commit, or a rollback leaves an effect behind.
- Let the use case own the boundary
- Open the unit in the application layer, around one business operation. Repositories enlist their changes and never commit on their own, or a failure halfway leaves partial data.
- Keep the transaction small and short
- Change one aggregate per transaction where you can. A unit that touches hundreds of rows holds locks longer and makes every other writer wait.
Errores habituales
- A unit that lives longer than one request and leaks state into the next one.
- Sending email or charging a card inside the boundary. A rollback cannot take it back.
- Huge transactions that hold row locks and slow down every other writer.
- No rollback on the error path, which leaves a pooled connection mid-transaction.