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
- One repository per aggregate root — not per table, not per entity.
- Returns aggregate objects, not rows or DTOs.
- Hides all persistence concerns — SQL, ORM, JOINs, indexes.
- The domain depends on a protocol; infrastructure provides the implementation.
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
- Returning rows or DTOs.
find_by_idreturns{"id": ..., "items": [...]}. The caller has to rebuild the aggregate. Repository's job is to return a usable aggregate. - Generic Repository. One class for all entities. Fine for CRUD; loses everything DDD-specific. Each aggregate has different querying needs.
- Query-leaking. Methods like
find_where(sql_clause). The domain now knows about SQL. - Partial loading from outside.
find_by_id_without_items(). Either load the aggregate or don't. - Repository per entity (not per aggregate root).
OrderItemRepository. The aggregate root owns its internals.
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
find_by_id(id) -> Aggregate | None— primary lookup.save(aggregate) -> None— upsert (insert or update).delete(id) -> None— remove.- A handful of domain-meaningful lookups:
find_by_customer(...),find_overdue(...). Not generic filters.
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.