Skip to content
IT glossary
ArchitectureUpdated December 3, 2026

Repository pattern

Репозиторий

This design pattern lets application code find and save business objects through a small set of methods without knowing how the underlying data is stored.

What is the Repository pattern?

Imagine the code for cancelling an order. It needs to retrieve the order, ask it to cancel, and keep the result. It doesn't need to know which tables contain the order or how its line items are joined. A repository is the boundary that makes that distinction possible. It presents stored business objects much like a collection, even when finding one object requires a database query. This is unrelated to a Git repository.

What belongs behind the boundary?

Application code calls methods such as findById or save. The repository implementation issues queries, often through an ORM, and maps the results to domain objects if the storage and domain models differ. Choose methods based on what the application needs, not on every operation the database supports. In domain-driven design, repositories typically work with aggregate roots: for example, you load an Order and change its line items through the order rather than saving each line item through a separate repository.

Example: cancelling an order

interface OrderRepository {
  findById(id: string): Promise<Order | null>;
  save(order: Order): Promise<void>;
}

async function cancelOrder(id: string, orders: OrderRepository) {
  const order = await orders.findById(id);
  if (!order) throw new OrderNotFound(id);
  order.cancel();
  await orders.save(order);
}

The Order enforces the cancellation rules, such as rejecting cancellation after shipment. The repository handles persistence. Passing it in lets a unit test run the use case with an in-memory implementation. Use integration tests to verify the actual queries, mappings, and database constraints; the in-memory version won't catch those failures.

When is it worth adding?

A repository earns its keep when it gives business code a stable interface and keeps storage details in one place. If a small CRUD application already uses its ORM cleanly, an extra class that simply forwards each call may not help. Returning the ORM's query builder is another common mistake: callers still have to know how to construct storage-specific queries. A report that needs totals and a few columns can often use a dedicated read query rather than loading whole domain objects.

What comes up in interviews?

Be ready to distinguish a repository from an ORM: the repository defines the application's data access contract, while the ORM is one way to implement it. A useful follow-up is: “What if cancelling an order must also release reserved stock?” If both writes must succeed or fail together, don't have each repository commit independently. Define one transaction around the use case; a Unit of Work can coordinate the changes and commit them together.