Repository

Repository

A repository is a collection-like interface for retrieving and persisting aggregates. The domain talks to it as if it were an in-memory collection; the infrastructure layer implements the actual persistence.

Defining trait

Python shape

# Domain layer
from typing import Protocol

class OrderRepository(Protocol):
    async def find_by_id(self, order_id: UUID) -> Order | None: ...
    async def find_by_customer(self, customer_id: UUID) -> list[Order]: ...
    async def save(self, order: Order) -> None: ...
    async def delete(self, order_id: UUID) -> None: ...


# Infrastructure layer (SQLAlchemy example)
class SqlOrderRepository:
    def __init__(self, session: AsyncSession):
        self._session = session

    async def find_by_id(self, order_id: UUID) -> Order | None:
        row = await self._session.execute(...)
        return _to_order(row) if row else None

    async def save(self, order: Order) -> None:
        # upsert order + items
        ...

The use case takes OrderRepository, never SqlOrderRepository — Dependency Inversion.

What lives where

Concern Layer
OrderRepository Protocol Domain
SqlOrderRepository, MongoOrderRepository, InMemoryOrderRepository Infrastructure
SQL queries, ORM mapping Infrastructure
Aggregate logic Domain
Repository injection wiring Composition root

Anti-patterns

A repository is not a query service

For read models (reports, dashboards, search), use separate read-side query services that bypass the repository and hit the DB directly. Repositories are for transactional writes of aggregates. CQRS makes this split explicit.

Useful methods

Testing

Provide an in-memory implementation (a dict keyed by ID) for unit tests. Run the same contract test suite against both real and in-memory impls — that's how you prove they're interchangeable.