Book › DDD

Separating application and domain services in DDD

Place request validation, authorization, transaction boundaries, and cross-aggregate business rules in the right layer using Kotlin and Spring.

Separating application and domain services in DDD

An order service can grow to parse HTTP requests, check permissions, calculate discounts, and call a payment provider. In these notes on Chapters 6 and 7 of Getting Started with Domain-Driven Development, I use Kotlin examples to give each responsibility a clear owner.

The examples use Kotlin 1.9, Java 21, Spring Boot 3.x, Spring Security 6, and Spring Data JPA.

Divide the request from the use case

The presentation layer accepts an HTTP request, maps it to a request DTO, validates its shape, and extracts the authenticated principal. It calls the application service and translates the result into an HTTP response.

The application service coordinates a use case. It loads roots, invokes business behavior, manages its transaction, and arranges any event publication. It takes a plain DTO, ID, or domain value so the same operation can be called from a controller, job, or test. For a straightforward read, a controller can call a query object and return a projection.

flowchart TD
    Ctrl["Presentation (controller)"]
    AppSvc["Application service"]
    DomSvc["Domain service"]
    Agg["Aggregate"]
    Infra["Repositories and adapters"]

    Ctrl -->|"Passes DTO"| AppSvc
    AppSvc -->|"Delegates changes"| Agg
    AppSvc -->|"Delegates policy"| DomSvc
    AppSvc -->|"Loads and saves"| Infra
    DomSvc -.->|"Uses a port"| Infra

When the application service decides whether a shipped order can change, the same condition tends to appear in every use case that supports an order edit. I put the rule on the aggregate and let the service invoke it. That keeps the invariant consistent and makes it possible to test it without setting up repositories or a Spring context. The layered order model shows how the entity can expose that behavior.

Put validation and authorization at the right boundary

I split a service by use case when a growing OrderService accumulates dependencies that only one or two methods need. CancelOrderService and ChangeShippingService can have separate tests and transaction concerns. If a service has one implementation and callers do not need a distinct port, a concrete class is sufficient.

Request validation checks required fields and formats with @Valid. The use case checks whether the requested order exists and invokes the aggregate to enforce transitions such as verifyNotYetShipped(). This protects the invariant when a command arrives through an entry point that does not use HTTP validation.

Authorization also has layers. A SecurityFilterChain can restrict general URL access. With @EnableMethodSecurity, an AuthorizationManagerBeforeMethodInterceptor evaluates a @PreAuthorize expression before invoking the method. A role check is enough for some decisions. When canceling requires knowing whether the current customer owns the order, a policy such as CancelPolicy can evaluate the loaded order and the actor together. Spring Security method security

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// com/example/shop/order/application/CancelOrderService.kt
package com.example.shop.order.application

import com.example.shop.order.domain.CancelPolicy
import com.example.shop.order.domain.Canceller
import com.example.shop.order.domain.OrderNo
import com.example.shop.order.domain.OrderRepository
import com.example.shop.order.domain.RefundService
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
class CancelOrderService(
    private val orderRepository: OrderRepository,
    private val cancelPolicy: CancelPolicy,
    private val refundService: RefundService,
) {
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    @Transactional
    fun cancel(orderNo: OrderNo, canceller: Canceller) {
        val order = orderRepository.findById(orderNo)
            ?: throw NoOrderException(orderNo)
        if (!cancelPolicy.hasCancellationPermission(order, canceller)) {
            throw NoCancellablePermissionException()
        }
        order.cancel()
        refundService.refund(order.number)
    }
}

Use a domain service for rules that span objects

Discount calculation can need order lines, coupons, and a member grade. If the rule has no natural owner among the involved objects, I give it a stateless domain service. The objects needed for the calculation arrive as parameters, and the service expresses the discount in domain terms.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// com/example/shop/order/domain/DiscountCalculationService.kt
package com.example.shop.order.domain

import com.example.shop.common.model.Money
import com.example.shop.member.domain.MemberGrade
import org.springframework.stereotype.Component

@Component
class DiscountCalculationService {
    fun calculateDiscountAmounts(
        orderLines: List<OrderLine>,
        coupons: List<Coupon>,
        grade: MemberGrade,
    ): Money {
        val couponDiscount = coupons.fold(Money(0)) { acc, c -> acc + c.discountAmount }
        val total = orderLines.fold(Money(0)) { acc, line -> acc + line.amounts }
        val gradeDiscount = Money(total.value * grade.discountRate / 100)
        return couponDiscount + gradeDiscount
    }
}

The order can accept the service as a parameter, as in order.calculateAmounts(discountCalculationService, member.grade). The entity remains independent of Spring bean injection.

A payment refund needs an external adapter. The domain-facing RefundService expresses the operation that the shop needs. PgRefundService implements that interface in the infrastructure package by calling the payment provider. The dependency points toward the interface. An application test can supply a stub through the same contract.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// com/example/shop/order/domain/RefundService.kt
package com.example.shop.order.domain

interface RefundService {
    fun refund(orderNo: OrderNo)
}

// com/example/shop/order/infra/PgRefundService.kt
package com.example.shop.order.infra

import com.example.shop.order.domain.OrderNo
import com.example.shop.order.domain.RefundService
import org.springframework.stereotype.Component

@Component
class PgRefundService(
    private val pgClient: PgHttpClient,
) : RefundService {
    override fun refund(orderNo: OrderNo) {
        pgClient.requestCancel(orderNo.number)
    }
}

Compare the two service responsibilities

ConcernApplication serviceDomain service
Package in this exampleorder.applicationorder.domain
Main responsibilityCoordinates a use case, authorization, and event timingImplements a policy or domain operation that spans objects
TransactionDefines when the use case commitsRuns within the transaction established by the caller when one is needed
Data accessLoads and saves relevant rootsTypically accepts the domain objects needed for the operation
ExamplesCancelOrderService, ChangeShippingServiceDiscountCalculationService, RefundService

Spring’s TransactionInterceptor handles calls that go through the transactional proxy and delegates resource management to the selected transaction manager. I place the transaction boundary at the application operation because that is where I can see which changes must succeed together. A self-invocation that bypasses the proxy does not get that advice. Spring declarative transactions

Check transaction duration and service state

The cancellation excerpt calls the payment provider inline to show the boundary problem. A slow payment call can keep the SQL transaction open and a HikariCP connection occupied. A remote refund also cannot roll back with the local database.

  • For a refund that must survive a process restart, store a durable handoff in the order transaction and process it afterward. See the domain events and async processing example.
  • Keep request-specific calculations in local variables. A mutable property on a singleton domain service is shared across concurrent calls.
  • If application services start injecting each other to reuse rules, move the shared policy into the object that owns it or a domain service. Check which caller owns the transaction.
  • Test permission and state separately. A user can have the right role and still lack permission to cancel a specific order, and an authorized user can still be too late to cancel.
This post is licensed under CC BY 4.0 by the author.