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

📚 Interview question

What is the difference between a service layer, an application service and a domain service? Explain what goes where in a DDD-style .NET application, how a fat service layer leads to an anaemic domain model, and how you keep business rules out of controllers and handlers.

Service layer (Fowler) vs application service vs domain service (Evans/DDD): responsibilities (orchestration, transactions, authorisation and mapping vs stateless domain logic spanning aggregates), what belongs in entities, how 'god' service layers create an anaemic domain model, thin controllers/minimal API endpoints, and a funds-transfer example in .NET 10.

Intermediate Theory Intermediate anaemic-domain-model application-service design-patterns domain-driven-design domain-service service-layer

🎯 Key points

  • Service layer (Fowler, PoEAA): the application's boundary of operations; coordinates the response to each operation
  • Application service (DDD): one use case; loads aggregates via repositories, calls domain logic, commits the unit of work, publishes events; no business rules
  • Domain service (DDD): stateless domain logic that doesn't belong to one entity, usually spanning aggregates (funds transfer, pricing policy), named in the ubiquitous language
  • Entities and value objects own their own invariants (Order.Submit, Money arithmetic); prefer them before creating a domain service
  • Anaemic domain model: entities are property bags and all rules live in services, so invariants are duplicated and easy to bypass
  • Avoid a fat service layer: one handler per use case (vertical slices) instead of an OrderService with 40 methods, private setters on entities, and a review rule that any 'if' about business outcomes in a handler moves to the domain
  • Controllers/endpoints only translate HTTP: bind DTO, call the application service/handler, map the result to a status code; the same use case must be callable from a queue consumer or batch job
  • Domain services take domain types, don't depend on HTTP, EF Core or DTOs, and never call SaveChanges

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"The names get used loosely, so I separate them by what they're allowed to know. Fowler's service layer is the application's boundary: the set of operations the outside world can call, like 'place order' or 'transfer funds'. In DDD terms each of those is an application service, or in a vertical-slice codebase a command handler. It orchestrates: load the aggregates through repositories, check the user may do this, call the domain, save through the unit of work, publish an event, and return a result. It deals in DTOs, transactions and authorisation, but it shouldn't decide business outcomes.

Business outcomes belong in the domain. First choice is the entity or value object itself: order.Submit() refuses an empty order, and Money.Add refuses mixed currencies. A domain service is for domain logic with no natural home on one object, usually because it involves several aggregates. Transferring money between two Accounts is the classic example: debit one, credit the other, enforce the daily limit and the same-currency rule. A FundsTransferService is stateless, takes domain types, and has no idea that HTTP or EF Core exist. If it needs an exchange rate, it takes an IExchangeRateProvider interface defined in the domain.

The mistake I see is the fat service layer: an OrderService with 3,000 lines that checks every rule, sets every property and calls SaveChanges, while Order is a bag of public setters. That's Fowler's anaemic domain model. The rules get duplicated in the next service that touches orders, and anyone can set Status = Shipped directly. Controllers have a similar problem when they start validating business rules. My rule of thumb: controllers translate HTTP, application services orchestrate, entities enforce their own rules, and a domain service is the exception for logic that spans aggregates."


What goes where

Concern Controller / endpoint Application service / handler Domain service Entity / value object
HTTP binding, status codes Yes No No No
DTO mapping Optional Yes No No
Authorisation Policy attribute Resource checks No No
Transaction / SaveChanges No Yes No No
Business rule on one aggregate No No No Yes
Business rule across aggregates No No Yes Partly (each side's own rules)
Publishing events No Yes (or outbox) No Raises domain events

Smells and fixes

Smell Fix
Entity with only public setters Private setters + intention-revealing methods
OrderService with every rule Move rules into Order; keep orchestration in the handler
Domain service that calls DbContext Inject repositories into the application service instead
Controller checks "order must have lines" Move to Order.Submit()
Service named OrderManager/OrderHelper Name the use case or domain concept

Production example

In a loyalty-points system, the "points can't go negative" rule lived in four services and was missing from a fifth (a batch import), which created about 1,200 negative balances in one month. Moving the rule into PointsAccount.Redeem() and making the setters private turned the bug into a compile error in the import and removed around 300 lines of duplicated checks.

🔍 What the interviewer is checking

Checks whether the candidate can place logic in the right layer and recognises the anaemic domain model as a consequence of fat services.

Green flags

  • Distinguishes orchestration (application service) from domain logic (entity or domain service).
  • Gives a cross-aggregate example for a domain service.
  • Keeps transactions and DTOs out of the domain.
  • Describes thin controllers and reuse from other entry points.
  • Knows when CRUD doesn't need any of this.

Red flags

  • Uses "service" for everything without distinction.
  • Puts SaveChanges in domain services.
  • Thinks entities should only hold data.
  • Validates business rules in controllers.

📚 Learn in depth

1. Where the terms come from

  • Service Layer (Fowler, PoEAA): "defines an application's boundary with a layer of services that establishes a set of available operations and coordinates the application's response in each operation". Fowler warns against putting domain logic in it.
  • Application Service and Domain Service (Evans, DDD, and Vernon, Implementing DDD): Evans splits services into application, domain and infrastructure. A domain service is an operation that "does not naturally belong to an entity or value object", is stateless and is named in the ubiquitous language.
  HTTP request
      |
  Endpoint / controller        (bind DTO, auth policy, map result -> 200/400/404)
      |
  Application service/handler  (use case: load, authorise, call domain, save, publish)
      |            \
  Repositories      Domain service (stateless, spans aggregates)
      |                 |
  Aggregates <----------+   entities + value objects enforce their own invariants
      |
  Unit of work (DbContext.SaveChangesAsync)

2. Application service in detail

One public method per use case (or one handler class per command). Typical steps:

  1. Validate the input shape (or rely on endpoint validation).
  2. Load aggregates through repositories.
  3. Authorise against the loaded resource ("is this the customer's account?").
  4. Call entity methods or a domain service.
  5. Commit once.
  6. Publish integration events (ideally through an outbox).
  7. Map to a result DTO.

It's thin by design: if it contains if (account.Balance < amount), a business rule has leaked.

3. Domain service in detail

Use one when the logic:

  • involves several aggregates (transfer between accounts);
  • is a policy that changes independently (pricing, tax, eligibility);
  • needs a domain-defined dependency (exchange rates via an interface).

It should be pure where possible: domain types in, domain types (or domain events) out. It doesn't load or save; the application service does.

4. The anaemic domain model

Fowler called it an anti-pattern in 2003: objects that look like domain objects but have no behaviour, with all logic in services. Costs:

  • invariants duplicated across services and easily missed;
  • any code can put an entity into an invalid state;
  • tests have to go through services and mocks rather than testing the entity directly.

It isn't always wrong: for CRUD with no rules, a transaction script or direct endpoint code is simpler. The problem is a complex domain modelled anaemically.

5. Keeping controllers thin

Minimal API endpoints or controllers should be a few lines: bind, call, map. Business validation ("an order needs a line") goes in the domain; input-shape validation (required fields, lengths) can stay at the edge. A useful check: could you call the use case from a message consumer without copying anything from the controller? If not, logic has leaked into it.

6. Cost

More types, and decisions about where each rule lives. The payoff grows with domain complexity and the number of entry points (API, consumer, batch job) that share the same rules.

Try it yourself

  1. Take an anaemic Account with public setters and an AccountService; move the overdraft rule into Account.Withdraw and see which callers stop compiling.
  2. Write a FundsTransferService and unit-test it with two in-memory accounts and no mocks.
  3. Call the same application service from a minimal API endpoint and from a BackgroundService consumer.
  4. Grep your codebase for Service classes over 500 lines and list which methods contain business rules versus orchestration.

💻 Code

Entities enforce their own rules, a domain service handles the cross-aggregate rule, and the application service orchestrates.

namespace Bank.Domain;

public readonly record struct Money(decimal Amount, string Currency)
{
    public static Money operator -(Money a, Money b) => a.Currency == b.Currency
        ? new(a.Amount - b.Amount, a.Currency)
        : throw new InvalidOperationException("Currency mismatch.");
    public static Money operator +(Money a, Money b) => a.Currency == b.Currency
        ? new(a.Amount + b.Amount, a.Currency)
        : throw new InvalidOperationException("Currency mismatch.");
}

public sealed class Account(Guid id, Guid ownerId, Money balance)
{
    public Guid Id { get; } = id;
    public Guid OwnerId { get; } = ownerId;
    public Money Balance { get; private set; } = balance;     // no public setter: rules can't be bypassed

    public void Withdraw(Money amount)
    {
        if (amount.Amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
        if ((Balance - amount).Amount < 0) throw new InvalidOperationException("Insufficient funds.");
        Balance -= amount;
    }

    public void Deposit(Money amount)
    {
        if (amount.Amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
        Balance += amount;
    }
}

// Domain service: a rule that spans two aggregates, stateless, no EF Core or HTTP
public sealed class FundsTransferService
{
    private const decimal DailyLimit = 10_000m;

    public void Transfer(Account from, Account to, Money amount, decimal alreadyTransferredToday)
    {
        if (from.Id == to.Id) throw new InvalidOperationException("Cannot transfer to the same account.");
        if (from.Balance.Currency != to.Balance.Currency) throw new InvalidOperationException("Accounts use different currencies.");
        if (alreadyTransferredToday + amount.Amount > DailyLimit) throw new InvalidOperationException("Daily transfer limit exceeded.");

        from.Withdraw(amount);   // each entity still enforces its own invariants
        to.Deposit(amount);
    }
}

public interface IAccountRepository
{
    Task<Account?> GetAsync(Guid id, CancellationToken ct);
    Task<decimal> TransferredTodayAsync(Guid accountId, CancellationToken ct);
}
namespace Bank.Application;

using Bank.Domain;

public sealed record TransferRequest(Guid FromAccountId, Guid ToAccountId, decimal Amount, string Currency);
public sealed record TransferResult(decimal NewBalance);

public interface IUnitOfWork { Task<int> SaveChangesAsync(CancellationToken cancellationToken = default); }

// Application service: orchestration, authorisation and the transaction; no business rules
public sealed class TransferFundsHandler(IAccountRepository accounts, FundsTransferService transfers, IUnitOfWork unitOfWork)
{
    public async Task<TransferResult> HandleAsync(TransferRequest request, Guid currentUserId, CancellationToken ct)
    {
        var from = await accounts.GetAsync(request.FromAccountId, ct) ?? throw new KeyNotFoundException("Source account not found.");
        var to = await accounts.GetAsync(request.ToAccountId, ct) ?? throw new KeyNotFoundException("Target account not found.");
        if (from.OwnerId != currentUserId) throw new UnauthorizedAccessException();

        var today = await accounts.TransferredTodayAsync(from.Id, ct);
        transfers.Transfer(from, to, new Money(request.Amount, request.Currency), today);

        await unitOfWork.SaveChangesAsync(ct);    // one commit for both accounts
        return new TransferResult(from.Balance.Amount);
    }
}
// Program.cs: the endpoint only translates HTTP
builder.Services.AddSingleton<FundsTransferService>();   // stateless
builder.Services.AddScoped<TransferFundsHandler>();

app.MapPost("/transfers", async (TransferRequest request, TransferFundsHandler handler, ClaimsPrincipal user, CancellationToken ct) =>
{
    var userId = Guid.Parse(user.FindFirstValue(ClaimTypes.NameIdentifier)!);
    return Results.Ok(await handler.HandleAsync(request, userId, ct));
}).RequireAuthorization();

⚠ Common mistakes

  • Mistake: Putting every business rule in a big OrderService while entities only have public setters. Why it is wrong: That's an anaemic domain model; rules are duplicated and any caller can set invalid state. Instead: Move rules into entity methods and keep the service for orchestration.
  • Mistake: Creating a domain service for logic that belongs to one entity. Why it is wrong: It strips the entity of behaviour and scatters its rules. Instead: Use a domain service only for logic spanning aggregates or a separate policy.
  • Mistake: Letting a domain service load and save through DbContext. Why it is wrong: It mixes persistence and transactions into the domain and makes it hard to test. Instead: The application service loads, calls the domain service, and commits.
  • Mistake: Putting business validation in controllers. Why it is wrong: A message consumer or batch job calling the same use case skips it. Instead: Validate input shape at the edge; enforce rules in the domain.
  • Mistake: Passing DTOs or HttpContext into domain services. Why it is wrong: It couples the domain to the API contract and transport. Instead: Map to domain types in the application layer.
  • Mistake: Naming services OrderManager, OrderHelper or OrderProcessor. Why it is wrong: Vague names attract unrelated responsibilities until it's a god class. Instead: Name the use case (SubmitOrderHandler) or the domain concept (FundsTransferService).
  • Mistake: Building all three layers for a CRUD admin screen. Why it is wrong: It's ceremony with no rules to protect. Instead: Use a transaction script or direct endpoint code until real rules appear.

🏛 Senior insight: trade-offs

I treat "where does this rule live?" as a design review question, not a folder convention. Entities first, a domain service only when the rule genuinely spans aggregates, and application services kept thin enough that I could call them from an API, a queue consumer and a batch job without copying any logic.

Option When it fits Cost When not to
Transaction script in the endpoint CRUD, few rules Duplication if rules grow Rules shared by several entry points
Application service + rich entities Most business services More types, design discipline Pure CRUD
Domain service Rules across aggregates, independent policies Another abstraction Logic that belongs to one entity
Fat service layer + anaemic entities Rarely by choice Duplicated, bypassable rules Complex domains

A useful measure: how many places enforce a given rule? If the answer is more than one, the rule isn't in the domain yet.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate describes entities with only public setters and logic in services Why: Checks moving a codebase from an anaemic to a richer domain model
    How to answer

    In an anemic domain model, entities are property bags with public getters and setters, and all business rules live in service classes that read and set those properties. In a rich domain model, entities own their behaviour: state is private, changes happen through methods like order.Pay(amount) that enforce invariants, and services only orchestrate (load, call, save). Anemic models scatter and duplicate rules, let any code put objects into invalid states, and are hard to test without a database. They are acceptable for simple CRUD or reporting with few rules. Move towards a richer model incrementally: make setters private, move one rule at a time into the entity, protect collections, and use value objects, guided by where bugs actually occur.

  2. When: Candidate says the entity should enforce its own rules via methods Why: Checks Tell, Don't Ask as the principle behind rich entities
    How to answer

    Tell, Don't Ask means you tell an object what you want done, and the object decides how, using its own data. Instead of a service doing if (order.Status == Pending && !order.IsPaid) order.Status = Cancelled;, you call order.Cancel(), and the order enforces the rule. That keeps invariants in one place, removes duplicated checks across services and moves you from an anaemic model towards a rich one. It applies to behaviour; for reading data to display or report, querying is exactly right.

  3. When: Candidate mentions a huge OrderService doing everything Why: Checks the difference between a facade and a god service
    How to answer

    Facade puts a simple entry point in front of a complex subsystem, so clients make one call instead of coordinating many classes. The subsystem stays available for anyone who needs more control.

    .NET examples: File.ReadAllTextAsync (hides FileStream, StreamReader and encoding detection), HttpClient (hides the handler pipeline), JsonSerializer and DbContext. In business code, a checkout facade or application service coordinates inventory, payment and shipping for one use case.

    The difference from a god service is cohesion. A facade is thin orchestration for one client need, and it delegates the rules to the subsystems. A god service has dozens of unrelated methods, owns business logic and has a ten-dependency constructor. The trade-off is that facades tend to grow, so split them by use case.

  4. When: Candidate says the application service loads aggregates and commits Why: Checks how application services load aggregates through repositories
    How to answer

    A repository gives the domain a collection-like interface for one aggregate root: GetAsync(orderId), Add(order). The domain asks for orders; it doesn't know about SQL, DbContext or tables. That's different from a DAO/table gateway, which mirrors tables with CRUD per table.

    In EF Core, DbContext already is a repository (DbSet<T>) and a unit of work (SaveChanges). So a generic IRepository<T> with GetAll(), Update() and Save() usually adds a layer with no behaviour, and makes things worse:

    • IQueryable<T> GetAll() leaks EF semantics to callers.
    • Save() per repository breaks the unit of work.
    • It invites repositories for child entities, which bypass the aggregate's rules.

    A good repository is narrow and aggregate-specific, takes a CancellationToken and never commits. The trade-off is an abstraction that protects the domain model, against a layer that only renames EF Core.

↩ Usually asked after

More in Enterprise Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me