Domain Service
Domain Service
A domain service is a piece of domain logic that doesn't naturally belong to a single entity or value object. It is stateless, lives in the domain layer, and does no I/O.
When you need one
You have logic that:
- Operates on multiple aggregates or VOs and isn't owned by any one of them.
- Encodes a business rule that's no single entity's responsibility.
- Returns a result based on inputs without holding state between calls.
The litmus test: if I put this method on entity X, would it have to reach into entity Y's internals? If yes -> domain service.
Python shape
# Domain service — pure, no I/O
class FundsTransfer:
@staticmethod
def execute(source: Account, target: Account, amount: Money) -> None:
if source.currency != target.currency:
raise CurrencyMismatch()
if source.balance < amount:
raise InsufficientFunds()
source.withdraw(amount)
target.deposit(amount)
Or just a function (Python doesn't require a class for stateless logic):
def calculate_tax(items: list[OrderItem], jurisdiction: TaxJurisdiction) -> Money:
rate = jurisdiction.rate_for(items[0].sku)
subtotal = sum((i.unit_price * i.quantity for i in items), Money(0))
return subtotal * rate
Domain Service vs Application Service / Use Case
| Domain Service | Application Service (Use Case) | |
|---|---|---|
| Has business logic? | Yes | No (orchestrates only) |
| Does I/O? | No | Yes (repos, events, etc.) |
| Tests | Pure unit, no mocks | Integration, with fake repos |
| Knows about persistence? | No | Yes |
| Knows about HTTP, queues? | No | No |
Domain Service vs Entity method
- Method on entity — operates on the entity's own data plus a few VOs.
- Domain service — spans multiple entities, no single owner.
Don't reach for a service when an entity method would do. Anemic Domain Models are mostly services that should have been methods.
Anti-patterns
- Service-dump. All logic in
OrderService,UserService,BookService; entities are anaemic data bags. You have services, not domain services. Move methods back to entities. - I/O in domain service. A "domain" service that calls a repository or sends email. Move to application layer.
- Stateful service. Holding instance state between calls. Accidentally an entity. Keep services stateless.
- Wrapping a single entity method.
class ActivateUserService: def execute(self, user): user.activate(). Just calluser.activate().
Keep them rare
In a well-modelled domain, most logic lives on entities and VOs. Domain services are the leftover — necessary but not abundant. If most of your domain is services, the model is anaemic.