Repository Pattern
A collection-like interface between the domain and the data store. Know where the interface lives, why that direction matters, and how it makes services testable without a database.
Overview
A Repository is an object that behaves like an in-memory collection of domain objects while actually talking to a database. The service code says accounts.get(id), accounts.add(account) or accounts.find_overdrawn(), and never writes SQL, never opens a connection, and never knows which database is behind the call.
The pattern is in Martin Fowler's *Patterns of Enterprise Application Architecture* (2003), where the Repository chapter was written by Edward Hieatt and Rob Mee. Their definition is short: a Repository mediates between the domain and the data mapping layers using a collection-like interface for accessing domain objects. Two words carry the meaning. 'Mediates' means it sits between two layers and each side sees only it. 'Collection-like' means the interface is add, remove, get and find, not insert, update, select and join.
Interviewers use the pattern to check three things: whether you put the interface in the domain layer and the implementation in the infrastructure layer (that is the Dependency Inversion Principle in action), whether you can test a service with an in-memory repository, and whether you know where the pattern stops (no business rules inside, no leaking of the ORM out).
Where it sits
The repository sits on a layer boundary. Three layers take part, and each one knows about a different amount of the system.
- Domain: holds Account, TransferService and the AccountRepository interface. It knows about nothing outside itself.
- Infrastructure: holds PostgresAccountRepository. It knows about the domain (it imports Account) and about the database driver.
- Tests: hold InMemoryAccountRepository, which knows only about the domain.
The arrows point inward. The infrastructure imports the domain; the domain imports nothing. That is what lets the domain be compiled and tested alone.
Interview questions
- How does a Repository differ from a DAO?
- Which layer owns the repository interface, and why is that the Dependency Inversion Principle?
- When do you use a generic repository, and when a specific one?
- How would you test a service that depends on a repository?
- What is the Unit of Work pattern, and how does it relate to a repository?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio