Skip to content
Back to blog
Design Patterns

Repository Pattern: Abstraction or Unnecessary Layer?

Updated 17 min read

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.

Table of Contents

Introduction

The Repository Pattern is one of the most frequently discussed patterns in backend architecture.

Some developers consider it essential for maintaining a clean separation between business logic and data access. Others argue that it introduces unnecessary interfaces, classes, and indirection—especially when an ORM already provides a convenient abstraction over the database.

Both perspectives can be correct.

A repository can protect the domain from persistence details, centralize meaningful data-access operations, and provide a stable boundary around complex queries. It can also become a thin wrapper around an ORM, forcing developers to maintain extra code without gaining meaningful flexibility or clarity.

The important question is not whether repositories are good or bad.

It is which responsibility needs to be separated, and whether a repository is the simplest abstraction that accomplishes that separation.

This article explores the problem through a practical TypeScript example, examines the trade-offs, and identifies when a repository adds real architectural value.

1. The Problem: Persistence Logic Spreads Across the Application

Imagine a system that manages users.

A service needs to retrieve a user, check whether the user exists, update the user's profile, and save the changes.

Without a dedicated data-access boundary, the service might interact directly with an ORM:

typescript
import { db } from "./database";
import { users } from "./schema";
import { eq } from "drizzle-orm";

class UserService {
  async getUser(id: string) {
    const user = await db.query.users.findFirst({
      where: eq(users.id, id),
    });

    if (!user) {
      throw new Error("User not found");
    }

    return user;
  }

  async updateEmail(
    id: string,
    email: string,
  ) {
    const user = await db.query.users.findFirst({
      where: eq(users.id, id),
    });

    if (!user) {
      throw new Error("User not found");
    }

    await db
      .update(users)
      .set({ email })
      .where(eq(users.id, id));
  }
}

This code is not inherently wrong. For a small application, direct ORM access may be the most straightforward solution.

However, as the application grows, several concerns can become mixed together:

  • Business operations and persistence details appear in the same service.
  • Similar queries are repeated across multiple services.
  • Database-specific result types leak into application logic.
  • Complex query rules become difficult to locate.
  • Tests become coupled to ORM behavior or database setup.
  • Changes to persistence can require edits across multiple parts of the application.

The problem becomes more significant when business rules depend on specific data-access semantics.

For example, consider the difference between these two operations:

typescript
findById(id: string): Promise<User | null>;
typescript
findActiveAccountByEmail(
  email: string,
): Promise<User | null>;

The first operation is a generic lookup. The second expresses a meaningful application query: find an active account by email.

If the second query is used throughout the application, centralizing it can prevent different services from implementing subtly different definitions of an active account.

The architectural problem is not direct database access itself. It is the absence of a useful boundary when persistence rules and application behavior become difficult to maintain independently.

2. The Core Idea Behind the Repository Pattern

A repository provides an interface through which application or domain code accesses persisted objects without needing to know the details of how they are stored.

Instead of exposing SQL, table schemas, or ORM-specific query builders, a repository exposes operations expressed in terms of the application's needs.

For example:

typescript
interface UserRepository {
  findById(id: string): Promise<User | null>;

  findActiveByEmail(
    email: string,
  ): Promise<User | null>;

  save(user: User): Promise<void>;
}

The application depends on this contract rather than a particular database implementation.

A concrete implementation can use PostgreSQL, SQLite, or another persistence mechanism, provided it preserves the contract's behavior.

Conceptually:

flowchart TD
    S[UserService] -->|depends on| I[["UserRepository (interface)"]]
    P[PostgresUserRepository] -.->|implements| I
    P -->|queries| DB[(PostgreSQL)]

The interface defines what the application needs. The implementation determines how that need is fulfilled.

This creates a boundary between two concerns:

  • Application and domain behavior: What the system needs to do with users.
  • Persistence: How users are stored, queried, and updated.

The Repository Pattern is especially useful when this boundary represents meaningful domain concepts rather than merely hiding individual SQL statements.

A repository is not simply a class containing database queries

A class named UserRepository does not automatically create a good abstraction.

Consider:

typescript
class UserRepository {
  findById(id: string) {
    return db.query.users.findFirst({
      where: eq(users.id, id),
    });
  }
}

This may be a useful organizational choice. But if the class simply forwards every ORM method without establishing a meaningful boundary, its architectural value may be limited.

The value comes from the contract, its semantics, and the dependency direction—not from the class name.

3. Implementing a Repository in TypeScript

Let's build a small example that separates application behavior from persistence.

The implementation uses a user entity, a repository interface, a service, and a PostgreSQL-backed adapter.

3.1 Define the application model

First, define the shape of the user that the application needs.

typescript
interface User {
  id: string;
  email: string;
  name: string;
  active: boolean;
}

In a domain-rich application, this might instead be a class containing business invariants and behavior. For a simple example, an interface is sufficient.

The important decision is whether this model is independent of ORM-specific types.

If every service requires a database-generated row type containing internal columns, query metadata, and persistence-specific representations, the boundary may not be achieving much.

3.2 Define the repository contract

Next, define the operations the application requires.

typescript
interface UserRepository {
  findById(id: string): Promise<User | null>;

  findActiveByEmail(
    email: string,
  ): Promise<User | null>;

  save(user: User): Promise<void>;
}

Notice what is absent:

  • No SQL statements.
  • No database connection.
  • No ORM query builder.
  • No table names.
  • No driver-specific result objects.

The contract describes the application's needs without committing to a particular persistence technology.

The method names also express semantics. findActiveByEmail() communicates more intent than requiring every caller to reconstruct the filtering logic independently.

3.3 Implement the repository

The following example uses a Drizzle-style database API. The table schema and database instance are assumed to be defined elsewhere.

typescript
import { eq, and } from "drizzle-orm";
import { db } from "./database";
import { users } from "./schema";

class PostgresUserRepository
  implements UserRepository
{
  async findById(
    id: string,
  ): Promise<User | null> {
    const row = await db.query.users.findFirst({
      where: eq(users.id, id),
    });

    if (!row) {
      return null;
    }

    return {
      id: row.id,
      email: row.email,
      name: row.name,
      active: row.active,
    };
  }

  async findActiveByEmail(
    email: string,
  ): Promise<User | null> {
    const row = await db.query.users.findFirst({
      where: and(
        eq(users.email, email),
        eq(users.active, true),
      ),
    });

    if (!row) {
      return null;
    }

    return {
      id: row.id,
      email: row.email,
      name: row.name,
      active: row.active,
    };
  }

  async save(user: User): Promise<void> {
    await db
      .update(users)
      .set({
        email: user.email,
        name: user.name,
        active: user.active,
      })
      .where(eq(users.id, user.id));
  }
}

This implementation does two useful things.

First, it keeps database-specific query construction inside the persistence adapter.

Second, it explicitly maps database rows to the application model instead of exposing the raw database representation.

That mapping is not always necessary. If the ORM's types are already appropriate for the application's boundary, additional mapping may create boilerplate without meaningful benefit.

Also note that the example's save() updates an existing record; it does not implement an insert-or-update operation. Repository contracts should make such semantics explicit rather than using ambiguous names.

3.4 Use the repository from a service

The application service now depends on the interface:

typescript
class UserService {
  constructor(
    private readonly users: UserRepository,
  ) {}

  async getUser(id: string): Promise<User> {
    const user = await this.users.findById(id);

    if (!user) {
      throw new Error("User not found");
    }

    return user;
  }

  async changeEmail(
    id: string,
    email: string,
  ): Promise<void> {
    const user = await this.users.findById(id);

    if (!user) {
      throw new Error("User not found");
    }

    const updatedUser: User = {
      ...user,
      email,
    };

    await this.users.save(updatedUser);
  }
}

The service does not know how the user is queried or updated. It depends on the repository contract.

This makes the service easier to test without requiring a real database for every unit test.

However, the repository does not eliminate all persistence-related concerns. If changing an email requires uniqueness checks, normalization, audit records, or transactional updates, those requirements must still be designed explicitly.

3.5 Compose the application

At the application's composition boundary, provide the concrete implementation:

typescript
const userRepository =
  new PostgresUserRepository();

const userService =
  new UserService(userRepository);

This is a small example of dependency inversion in practice: the service depends on an abstraction, while the application setup chooses the concrete adapter.

You do not need a dependency injection container to achieve this. Constructor injection and explicit composition are often enough.

4. Where Should the Repository Boundary Live?

One of the most important repository design decisions is deciding which layer owns the interface.

There is no universal rule that every repository interface must live in a specific directory. Its location should reflect the architectural boundary it protects.

Option A: Put the interface beside the implementation

A small application might use this structure:

text
src/
  users/
    user.service.ts
    user.repository.ts
    postgres-user.repository.ts

This is straightforward and can be entirely appropriate when the application has limited architectural complexity.

The downside is that the application-facing contract and persistence implementation are colocated, which may make dependency direction less obvious in larger systems.

Option B: Put the interface in the application or domain layer

A more explicitly layered structure might look like this:

text
src/
  domain/
    users/
      user.ts

  application/
    users/
      user.repository.ts
      user.service.ts

  infrastructure/
    persistence/
      postgres-user.repository.ts

Here, the application defines the operations it requires, and infrastructure implements them.

This arrangement is useful when the application must remain independent of persistence technology or when multiple adapters are genuinely valuable.

The exact folder names are less important than the dependency rule:

The application should not need to import the concrete database implementation merely to perform its business operations.

Should every repository expose CRUD methods?

Not necessarily.

A generic CRUD interface might look like this:

typescript
interface Repository<T, ID> {
  findById(id: ID): Promise<T | null>;
  findAll(): Promise<T[]>;
  create(entity: T): Promise<void>;
  update(entity: T): Promise<void>;
  delete(id: ID): Promise<void>;
}

This can work for simple entities with similar persistence needs.

But business domains often have different requirements. A payment repository may need operations such as findPendingPaymentsForReconciliation(), while an order repository may need findOrdersReadyForFulfillment().

Forcing both into the same generic interface can hide useful domain semantics or introduce methods that some implementations cannot support meaningfully.

Prefer the smallest contract that expresses the operations the application actually needs.

5. Repository Pattern and Testing

One commonly cited benefit of repositories is that they make testing easier. This is true, but it is important to understand exactly what becomes easier and what does not.

5.1 Unit-test the service with a fake repository

A service can be tested with a small in-memory implementation:

typescript
class InMemoryUserRepository
  implements UserRepository
{
  private readonly users = new Map<
    string,
    User
  >();

  async findById(
    id: string,
  ): Promise<User | null> {
    return this.users.get(id) ?? null;
  }

  async findActiveByEmail(
    email: string,
  ): Promise<User | null> {
    for (const user of this.users.values()) {
      if (
        user.email === email &&
        user.active
      ) {
        return user;
      }
    }

    return null;
  }

  async save(user: User): Promise<void> {
    this.users.set(user.id, user);
  }
}

A test can then verify the service's behavior without connecting to a database:

typescript
import {
  describe,
  expect,
  it,
} from "vitest";

describe("UserService", () => {
  it("changes a user's email", async () => {
    const repository =
      new InMemoryUserRepository();

    await repository.save({
      id: "user-1",
      email: "[email protected]",
      name: "Alex",
      active: true,
    });

    const service =
      new UserService(repository);

    await service.changeEmail(
      "user-1",
      "[email protected]",
    );

    const user = await service.getUser("user-1");

    expect(user.email).toBe(
      "[email protected]",
    );
  });
});

The service test focuses on application behavior rather than SQL execution.

5.2 A fake repository is not proof that database behavior is correct

The in-memory implementation does not automatically reproduce the behavior of PostgreSQL.

It may differ in:

  • Unique constraints.
  • Transaction isolation.
  • Case sensitivity and collation.
  • Null handling.
  • Query ordering.
  • Locking and concurrent updates.
  • Database-specific errors.

Therefore, repository abstractions should not be used as a reason to skip integration tests.

A sensible testing strategy separates concerns:

  • Service unit tests: Verify business and application behavior using a fake or mock.
  • Repository integration tests: Verify queries, mapping, constraints, and persistence semantics against a real or appropriately isolated database.
  • End-to-end tests: Verify important workflows across the actual application boundaries.

If the repository contains complex query logic, integration tests become particularly important.

5.3 Do you need an interface just to mock the database?

No.

TypeScript allows many concrete classes to be tested with injected dependencies, and modern testing tools can mock modules or functions directly.

An interface is valuable when it represents a meaningful contract, not merely because a testing framework needs something to mock.

If a repository interface exists only to make one trivial method mockable, consider whether the abstraction is worth maintaining.

6. Repository vs. DAO, ORM, and Unit of Work

These concepts are related, but they solve different problems.

Repository vs. Data Access Object (DAO)

A DAO typically provides a data-access-oriented interface for interacting with a persistence mechanism.

A repository often presents a collection-like or domain-oriented interface to application code.

The distinction is not absolute. In real codebases, the terms sometimes overlap. What matters more than the name is whether the interface exposes low-level persistence operations or application-relevant concepts.

Repository vs. ORM

An ORM maps between application objects and relational data, and often provides query construction, persistence operations, and relationship management.

A repository can sit above an ORM to establish an application-facing boundary.

You do not automatically need both. If the ORM already provides the abstraction your application needs and its types do not cause meaningful coupling, using it directly may be the better design.

Repository vs. Unit of Work

A repository answers questions such as:

  • How do I retrieve this entity?
  • How do I save it?
  • Which query represents this domain operation?

A Unit of Work addresses a different concern: coordinating changes so they can be committed as a unit.

For example, an operation may need to update an order, record a payment, and decrement inventory within one database transaction.

A repository alone does not guarantee that these changes are atomic.

The application may need a transaction boundary or Unit of Work abstraction that coordinates the repositories involved.

ConceptPrimary responsibility
ORMObject-relational mapping and persistence facilities
DAOData-access operations
RepositoryApplication- or domain-oriented persistence boundary
Unit of WorkCoordinating changes within a transaction

These abstractions can coexist, but each should have a clear responsibility. Adding all of them by default creates complexity rather than automatically improving the architecture.

7. When a Repository Becomes an Unnecessary Abstraction

Consider a repository that exposes the ORM almost unchanged:

typescript
class UserRepository {
  findMany() {
    return db.query.users.findMany();
  }

  findFirst() {
    return db.query.users.findFirst();
  }

  insert(values: typeof users.$inferInsert) {
    return db.insert(users).values(values);
  }

  update(
    values: Partial<typeof users.$inferInsert>,
  ) {
    return db.update(users).set(values);
  }
}

This wrapper may be useful if it centralizes shared query policies, access restrictions, or instrumentation. But if it simply renames ORM methods, it may not create a meaningful architectural boundary.

The application may still depend on ORM-specific types. Query semantics remain tied to the underlying library. Replacing the ORM would still require changes across much of the application.

The additional layer may therefore introduce:

  • More files and interfaces to maintain.
  • Extra indirection when tracing a query.
  • Duplicate method definitions.
  • More boilerplate during schema changes.
  • A false sense that persistence is fully abstracted.

A practical decision framework

Before adding a repository, ask:

1. Does it hide something that should not leak into the caller?

If the service needs to know about table names, query builders, database-specific result types, or complicated persistence details, a repository may provide a useful boundary.

2. Does it express meaningful operations?

Methods such as findActiveByEmail() or findOrdersReadyForFulfillment() can capture shared semantics and prevent duplicated query rules.

3. Does it centralize behavior that must remain consistent?

Tenant filtering, soft-delete policies, common query constraints, or domain-specific persistence mapping may justify a repository, provided those concerns belong at that boundary.

4. Would removing the repository simplify the system without increasing coupling?

If the repository adds no useful contract and the application is small, direct ORM usage may be clearer.

5. Is the abstraction designed around real requirements or hypothetical future changes?

The possibility that the system might someday switch databases is not, by itself, sufficient justification for an additional layer. Consider the likelihood and cost of that change alongside the current maintenance cost.

The objective is not to maximize abstraction. It is to minimize the total complexity of the system.

8. Common Repository Design Mistakes

8.1 Returning database-specific types from the interface

If a repository interface exposes ORM query builders, database transaction objects, or driver-specific result types throughout the application, the boundary may be leaking implementation details.

Sometimes exposing those types is a deliberate and reasonable choice. But do not claim that the repository decouples persistence if callers remain tightly coupled to the persistence library.

8.2 Creating a generic repository that cannot express domain queries

A universal CRUD interface can make simple operations consistent, but it may be awkward for complex domains.

Avoid forcing every query into generic methods when a named operation would communicate intent more clearly.

8.3 Putting business workflows inside the repository

A repository should primarily handle persistence operations.

For example, a method called approveAndNotifyCustomer() may be doing too much if it combines domain decisions, database writes, and email delivery.

Those responsibilities may belong in an application service or domain operation that coordinates the repository with other collaborators.

The correct boundary depends on the domain model, but the repository should not become a general-purpose service layer.

8.4 Treating repository methods as transaction boundaries

A method named save() does not imply that an entire business workflow is atomic.

If multiple operations must succeed or fail together, make the transaction boundary explicit and ensure all relevant writes participate in the same transaction.

8.5 Assuming a repository makes the database replaceable for free

A well-designed interface can reduce coupling, but different databases may have different capabilities and semantics.

Queries involving full-text search, locking, isolation, JSON operators, or specialized indexes may not translate cleanly between persistence technologies.

Abstraction can reduce the cost of change; it cannot eliminate fundamental differences between systems.

9. When Should You Use the Repository Pattern?

The Repository Pattern is particularly useful when:

  • The application has meaningful domain or application boundaries.
  • Persistence logic is duplicated or increasingly complex.
  • You need stable, semantic operations rather than generic query access.
  • The domain model should remain independent of ORM-specific types.
  • Different persistence adapters are genuinely required.
  • You need to centralize persistence policies that must remain consistent.

Direct ORM access may be preferable when:

  • The application is small and its queries are straightforward.
  • The ORM already provides a clean, sufficient abstraction.
  • Repository methods would simply forward calls without adding semantics.
  • The cost of maintaining another layer exceeds the coupling it removes.

There is also a middle ground.

You can introduce repositories only for parts of the application where they provide real value. One module may use direct ORM access, while another uses a repository to protect a complex domain boundary.

Architectural consistency does not require every module to have identical layers regardless of its needs.

Use a repository when it makes the application easier to understand and change—not simply because the architecture diagram contains a repository box.

Summary

The Repository Pattern provides an abstraction over persistence, but the value of that abstraction depends on its contract and the coupling it removes.

A well-designed repository expresses meaningful application or domain operations, keeps persistence details behind a clear boundary, and helps maintain consistent query behavior.

A poorly designed repository merely forwards ORM methods, leaks persistence-specific types, and adds another layer developers must navigate.

The right choice depends on the application's size, domain complexity, testing needs, and expected evolution.

Do not introduce a repository solely to follow a conventional layered architecture. Start with the actual problem, identify the boundary that needs protection, and add the smallest abstraction that solves it.

The next question follows naturally: once an application needs to coordinate changes across multiple repositories, how should those changes be committed consistently? That is where the Unit of Work Pattern becomes relevant.

  • Design Patterns
  • Repository Pattern
  • OOP
  • Programing
  • Software Architecture
  • Data Access Layer
  • Clean Architecture
  • Repository vs ORM
  • Persistence Abstraction
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

Unit of Work: Coordinating Data Changes

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.

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.