Skip to content
Back to blog
Design Patterns

Unit of Work: Coordinating Data Changes

Updated 17 min read

The Unit of Work Pattern helps coordinate multiple persistence operations as one business transaction. Explore a practical TypeScript example, learn how it works with repositories, and understand the limits of rollback, transaction boundaries, retries, and distributed systems.

Table of Contents

Introduction

A business operation rarely consists of a single database write.

Creating an order may require inserting an order record, creating its line items, reserving inventory, and recording a payment attempt. Transferring money between accounts requires updating two balances while preserving the invariant that the total amount transferred is consistent.

If one write succeeds and a later write fails, the application may be left with inconsistent data.

Database transactions solve this problem by allowing multiple operations to commit or roll back together. The Unit of Work Pattern helps organize those operations around a single business transaction.

The pattern is particularly relevant when an application already uses repositories. A repository can provide access to a particular type of data, but it does not automatically coordinate changes across several repositories.

This leads to an important design question:

How can an application make several related persistence operations behave as one coherent unit?

The Unit of Work Pattern provides one possible answer. Understanding it requires distinguishing the business operation, the transaction boundary, and the persistence mechanisms that implement it.

1. The Problem: A Business Operation Spans Multiple Writes

Consider an application that transfers money between two accounts.

The operation must:

  1. Load the source and destination accounts.
  2. Verify that the source account has sufficient funds.
  3. Debit the source account.
  4. Credit the destination account.
  5. Persist both changes.

A naive implementation might look like this:

typescript
class TransferService {
  constructor(
    private readonly accounts: AccountRepository,
  ) {}

  async transfer(
    fromId: string,
    toId: string,
    amount: number,
  ): Promise<void> {
    const source =
      await this.accounts.findById(fromId);

    const destination =
      await this.accounts.findById(toId);

    if (!source || !destination) {
      throw new Error("Account not found");
    }

    if (source.balance < amount) {
      throw new Error("Insufficient funds");
    }

    source.balance -= amount;
    await this.accounts.save(source);

    destination.balance += amount;
    await this.accounts.save(destination);
  }
}

The problem is the order of the writes.

Suppose the source account is updated successfully, but the destination update fails because the database connection is interrupted.

The source account has lost money, but the destination account has not received it.

The business operation has only partially succeeded.

This is not merely a code-organization problem. It is a correctness problem.

Why separate repository methods are insufficient

Each repository method might execute its own database statement correctly. Nevertheless, the overall operation can still fail because the statements are not necessarily part of the same transaction.

The application needs a mechanism to define the scope of atomicity:

  • Either both balance changes are committed.
  • Or neither balance change is committed.

A database transaction can provide this guarantee when both writes use the same transactional database connection and transaction.

The application must still decide where that transaction begins, which operations participate in it, and when it commits.

2. The Core Idea Behind the Unit of Work Pattern

A Unit of Work coordinates the changes that belong to one business operation and ensures they are committed through a defined persistence boundary.

Depending on the implementation, a Unit of Work may track modified objects, coordinate repository operations, manage a database transaction, or combine several of these responsibilities.

The essential idea is that related changes are treated as a single unit rather than as unrelated writes.

Conceptually:

flowchart TD
    S[TransferService] --> U[UnitOfWork]
    U --> AR[AccountRepository]
    U --> TR[TransactionRepository]
    AR --> TX
    TR --> TX
    subgraph TX[Database Transaction]
        D1[Debit source account]
        D2[Credit destination account]
        D3[Record transfer]
    end
    TX --> R{Commit or Rollback}

The application service expresses the business operation. The Unit of Work defines the transaction boundary and coordinates the persistence operations involved.

A simple implementation may delegate transaction handling directly to the database library. A more sophisticated implementation may also track changes and flush them together.

These are related designs, but not every Unit of Work needs a full object-tracking mechanism.

The important guarantee

A Unit of Work does not make arbitrary operations atomic automatically.

For a database transaction to protect the operation:

  • All relevant database writes must participate in the same transaction.
  • The transaction must be committed only after the required work succeeds.
  • Failures must cause the transaction to roll back.
  • Operations outside the transaction must not be mistaken for transactional writes.

This last point becomes important when the operation also sends emails, calls external APIs, or publishes messages.

3. Implementing Unit of Work in TypeScript

Let's implement the transfer example using a transaction boundary.

The following example uses a generic transaction interface so that the application-level design remains independent of a particular ORM.

The persistence adapter is responsible for connecting this interface to the database library.

3.1 Define the transaction-aware repositories

First, define the account model and repository contract.

typescript
interface Account {
  id: string;
  balance: number;
}

interface AccountRepository {
  findById(id: string): Promise<Account | null>;

  save(account: Account): Promise<void>;
}

The repository interface describes the operations needed by the application.

It does not expose a particular SQL query builder or database driver.

3.2 Define the Unit of Work contract

typescript
interface UnitOfWork {
  readonly accounts: AccountRepository;

  transaction<T>(
    work: () => Promise<T>,
  ): Promise<T>;
}

This interface exposes an account repository and a transaction operation.

However, this design has an important requirement: the repository instance used inside work() must participate in the transaction managed by the Unit of Work.

A repository that silently uses a separate database connection would violate that requirement.

The interface alone cannot enforce transactional correctness. The concrete implementation must do so.

3.3 Implement the application service

typescript
class TransferService {
  constructor(
    private readonly unitOfWork: UnitOfWork,
  ) {}

  async transfer(
    fromId: string,
    toId: string,
    amount: number,
  ): Promise<void> {
    if (!Number.isFinite(amount) || amount <= 0) {
      throw new Error("Invalid transfer amount");
    }

    if (fromId === toId) {
      throw new Error(
        "Source and destination must differ",
      );
    }

    await this.unitOfWork.transaction(
      async () => {
        const source =
          await this.unitOfWork.accounts.findById(
            fromId,
          );

        const destination =
          await this.unitOfWork.accounts.findById(
            toId,
          );

        if (!source || !destination) {
          throw new Error("Account not found");
        }

        if (source.balance < amount) {
          throw new Error("Insufficient funds");
        }

        source.balance -= amount;
        destination.balance += amount;

        await this.unitOfWork.accounts.save(source);
        await this.unitOfWork.accounts.save(
          destination,
        );
      },
    );
  }
}

The service describes the business operation and delegates transaction management to the Unit of Work.

If either save operation fails, the transaction implementation should roll back both changes.

The service does not need to manually reverse the first update when the second update fails.

That is one of the key benefits of a transaction boundary.

Important: this is a structural example, not a complete banking implementation. Real financial systems generally need integer minor units or suitable decimal arithmetic, database-level concurrency protection, ledger records, idempotency, authorization, and auditability.

3.4 Implement transaction handling with an ORM

A real implementation depends on the database library. Many ORMs expose a transaction callback that provides a transaction-scoped database client.

A simplified adapter might look like this:

typescript
interface TransactionClient {
  accounts: AccountRepository;
}

interface TransactionManager {
  run<T>(
    work: (
      client: TransactionClient,
    ) => Promise<T>,
  ): Promise<T>;
}

The Unit of Work can use that transaction manager to create repositories bound to the transaction-scoped client:

typescript
class DatabaseUnitOfWork
  implements UnitOfWork
{
  constructor(
    private readonly transactions:
      TransactionManager,
    private readonly client: TransactionClient,
  ) {}

  get accounts(): AccountRepository {
    return this.client.accounts;
  }

  async transaction<T>(
    work: () => Promise<T>,
  ): Promise<T> {
    return this.transactions.run(
      async (transactionClient) => {
        const scopedUnitOfWork =
          new DatabaseUnitOfWork(
            this.transactions,
            transactionClient,
          );

        return scopedUnitOfWork.runWork(work);
      },
    );
  }

  private async runWork<T>(
    work: () => Promise<T>,
  ): Promise<T> {
    return work();
  }
}

There is a subtle problem with this illustrative implementation: the service's repositories are resolved from the original Unit of Work, not from the scoped instance. Consequently, the service could still execute writes outside the transaction.

This demonstrates a common design trap: creating a transaction callback does not guarantee that dependencies automatically switch to the transaction-scoped connection.

A safer contract passes the scoped Unit of Work into the callback explicitly:

typescript
interface TransactionalUnitOfWork {
  readonly accounts: AccountRepository;
}

interface UnitOfWorkFactory {
  transaction<T>(
    work: (
      uow: TransactionalUnitOfWork,
    ) => Promise<T>,
  ): Promise<T>;
}

The service then receives the transactional repositories directly:

typescript
class SafeTransferService {
  constructor(
    private readonly unitOfWork:
      UnitOfWorkFactory,
  ) {}

  async transfer(
    fromId: string,
    toId: string,
    amount: number,
  ): Promise<void> {
    if (!Number.isFinite(amount) || amount <= 0) {
      throw new Error("Invalid transfer amount");
    }

    if (fromId === toId) {
      throw new Error(
        "Source and destination must differ",
      );
    }

    await this.unitOfWork.transaction(
      async (uow) => {
        const source =
          await uow.accounts.findById(fromId);

        const destination =
          await uow.accounts.findById(toId);

        if (!source || !destination) {
          throw new Error("Account not found");
        }

        if (source.balance < amount) {
          throw new Error("Insufficient funds");
        }

        source.balance -= amount;
        destination.balance += amount;

        await uow.accounts.save(source);
        await uow.accounts.save(destination);
      },
    );
  }
}

Now the transaction-scoped repository dependency is explicit.

A concrete adapter can implement UnitOfWorkFactory using the transaction callback provided by the selected ORM, constructing repositories with that callback's transaction client.

This is more verbose, but the contract makes an important invariant visible: all repository operations performed through the supplied Unit of Work belong to the same transaction.

4. Understanding Transaction Boundaries

A transaction boundary defines which operations must succeed or fail together.

Choosing the correct boundary is often more important than the exact class structure.

Too small: each repository manages its own transaction

Imagine this sequence:

sequenceDiagram
    participant App as Application
    participant DB as Database
    App->>DB: BEGIN
    App->>DB: Update source account
    App->>DB: COMMIT
    Note over App,DB: Source debit is now permanent
    App->>DB: BEGIN
    App->>DB: Update destination account
    App->>DB: COMMIT

If the second transaction fails, the first has already committed. The overall operation is not atomic.

Wrapping each repository method in a transaction does not solve a problem that requires a transaction across multiple repositories.

Appropriate: the business operation owns the transaction

For a simple transfer:

sequenceDiagram
    participant S as TransferService
    participant DB as Database
    S->>DB: BEGIN
    S->>DB: Read source and destination
    S->>S: Validate balances
    S->>DB: Update source
    S->>DB: Update destination
    S->>DB: Record transfer
    alt all steps succeed
        S->>DB: COMMIT
    else any step fails
        S->>DB: ROLLBACK
    end

If an operation fails before commit, the database rolls back the transaction.

The exact isolation level and locking strategy still determine what happens under concurrent requests.

Too broad: unrelated work is included in the transaction

Consider a transaction that remains open while the application:

  • Calls a slow external payment API.
  • Sends an email.
  • Waits for a third-party service.
  • Performs a long computation.

Long-running transactions can hold locks, consume database resources, increase contention, and reduce throughput.

A transaction should generally contain the database work that needs to be atomic—not every activity associated with the business operation.

This distinction is particularly important in high-throughput services.

Transaction ownership should be explicit

There are several possible ownership models:

  • An application service starts and commits the transaction.
  • A Unit of Work exposes a transaction callback.
  • A framework or request scope manages transaction lifetime.
  • A higher-level workflow coordinates several distinct transactions.

Each model can work. Problems arise when multiple layers independently start, commit, or roll back transactions without a clear ownership rule.

Choose one layer to define the transaction boundary for a given operation, and make nested transaction behavior explicit if it is supported.

5. Unit of Work and Repository: Different Responsibilities

The Repository Pattern and Unit of Work are often implemented together, but they solve different problems.

A repository encapsulates access to a particular collection of persisted entities or a set of meaningful data-access operations.

A Unit of Work coordinates changes across repositories and provides a transaction boundary.

For example:

flowchart TD
    OS[OrderService] --> U[UnitOfWork]
    U --> OR[OrderRepository]
    U --> IR[InventoryRepository]
    U --> PR[PaymentRepository]
    OR --> TX[(Database Transaction)]
    IR --> TX
    PR --> TX

A repository may know how to update an order. It does not necessarily know that the same business operation must also update inventory and record a payment.

The Unit of Work coordinates the participating repositories.

ResponsibilityRepositoryUnit of Work
Retrieve an entityYesUsually delegates
Express meaningful queriesYesNo
Encapsulate persistence detailsYesCoordinates adapters
Coordinate multiple repositoriesNot necessarilyYes
Define a transaction boundaryNot necessarilyOften
Guarantee atomicity by itselfNoOnly through a correctly implemented transaction

Not every application needs a custom Unit of Work abstraction. If the ORM already provides a clear transaction API, an application service may use that API directly.

A separate Unit of Work becomes useful when it creates a meaningful boundary, coordinates multiple repositories consistently, or keeps transaction management independent of a specific infrastructure library.

6. Handling Errors, Retries, and Concurrency

Transactions protect a group of database operations from partial commitment. They do not eliminate every failure mode.

6.1 Roll back on failure

The transaction implementation should commit only when the callback completes successfully and roll back when it fails.

The application should avoid swallowing an error inside the transaction callback if the operation must be rolled back.

For example, this is dangerous:

typescript
await unitOfWork.transaction(async (uow) => {
  await uow.accounts.save(source);

  try {
    await uow.accounts.save(destination);
  } catch {
    // The error is swallowed.
  }
});

If the transaction callback resolves successfully, the transaction manager may commit the changes, depending on the database adapter's behavior. The operation has hidden a failure that should have prevented commitment.

Handle errors deliberately, and allow failures that invalidate the transaction to propagate to the transaction manager.

6.2 Retrying a transaction safely

Some databases can abort a transaction because of serialization conflicts or deadlocks. Retrying the transaction may be appropriate for transient failures.

However, retrying is safe only when the operation has been designed for it.

The transaction callback should not send a customer email, charge an external payment provider, or perform another irreversible side effect on each attempt. The database might roll back even though the external action has already occurred.

A safer structure is:

  1. Execute the database transaction.
  2. Commit the database changes.
  3. Trigger external work through an appropriate post-commit mechanism.

For reliable event delivery, a transactional outbox can record an event in the same database transaction as the business changes. A separate worker publishes the event later.

6.3 Protect against concurrent updates

Suppose two requests transfer money from the same account at almost the same time.

Both transactions may read a balance of 100. Each attempts to transfer 80. If the implementation uses an unsafe read-modify-write sequence, both may believe sufficient funds are available.

The result can violate the business invariant.

Depending on the database and application, appropriate protections include:

  • Conditional updates that check the balance in the write operation.
  • Row-level locking.
  • Optimistic concurrency using a version column.
  • Suitable transaction isolation levels.
  • Database constraints where the invariant can be expressed safely.

For example, a conditional debit can require the balance to remain sufficient at update time:

sql
UPDATE accounts
SET balance = balance - :amount
WHERE id = :account_id
  AND balance >= :amount;

The application must verify that exactly one row was updated. Zero updated rows means the debit did not satisfy the condition.

This is an illustration of a database-level guard, not a complete transfer implementation. The destination credit and transfer record must still participate in the same transaction, with appropriate handling for failures and concurrent requests.

A Unit of Work coordinates writes. Database isolation, locking, and constraints protect invariants under concurrency. These responsibilities complement each other.

7. Database Transactions Are Not Distributed Transactions

A database transaction can coordinate operations within a supported transactional resource. It does not automatically make changes across unrelated services atomic.

Consider an order service that needs to:

  1. Create an order in PostgreSQL.
  2. Charge a payment provider.
  3. Reserve inventory in another service.
  4. Publish an order-created event.

A local database transaction cannot roll back a successful external payment or undo an inventory reservation in another service automatically.

This is a different class of problem.

Possible approaches include:

  • Transactional outbox: Persist the business change and an event record together, then publish the event asynchronously.
  • Saga: Coordinate a sequence of local transactions with compensating actions for failures.
  • Idempotent operations: Make retries safe when a request or message is delivered more than once.
  • Workflow orchestration: Track a long-running business process and its recovery behavior.

These approaches are not interchangeable, and none guarantees that every external action can be reversed perfectly.

For example, a refund is a compensating business operation, not a literal rollback of an already completed payment.

The right design depends on consistency requirements, failure modes, and the capabilities of each external system.

8. Common Unit of Work Mistakes

8.1 Assuming all repositories automatically share a transaction

A transaction-aware repository must use the transaction-scoped client or connection.

If one repository uses the transaction client while another uses a global database instance, the second repository may execute outside the intended transaction.

Make the transactional dependency explicit and test the adapter's behavior.

8.2 Treating the Unit of Work as a general-purpose service

A Unit of Work should not become the place for all business decisions, validation, and external API calls.

Its responsibility is to coordinate persistence changes and, where appropriate, transaction lifecycle.

Business rules belong in the domain or application layer that owns the operation.

8.3 Keeping transactions open too long

Long-running transactions can increase lock contention and degrade performance.

Perform non-transactional preparation before the transaction where safe, and move slow external actions outside the transaction whenever the consistency model permits it.

8.4 Assuming rollback reverses every side effect

Database rollback cannot unsend an email or reverse a third-party API call.

Distinguish database state from external effects, and design delivery, retries, and compensation explicitly.

8.5 Retrying operations without idempotency

A client may retry a request because it never received the response—even though the original transaction committed successfully.

Without idempotency or a reliable way to identify the original operation, a retry can perform the business operation twice.

This is particularly dangerous for transfers, payments, and order creation.

8.6 Building a custom framework too early

If the application performs one simple write per request, a custom Unit of Work abstraction may introduce more complexity than it removes.

Use the transaction API provided by your database library when it already expresses the required boundary clearly. Introduce an additional abstraction when repeated needs or architectural boundaries justify it.

9. When Should You Use the Unit of Work Pattern?

Consider a Unit of Work when:

  • A business operation modifies several entities or repositories.
  • Those modifications must commit or roll back together.
  • Transaction ownership is becoming scattered across the application.
  • Several services need a consistent way to obtain transaction-scoped repositories.
  • You need to isolate application logic from infrastructure-specific transaction APIs.

A custom abstraction may be unnecessary when:

  • Each operation performs one simple database write.
  • The ORM already provides a straightforward transaction callback.
  • There is no meaningful coordination across repositories.
  • The abstraction merely forwards transaction methods without simplifying the application.

Before implementing it, answer these questions:

  1. Which changes must be atomic?
  2. Which persistence operations participate in the same transaction?
  3. Which layer owns commit and rollback?
  4. How are concurrent requests prevented from violating business invariants?
  5. Which external effects must happen after commitment?
  6. How will retries avoid duplicating the operation?

These questions define the actual requirements. The Unit of Work Pattern is one way to organize the solution, not a substitute for answering them.

Summary

The Unit of Work Pattern coordinates persistence changes that belong to one business operation. When implemented around a correctly scoped database transaction, it allows multiple writes to commit or roll back together.

Repositories and Units of Work complement each other: repositories express data-access operations, while a Unit of Work coordinates changes across them and can provide a clear transaction boundary.

However, neither abstraction automatically solves concurrency, idempotency, distributed consistency, or external side-effect management. Those require additional design decisions based on the system's guarantees and failure modes.

Use the Unit of Work Pattern when it clarifies transaction ownership and makes coordinated changes safer to manage. Prefer a simpler transaction API when an additional abstraction adds no meaningful value.

A design pattern is useful when it captures a real invariant or responsibility. It becomes unnecessary complexity when it exists only to satisfy a diagram or convention.

  • Design Patterns
  • Repository Pattern
  • OOP
  • Programing
  • Software Architecture
  • Data Access Layer
  • Database Rollback
  • Database Transaction Management
  • Transaction Boundaries
Have a similar problem?

If something here resonates with a problem you're working on, let's talk.

Let's talk
Keep reading
Design Patterns · 17 min read

Repository Pattern: Abstraction or Unnecessary Layer?

The Repository Pattern can separate application logic from persistence, but it can also become an unnecessary wrapper around an ORM. Learn how to design meaningful repository contracts in TypeScript, test them effectively, and decide when direct database access is the simpler choice.

Design Patterns · 19 min read

When Design Patterns Become Anti-Patterns

Design patterns solve recurring software design problems, but applying them without a clear purpose can introduce unnecessary complexity. Learn how to recognize overengineering, evaluate abstractions, and choose designs that make software easier to understand, test, and change.

Design Patterns · 18 min read

State Pattern: Managing Complex State Transitions

The State Pattern helps manage complex state-dependent behavior without scattering conditional logic throughout your codebase. Learn how to implement it in TypeScript, model valid transitions, test lifecycle rules, and decide when a state machine or simpler approach is a better fit.