📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do repositories and services fit into a DDD model? Explain why you have one repository per aggregate root, what makes a domain service different from an application service, and walk through a worked example such as transferring funds between two accounts.

Covers DDD repositories as collections of aggregates (one per root), domain services versus application services, and a worked funds-transfer example showing where each piece of logic lives.

Mid-Level Theory Intermediate application-service architecture domain-driven-design domain-service ef-core repository

🎯 Key points

  • Repository mediates between the domain and data mapping: collection-like access to whole aggregates, one per aggregate root, not per table
  • Interface lives in Domain/Application, implementation in Infrastructure (EF Core); manages aggregate lifecycle (add, load, remove)
  • Changing child entities directly is discouraged because it bypasses the root's invariants; no child-entity repositories, no IQueryable leak
  • Domain service: stateless domain logic spanning several aggregates or not owned by one (transfer, pricing); no infrastructure dependencies
  • Application service / command handler: orchestrates the use case (load, call domain, save, publish), owns the transaction and concurrency handling
  • One SaveChanges per use case; rowversion on each root; touching two aggregates in one transaction is a deliberate, documented exception
  • Across services or at scale, a domain process becomes eventually consistent: a Transfer aggregate plus a saga with compensation
  • Overusing domain services leads to an anaemic model: prefer methods on the aggregate first

⏱ 30-second answer

A DDD repository gives collection-like access to whole aggregates: GetAsync(id), Add(order). There is one per aggregate root, not per table, so there is no OrderLineRepository. Its interface sits with the domain or application layer; the EF Core implementation sits in infrastructure.

A domain service holds domain logic that does not belong to a single aggregate, like a funds transfer that applies rules to two accounts, or a pricing policy. It is stateless and free of infrastructure. An application service (or command handler) orchestrates a use case: load aggregates, call the domain, save, publish events, manage the transaction. It contains no business rules. The trade-off: domain services are useful, but reach for them only after asking whether the logic belongs on an aggregate, or the model turns anaemic.

🗣 Full answer (senior)

How I would answer this in an interview

"In DDD a repository pretends to be an in-memory collection of aggregates. You ask it for an Order by id and you get the whole aggregate, lines and all, ready to enforce its rules; you add a new Order to it; and the unit of work saves it. That is why there is one repository per aggregate root: there's no OrderLine repository, because nobody outside the Order should load or save lines on their own. The interface lives next to the domain, IOrderRepository with three or four methods, and the implementation in Infrastructure wraps EF Core. It doesn't expose IQueryable, because then every caller can write queries that ignore the aggregate.

Services come in two kinds and people mix them up. A domain service is part of the model: it holds a business rule that doesn't naturally belong to one entity. The classic example is a transfer between two accounts. Debiting one and crediting the other isn't the responsibility of either account alone, and there are rules about it: daily transfer limits, same currency, the source can't go below its overdraft. So a FundsTransferService.Transfer(from, to, amount) in the domain applies those rules by calling from.Withdraw and to.Deposit. It's stateless and has no idea a database exists.

The application service, or command handler, is the use case. It loads both accounts through the repository, calls the domain service, saves, and writes an integration event to the outbox. It owns the transaction and knows about the outside world, but it doesn't decide anything about money. The mistake I see is the opposite: every rule ends up in an AccountService and the entities become property bags. My order of preference is: method on the aggregate first, domain service when the logic truly spans aggregates, and the application service only coordinates."


Who does what

Piece Responsibility Depends on Example
Aggregate Its own invariants Nothing Account.Withdraw(amount)
Domain service Rules spanning aggregates or not owned by one Domain types only FundsTransferService.Transfer
Repository (interface) Load and save whole aggregates Domain types IAccountRepository.GetAsync
Repository (implementation) EF Core queries, Include EF Core EfAccountRepository
Application service / handler Orchestrate use case, transaction, events Repositories, domain, outbox TransferFundsHandler

Is it a domain service or an application service?

Question Domain service Application service
Would a domain expert recognise the logic? Yes No (it is plumbing)
Does it call a database, queue or HTTP? Never Yes, through abstractions
Is it named in the ubiquitous language? TransferFunds, PricingPolicy TransferFundsHandler
Does it own the transaction? No Yes

Production example

In a [savings product], transfer rules were duplicated in the mobile API, the internet-banking API and a scheduled-payments job, and two of them disagreed on the daily limit. Moving them into a FundsTransferService domain service called from three thin handlers removed the inconsistency and cut transfer-rule tests from [three suites to one] with [40] fast unit tests.

🔍 What the interviewer is checking

Checks that the candidate can place logic correctly between aggregates, domain services and application services, and understands what a DDD repository is for.

Green flags

  • One repository per aggregate root, aggregate-shaped methods
  • Clear distinction: domain service = rules, application service = orchestration
  • Prefers aggregate methods before domain services
  • Notes that read screens bypass repositories

Red flags

  • Generic repository over every table
  • Business rules inside handlers or controllers
  • Domain services that inject DbContext

📚 Learn in depth

1. Repository semantics

Application layer                      Infrastructure
-----------------                      --------------
IAccountRepository  ◄── implements ──  EfAccountRepository
  GetAsync(AccountId)                    db.Accounts.Include(a => a.Holds)
  Add(Account)                                     .SingleOrDefaultAsync(...)
  • Collection-oriented: Add, Get, Remove; saving happens through the unit of work (SaveChangesAsync) because EF Core tracks changes.
  • Aggregate-shaped: always loads the full aggregate the invariants need.
  • Few methods: query screens do not go through repositories; they use read models or direct projections.

2. Why not one per table

A repository per table lets code load an OrderLine and change it without the Order knowing, breaking the order's total. It also tempts generic IRepository<T> with GetAll() and Update(T), which duplicates what DbSet<T> already does.

3. Domain services

Signs that logic belongs in a domain service:

  • It needs two or more aggregates (Transfer(from, to)).
  • It is a policy or calculation the experts name (PremiumCalculator, ShippingCostPolicy).
  • Putting it on one entity would make that entity know about another.

Domain services are stateless. They can depend on domain abstractions (IExchangeRateProvider defined in the domain) but not on EF Core or HTTP.

4. The transfer flow

POST /transfers
  │
  ▼
TransferFundsHandler (application)
  ├─ from = accounts.GetAsync(fromId)
  ├─ to   = accounts.GetAsync(toId)
  ├─ result = transferService.Transfer(from, to, amount, today)   (domain)
  │     ├─ checks: same currency, daily limit
  │     ├─ from.Withdraw(amount)  ── checks overdraft
  │     └─ to.Deposit(amount)
  ├─ outbox.Add(new FundsTransferred(...))
  └─ SaveChangesAsync()   (one transaction: two account rows + outbox)

This touches two aggregates in one transaction: a deliberate exception to the usual rule, justified because money must not be created or destroyed. In a high-scale system you would instead model a Transfer aggregate and use a saga.

5. Where the interfaces live

In Clean Architecture the repository interfaces live in Application (or Domain); Infrastructure references both and implements them. DI wiring happens in the composition root (Program.cs).

Try it yourself

  1. Count the repositories in your codebase and compare with the number of aggregate roots.
  2. Find a service class with "Service" in its name and classify each method as domain logic or orchestration.
  3. Move one rule from a service into an entity method and write a unit test for it.
  4. Implement the transfer example and write a test for the daily limit with a fake TimeProvider.

💻 Code

Funds transfer: aggregate methods, a domain service, a repository and a thin handler.

namespace Banking.Domain;

public readonly record struct AccountId(Guid Value);
public sealed record Money(decimal Amount, string Currency);

public sealed class Account
{
    private Account() { }
    public Account(AccountId id, string currency, decimal overdraftLimit)
        => (Id, Currency, OverdraftLimit) = (id, currency, overdraftLimit);

    public AccountId Id { get; private set; }
    public string Currency { get; private set; } = "AUD";
    public decimal Balance { get; private set; }
    public decimal OverdraftLimit { get; private set; }
    public byte[] RowVersion { get; private set; } = [];

    public bool CanWithdraw(Money m) => m.Currency == Currency && Balance - m.Amount >= -OverdraftLimit;

    public void Withdraw(Money m)
    {
        if (!CanWithdraw(m)) throw new InvalidOperationException("Insufficient funds.");
        Balance -= m.Amount;
    }

    public void Deposit(Money m)
    {
        if (m.Currency != Currency) throw new InvalidOperationException("Currency mismatch.");
        Balance += m.Amount;
    }
}

// Domain service: a rule that spans two aggregates. No infrastructure.
public sealed class FundsTransferService
{
    public const decimal DailyLimit = 10_000m;

    public string? Transfer(Account from, Account to, Money amount, decimal alreadyTransferredToday)
    {
        if (from.Id == to.Id) return "transfer.same_account";
        if (from.Currency != to.Currency) return "transfer.currency_mismatch";
        if (alreadyTransferredToday + amount.Amount > DailyLimit) return "transfer.daily_limit";
        if (!from.CanWithdraw(amount)) return "transfer.insufficient_funds";

        from.Withdraw(amount);
        to.Deposit(amount);
        return null; // success
    }
}

// Repository: one per aggregate root, aggregate-shaped.
public interface IAccountRepository
{
    Task<Account?> GetAsync(AccountId id, CancellationToken ct);
    Task<decimal> TransferredTodayAsync(AccountId id, DateOnly day, CancellationToken ct);
    Task SaveChangesAsync(CancellationToken ct);
}
namespace Banking.Application;

using Banking.Domain;

public sealed record TransferFunds(Guid From, Guid To, decimal Amount, string Currency);

// Application service: orchestration only; no business rules.
public sealed class TransferFundsHandler(IAccountRepository accounts, FundsTransferService transfers, TimeProvider clock)
{
    public async Task<string?> HandleAsync(TransferFunds cmd, CancellationToken ct)
    {
        var from = await accounts.GetAsync(new AccountId(cmd.From), ct);
        var to = await accounts.GetAsync(new AccountId(cmd.To), ct);
        if (from is null || to is null) return "transfer.account_not_found";

        var today = DateOnly.FromDateTime(clock.GetUtcNow().UtcDateTime);
        var sent = await accounts.TransferredTodayAsync(from.Id, today, ct);

        var error = transfers.Transfer(from, to, new Money(cmd.Amount, cmd.Currency), sent);
        if (error is not null) return error;

        await accounts.SaveChangesAsync(ct); // both rows in one transaction; rowversion protects each
        return null;
    }
}
// Program.cs: composition root.
builder.Services.AddScoped<IAccountRepository, EfAccountRepository>();
builder.Services.AddSingleton<FundsTransferService>(); // stateless
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddScoped<TransferFundsHandler>();

⚠ Common mistakes

  • Mistake: A repository per table (OrderLineRepository). Why it is wrong: children can be changed without the root checking invariants. Instead: one repository per aggregate root; changes to children go through the root.
  • Mistake: Generic IRepository<T> with GetAll, Update and IQueryable. Why it is wrong: it duplicates DbSet<T>, leaks query logic everywhere and ignores aggregate boundaries. Instead: small, aggregate-specific interfaces.
  • Mistake: Business rules in the application service. Why it is wrong: the domain becomes anaemic and rules duplicate across use cases. Instead: rules on aggregates or in domain services; handlers orchestrate.
  • Mistake: Domain services that call the database. Why it is wrong: the domain gains infrastructure dependencies and becomes slow to test. Instead: the handler loads data and passes it in.
  • Mistake: A domain service for every operation. Why it is wrong: it drains behaviour from the aggregates. Instead: aggregate method first; domain service only for logic spanning aggregates or named policies.
  • Mistake: Loading full aggregates by default for list and search screens. Why it is wrong: a grid of 50 orders rarely needs every line, the change tracker and the invariants, so it costs joins and memory for nothing. Instead: use read-side projections with AsNoTracking().Select(...); load the aggregate when the screen actually runs a business operation or needs the rules (for example, showing which actions are allowed).
  • Mistake: Calling SaveChanges inside each repository method. Why it is wrong: a use case touching two aggregates commits twice and can leave half the change. Instead: save once per use case in the handler (unit of work).
  • Mistake: Ignoring concurrency in the transfer. Why it is wrong: two transfers from the same account read the same balance and both succeed, breaching the overdraft. Instead: a rowversion on each Account, catch DbUpdateConcurrencyException in the handler and retry the use case or return 409.
  • Mistake: Keeping the in-process two-aggregate transaction when accounts move to separate services or databases. Why it is wrong: there is no local transaction any more, and distributed transactions do not scale. Instead: model a Transfer aggregate and use a saga (debit, credit, compensate on failure) with an outbox, accepting eventual consistency.

🏛 Senior insight: trade-offs

Repositories in DDD are about protecting aggregate boundaries, not about hiding EF Core for its own sake. In a small service where the aggregates are simple, using DbContext directly in handlers is a legitimate choice; the boundary is then kept by convention and architecture tests. Domain services are a pressure valve: necessary sometimes, but a codebase full of them is usually an anaemic model in disguise.

Option When it fits Cost When not to
Aggregate repository interface Rich domain, several use cases per aggregate One small interface + implementation per root Simple CRUD modules
DbContext in handlers Small service, simple aggregates, strong tests Boundary kept by discipline Many teams, complex invariants
Domain service Logic spanning aggregates, named policies Another type to find Logic that fits one aggregate

I watch the ratio of logic in services to logic in entities during review; when services keep growing, the model needs attention.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions service layer versus domain services. Why: Checks deeper understanding of how a fat service layer causes an anaemic model.
    How to answer

    These are three layers of responsibility:

    • An application service (Fowler's service layer) runs one use case. It loads aggregates through repositories, calls domain logic, commits the unit of work and publishes events. It handles transactions, authorisation and mapping, but holds no business rules.
    • A domain service holds stateless business logic that doesn't belong to one entity, often spanning aggregates (a funds transfer, a pricing policy). It's named in domain language and knows nothing about HTTP or EF Core.
    • Entities and value objects own their own invariants (order.Submit()), and they come first.

    When everything goes into a fat OrderService, entities become property bags: the anaemic domain model. Controllers should only translate HTTP. The trade-off is richer models and clear boundaries against more types and more thought about where each rule lives.

  2. When: Candidate debates wrapping DbContext in repositories. Why: Checks the trade-off of repositories over EF Core.
    How to answer

    I decide by what the abstraction protects, not by habit. DbContext is already a repository and unit of work, so a wrapper has to earn its place.

    • Testability alone isn't a reason. Mocking repositories tests the mocks, and the EF in-memory provider ignores SQL semantics. I test persistence against SQL Server in Testcontainers either way.
    • Write side: repositories per aggregate root pay off when aggregates have invariants and must be loaded whole.
    • Read side: project straight from DbContext with Select and AsNoTracking. Never return IQueryable from a repository.
    • EF Core 10 ExecuteUpdateAsync/ExecuteDeleteAsync bypass the change tracker and run at once, so they belong behind an intention-revealing method and need an explicit transaction to be atomic with SaveChanges.

    My answer flips for pure CRUD (skip repositories) or for Dapper, stored procedures or a second store (repositories hide them). The trade-off is domain protection against a layer that only renames EF Core.

  3. When: Candidate mentions where repository interfaces live in Clean Architecture. Why: Checks they can avoid leaking EF Core into Application and Domain.
    How to answer

    In Clean Architecture the interfaces live in the core and the implementations in Infrastructure. I define one repository per aggregate root (IOrderRepository with GetAsync(OrderId) and Add), usually in the Domain or Application project, and implement it with EF Core in Infrastructure. DbContext already is the unit of work, so at most I expose a thin IUnitOfWork.SaveChangesAsync. Specifications are named query objects whose evaluation stays in Infrastructure.

    The rule: no IQueryable, DbSet, Include or EF attributes cross into the core. Reads can skip repositories and project straight to DTOs. For CRUD or vertical slices, I'd skip the abstractions and use DbContext directly. The trade-off: isolation and testability of the domain versus extra layers.

🛠 Real-world problems: how you handle them

Transfer limits enforced differently by three channels
Situation
A [neobank] had transfer rules in the mobile API, internet banking and a scheduled-payments job, each with its own `TransferService`. Around [30,000] transfers a day.
Signals
A customer complaint that a scheduled payment exceeded the daily limit; reconciliation showed [~40] transfers a week above the limit, all from the scheduled-payments job.
Investigation
Compared the three implementations side by side, found the job used a calendar day in UTC while the APIs used Australian Eastern time, and the job ignored pending holds. Confirmed with transaction data in SQL and Application Insights traces.
Resolution
Hot-fixed the job's time zone. Then extracted the rules into a `FundsTransferService` domain service, using a `TimeProvider` and the bank's business time zone, and replaced the three services with thin handlers calling it.
Prevention
Single suite of domain tests for transfer rules, an architecture test that only the domain service calls `Account.Withdraw` for transfers, and a reconciliation alert on limit breaches.

How to tell it (STAR)

**S:** At [company], reconciliation found [about 40] transfers a week over the daily limit. **T:** I owned [finding the cause and making the rule consistent across channels]. **A:** I compared the three channel implementations, found the scheduled job used UTC days and ignored holds, shipped a hot-fix, then proposed one domain service for the rules. I wrote an ADR, built it with [a colleague] and switched channels one at a time behind tests. **R:** Limit breaches went to [zero] and the transfer rules now live in one place with [40] unit tests running in [under a second].

More in Domain-Driven Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me