Repository Pattern

A Repository is an object that behaves like an in-memory collection of domain objects and is actually backed by storage. It is not one of the 23 GoF patterns – it comes from Domain-Driven Design, which is why its vocabulary is save and findByCode rather than insert and select. Callers ask domain-meaningful questions; where the answers live is the Repository’s problem and nobody else’s.

Why this matters: almost every machine-coding round starts the same way. You reach for a HashMap, get the happy path working, and the interviewer says “now make it durable”. If storage lives inside your service methods that means rewriting them; if it lives behind a four-method interface the answer is “I add a second implementation and change one line in main” – and that answer is the one being graded.


Prerequisites


The Problem: the URL shortener that knows SQL

The service holds a map, and two methods later it also holds a database connection, because the map could not answer a question someone asked:

public class UrlShortenerService {

    private final Map<String, ShortUrl> byCode = new HashMap<>();  // storage choice #1
    private final DataSource dataSource;                            // storage choice #2
    private final CodeGenerator codeGenerator = new Base62CodeGenerator();

    public String shorten(String longUrl) {
        String code = codeGenerator.next();
        byCode.put(code, new ShortUrl(code, longUrl, Instant.now()));
        return "https://sho.rt/" + code;
    }

    public String resolve(String code) {
        ShortUrl found = byCode.get(code);
        if (found == null) throw new UnknownCodeException(code);
        return found.getLongUrl();
    }

    // Two methods later, because a HashMap cannot answer this one after a restart.
    public String findExistingCode(String longUrl) throws SQLException {
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(
                 "SELECT code FROM short_url WHERE long_url = ? LIMIT 1")) {
            ps.setString(1, longUrl);
            ResultSet rs = ps.executeQuery();
            return rs.next() ? rs.getString("code") : null;
        }
    }
}

Two consequences, both concrete:

  1. The unit tests now need a database. findExistingCode cannot run without a live short_url table, and because it is the same class, the tests for resolve – which touch nothing but a map – are hostage to schema setup too. Candidates who write this usually ship no tests at all, because wiring a database into the harness costs more minutes than they have.
  2. Moving to Redis rewrites every method body. byCode.put, byCode.get and the SQL string are three storage calls in three methods, so switching stores edits all three – and the rules sitting next to them, the collision check and the UnknownCodeException, get rewritten as collateral damage.

Class Diagram

classDiagram
    class UrlShortenerService {
        -ShortUrlRepository repository
        +shorten(longUrl) String
        +resolve(code) String
    }
    class ShortUrlRepository {
        <<interface>>
        +save(shortUrl) ShortUrl
        +findByCode(code) Optional~ShortUrl~
        +findByLongUrl(longUrl) Optional~ShortUrl~
        +deleteByCode(code) boolean
    }
    class InMemoryShortUrlRepository {
        -ConcurrentHashMap byCode
        -ConcurrentHashMap codeByLongUrl
    }
    class JdbcShortUrlRepository {
        -DataSource dataSource
    }
    class ShortUrl {
        -String code
        -String longUrl
    }

    UrlShortenerService --> ShortUrlRepository
    ShortUrlRepository <|.. InMemoryShortUrlRepository
    ShortUrlRepository <|.. JdbcShortUrlRepository
    ShortUrlRepository ..> ShortUrl

The non-obvious part is which way the arrows point at the interface. ShortUrlRepository is not owned by the persistence layer and handed upward – it is declared next to ShortUrl, in the domain, and both implementations point at it from below. The domain states what it needs to ask; storage code complies.


Real-World Example: URL Shortener with Swappable Storage

One interface, two implementations. The second one is the proof that the first one bought you something.

// ShortUrl is an immutable record of code, longUrl and createdAt, with a
// newLink factory. It knows nothing about rows, columns or keys.

// The deliverable. Four domain questions, zero storage words.
public interface ShortUrlRepository {
    ShortUrl save(ShortUrl shortUrl);                  // insert or replace, keyed by code
    Optional<ShortUrl> findByCode(String code);
    Optional<ShortUrl> findByLongUrl(String longUrl);  // for dedupe on shorten
    boolean deleteByCode(String code);                 // true if something was removed
}

// What you actually write in the interview: no dependencies, runs anywhere.
public class InMemoryShortUrlRepository implements ShortUrlRepository {

    private final Map<String, ShortUrl> byCode = new ConcurrentHashMap<>();
    private final Map<String, String> codeByLongUrl = new ConcurrentHashMap<>();

    @Override
    public ShortUrl save(ShortUrl url) {
        byCode.put(url.code(), url);
        codeByLongUrl.put(url.longUrl(), url.code());  // the index is mine, not the caller's
        return url;
    }

    @Override
    public Optional<ShortUrl> findByCode(String code) {
        return Optional.ofNullable(byCode.get(code));
    }

    @Override
    public Optional<ShortUrl> findByLongUrl(String longUrl) {
        return Optional.ofNullable(codeByLongUrl.get(longUrl)).map(byCode::get);
    }

    @Override
    public boolean deleteByCode(String code) {
        ShortUrl removed = byCode.remove(code);
        if (removed == null) return false;
        codeByLongUrl.remove(removed.longUrl(), code);
        return true;
    }
}

// What you say you would write in production -- same four methods, different
// machine. Sketched here with two of them; the other two are noted at the end.
public class JdbcShortUrlRepository implements ShortUrlRepository {

    private static final String UPSERT =
        "INSERT INTO short_url (code, long_url, created_at) VALUES (?, ?, ?) "
      + "ON CONFLICT (code) DO NOTHING";
    private static final String BY_CODE =
        "SELECT code, long_url, created_at FROM short_url WHERE code = ?";

    private final DataSource dataSource;

    public JdbcShortUrlRepository(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public ShortUrl save(ShortUrl url) {
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(UPSERT)) {
            ps.setString(1, url.code());
            ps.setString(2, url.longUrl());
            ps.setTimestamp(3, Timestamp.from(url.createdAt()));
            ps.executeUpdate();
            return url;
        } catch (SQLException e) {
            throw new StorageException("save failed for code " + url.code(), e);
        }
    }

    /** The ResultSet dies here. Nothing above this class ever sees one. */
    @Override
    public Optional<ShortUrl> findByCode(String code) {
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(BY_CODE)) {
            ps.setString(1, code);
            try (ResultSet rs = ps.executeQuery()) {
                if (!rs.next()) return Optional.empty();
                return Optional.of(new ShortUrl(rs.getString("code"),
                        rs.getString("long_url"),
                        rs.getTimestamp("created_at").toInstant()));
            }
        } catch (SQLException e) {
            throw new StorageException("findByCode failed for " + code, e);
        }
    }
    // findByLongUrl is this shape against a unique index on long_url, and
    // deleteByCode is one DELETE. Neither needs a second map.
}

// The service. Read it looking for a storage verb -- there isn't one.
public class UrlShortenerService {
    private final ShortUrlRepository repository;
    private final CodeGenerator codeGenerator;

    public UrlShortenerService(ShortUrlRepository repository, CodeGenerator codes) {
        this.repository = repository;
        this.codeGenerator = codes;
    }

    public String shorten(String longUrl) {
        return repository.findByLongUrl(longUrl)
            .map(ShortUrl::code)                       // same URL in, same code out
            .orElseGet(() -> repository.save(
                ShortUrl.newLink(codeGenerator.next(), longUrl)).code());
    }

    public String resolve(String code) {
        return repository.findByCode(code)
            .map(ShortUrl::longUrl)
            .orElseThrow(() -> new UnknownCodeException(code));
    }
}

// Wiring. One line decides where the data lives.
var service = new UrlShortenerService(new InMemoryShortUrlRepository(),
                                      new Base62CodeGenerator());
// production: new JdbcShortUrlRepository(pool) -- nothing above this line changes
from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime
from threading import Lock
from typing import Optional

@dataclass(frozen=True)
class ShortUrl:
    code: str
    long_url: str
    created_at: datetime

class ShortUrlRepository(ABC):
    """Collection-shaped boundary. Four domain questions, no storage words."""

    @abstractmethod
    def save(self, short_url: ShortUrl) -> ShortUrl: ...
    @abstractmethod
    def find_by_code(self, code: str) -> Optional[ShortUrl]: ...
    @abstractmethod
    def find_by_long_url(self, long_url: str) -> Optional[ShortUrl]: ...
    @abstractmethod
    def delete_by_code(self, code: str) -> bool: ...

class InMemoryShortUrlRepository(ShortUrlRepository):
    def __init__(self) -> None:
        self._by_code: dict[str, ShortUrl] = {}
        self._code_by_long_url: dict[str, str] = {}
        self._lock = Lock()          # the two dicts have to move together

    def save(self, short_url: ShortUrl) -> ShortUrl:
        with self._lock:
            self._by_code[short_url.code] = short_url
            self._code_by_long_url[short_url.long_url] = short_url.code
            return short_url

    def find_by_code(self, code: str) -> Optional[ShortUrl]:
        with self._lock:
            return self._by_code.get(code)

    def find_by_long_url(self, long_url: str) -> Optional[ShortUrl]:
        with self._lock:
            code = self._code_by_long_url.get(long_url)
            return self._by_code.get(code) if code is not None else None

    def delete_by_code(self, code: str) -> bool:
        with self._lock:
            removed = self._by_code.pop(code, None)
            if removed is None:
                return False
            self._code_by_long_url.pop(removed.long_url, None)
            return True
#include <cstdint>
#include <mutex>
#include <optional>
#include <string>
#include <unordered_map>

struct ShortUrl {
    std::string code;
    std::string longUrl;
    std::int64_t createdAtEpochSeconds = 0;
};

class ShortUrlRepository {
public:
    virtual ~ShortUrlRepository() = default;
    virtual ShortUrl save(const ShortUrl& shortUrl) = 0;
    virtual std::optional<ShortUrl> findByCode(const std::string& code) const = 0;
    virtual std::optional<ShortUrl> findByLongUrl(const std::string& longUrl) const = 0;
    virtual bool deleteByCode(const std::string& code) = 0;
};

class InMemoryShortUrlRepository : public ShortUrlRepository {
    std::unordered_map<std::string, ShortUrl> byCode_;
    std::unordered_map<std::string, std::string> codeByLongUrl_;
    mutable std::mutex mutex_;        // the two maps have to move together

public:
    ShortUrl save(const ShortUrl& url) override {
        std::lock_guard<std::mutex> guard(mutex_);
        byCode_[url.code] = url;
        codeByLongUrl_[url.longUrl] = url.code;
        return url;
    }

    std::optional<ShortUrl> findByCode(const std::string& code) const override {
        std::lock_guard<std::mutex> guard(mutex_);
        auto it = byCode_.find(code);
        if (it == byCode_.end()) return std::nullopt;
        return it->second;             // a copy, never a handle into the map
    }

    std::optional<ShortUrl> findByLongUrl(const std::string& longUrl) const override {
        std::lock_guard<std::mutex> guard(mutex_);
        auto indexed = codeByLongUrl_.find(longUrl);
        if (indexed == codeByLongUrl_.end()) return std::nullopt;
        auto it = byCode_.find(indexed->second);
        if (it == byCode_.end()) return std::nullopt;
        return it->second;
    }

    bool deleteByCode(const std::string& code) override {
        std::lock_guard<std::mutex> guard(mutex_);
        auto it = byCode_.find(code);
        if (it == byCode_.end()) return false;
        codeByLongUrl_.erase(it->second.longUrl);
        byCode_.erase(it);
        return true;
    }
};

The interface belongs to the domain, not to the database

findByCode is a question the domain wants to ask; executeQuery is a mechanism for answering it. The test for whether you wrote a Repository is to read the interface out loud: if the method names mention SQL, tables, columns or WHERE clauses – selectByCodeColumn, queryShortUrlTable, findWhere – the abstraction has leaked and you cannot write a second implementation, because the names only make sense for the first one.

The corollary is about return types, which is where leaks actually happen. A repository returns domain objects, or an Optional/List of them – never a ResultSet, never a cursor, never a DTO whose fields are the table’s columns. A ShortUrlRow holding a created_at string is the schema escaping under a different name.

💡 Aggregate = a cluster of domain objects loaded and saved as one unit, with one object as its entry point. One repository per aggregate, not one per table – an OrderRepository saves the order and its line items together.

Now the honest part, because a good interviewer pushes here: plenty of real queries do not fit the collection metaphor. “Top 50 codes by hit count last week” is not a question a collection answers, and neither is “page 4 of this user’s links sorted by date”. Forcing those in turns a four-method interface into a thirty-method one, so name both standard answers:

  • A dedicated read-side query object. ShortUrlReportQuery returns a purpose-built result type and may be as SQL-shaped as it likes, because it never pretended to be a collection. The repository keeps writes and by-identity reads.
  • Accept a Specification argument. One findAll(spec) where the spec is a composable, storage-agnostic predicate each implementation translates – a Stream.filter in memory, a WHERE fragment in JDBC.

Repository vs DAO vs Active Record vs Unit of Work

All four are “the class that talks to storage”, which is why they get mixed up. The difference is the shape each one mirrors:

Pattern Intent Shape it mirrors Tell
Repository Give the domain a collection it can ask questions of An aggregate Method names are domain questions – findByLongUrl
DAO Give one table a typed CRUD API A table One class per table, insertRow / selectAll
Active Record Put persistence on the entity itself A row order.save() – the object knows its own table
Unit of Work Batch several repositories’ writes into one commit A transaction It has commit() and rollback() and no finders

A repository over a single-table aggregate and a DAO for that table have nearly identical code; the split shows at the second aggregate, where the repository saves a parent and its children in one save and the DAO cannot, because a DAO’s unit is a table. Active Record is the opposite trade – fastest to write, and the entity now imports a database driver, so it cannot be unit-tested off the persistence path. Unit of Work composes with repositories rather than competing: MiniORM is exactly that, a change-tracking session over repositories that flushes every pending write in one commit.


When to Use vs When to Avoid

Use Repository When Avoid When
Storage might change – map now, Redis or SQL later The object is pure computation with no persistence
The service has rules worth testing without a database Your domain object is already a row and you accept that
One aggregate spans tables and must save atomically You need 20 analytical queries – use a query object
Several callers ask the same lookup question The ORM session is already your explicit boundary
You want one place for caching or retry around reads A single script does one query and exits

The characteristic failure mode is the generic repository: Repository<T, ID> with findAll(), findById(), save(), delete() and nothing else, inherited by everything and extended by nothing. Because the interface cannot express findByLongUrl, every real question gets answered up in the service as repository.findAll().stream().filter(u -> u.longUrl().equals(url)).findFirst(). In memory that is an O(n) scan where a map lookup was O(1); against a database findAll() is SELECT * FROM short_url, so you pull the whole table across the wire to find one row and the unique index on long_url never gets used. The fix is unglamorous: write the four or five methods your domain actually asks for, by hand, per aggregate.


Interview Questions

  1. “Isn’t this just an extra layer over the ORM? JPA already has EntityManager.” – EntityManager is a generic persistence API, so calling it directly puts JPQL strings in your service and the service stops being testable without a persistence unit. A repository names the queries the domain asks, which collects them in one file and makes them swappable for an in-memory version. Where the objection lands is Spring Data – the generated interface is the repository, so wrapping it in a second one is the over-engineering the question is hinting at.

  2. “One use case writes to two repositories. Where does the transaction live?” – Above both, in the service or application layer, never inside a repository: one that opens its own transaction per call makes atomicity across two of them impossible. Concretely that is a Unit of Work or a @Transactional method, with both repositories handed the same connection so one commit covers both writes. If the aggregates live in different stores and no commit can span them, stop pretending and reach for an outbox or a saga.

  3. “How do you support pagination and sorting without leaking SQL?” – Put both in the signature as domain-level parameters rather than a string the caller builds: findByOwner(ownerId, limit, afterCode) returns a page and lets each implementation pick keyset pagination, LIMIT/OFFSET, or a sublist. For order, pass an enum the domain owns (SortBy.CREATED_DESC), never a column name – once "created_at DESC" crosses the interface you have a SQL fragment in your service and an injection surface with it.

  4. “Do you even need a repository in a 90-minute machine-coding round?” – You need the interface; you do not need the second implementation. The interface costs one line per method and it is what lets you answer “now make it durable” with “I add JdbcShortUrlRepository and nothing else changes” instead of editing five method bodies live. Writing that JDBC code is the wrong use of the remaining minutes – say you would, describe the upsert, and spend the time on concurrency or the demo.

  5. “Your in-memory repository passes every test. What did those tests prove about production?” – That the service logic is right, which is most of the grade but not all of it. The mechanism that closes the gap is a contract test: one abstract test class asserting repository behaviour – save then findByCode returns it, deleteByCode on a missing code returns false – run twice, once per implementation. It is also why a fake beats a mock here: mocks assert on calls, a fake asserts on behaviour.


See It in Action

  • URL Shortener – the in-memory map you write and the JDBC version you describe
  • Inventory Management – one repository per aggregate, so stock and its reservations save together
  • Restaurant Booking – availability queries that outgrow the collection metaphor
  • MiniORM – Unit of Work and change tracking built on top of repositories