Transaction

Unit of work

Definition
A transaction treats a series of database changes as a unit.
Transaction

A transaction is a series of database changes that can either be committed (executed) or rolled back (ignored). The term unit of work is applied to the same principle at the business logic level.

A simple example of a transaction concerns the movement of money from customer A to customer B. The amount of A is decreased, while the amount of B is increased. If this series of events would somehow stop halfway, an inconsistent state would be formed, which would take manual intervention to fix. By grouping the series and committing it as a whole, this inconsistency cannot occur.

It's good to think about transactions at the start of a project and agree on the place in code where the transaction starts and ends. When every CRUD (Create, Read, Update, Delete) action contains a commit, it is impossible to create transactions from series of these actions.

Examples

  • Database transaction

When should you use it?

  • When it matters that an inconsistent state occurs

Problems

  • A transaction may lock tables. A transaction that takes a long time may lead to other threads having to wait

How does it work?

Groups multiple operations into a single atomic unit that is applied entirely or not at all and preserves integrity via ACID properties.

  1. Wikipedia on database transaction
  2. Martin Fowler on unit of work