advanced
Unit of Work
Coordinate multiple repository changes in one transactional boundary so commits, rollbacks, and identity tracking are consistent.
Unit of Work tracks changes across multiple repositories within one transactional boundary so commits and rollbacks stay consistent. It coordinates identity maps, pending inserts, and domain events flushed on commit. Essential when a use case touches several aggregates or tables atomically.
On interviews: explain transaction scope per HTTP request or message handler. Compare with naive per-repository saves and with database transactions alone.
Common pitfalls: long-lived units holding database locks; mixing read and write transactions; events published before commit succeeds.
The trade-off is flexibility versus complexity—know when the simpler path is enough.
Checklist:
- One unit of work per application request or command.
- Commit publishes domain events after persistence.
- Rollback clears pending changes and events.
- Integration tests verify atomic multi-repository updates.