Domain Service Extraction Roadmap: Moving Logic from Controllers to Aggregate Roots and Application Services
This roadmap provides a structured, incremental approach to refactoring a monolithic controller layer into a clean Domain-Driven Design (DDD) architecture. The goal is to make controllers "thin" (handling only HTTP concerns like input validation, serialization, and orchestration), while embedding business logic in aggregate roots (for single-aggregate invariants and behavior) and application services (for use cases orchestrating multiple aggregates or external concerns). Domain services are introduced sparingly for cross-aggregate logic that doesn't belong in aggregates.
Key Principles:
- Incremental: Refactor one feature/use case at a time to minimize risk.
- Test-Driven: Achieve >80% coverage before/after changes.
- Backward Compatible: No breaking changes to APIs during transition.
- Assumptions: Existing codebase (e.g., Spring Boot, .NET, or similar) with controllers bloated by business logic; domain model partially exists.
Estimated Timeline: 4-8 weeks for a medium-sized app (10-20 controllers), depending on team size and complexity.
Phase 1: Assessment and Planning (1-2 days)
- Inventory Controllers: Scan all controllers. For each endpoint:
- List business logic (e.g., validations, calculations, state changes).
- Classify: Aggregate-specific (→ Aggregate Root), cross-aggregate/external (→ Application Service), pure orchestration (keep in controller).
- Prioritize by usage/risk: High-traffic endpoints first.
- Map to Domain Model:
- Identify aggregates (e.g.,
Order aggregate root with OrderLine entities).
- Spot anemic models (data-only entities) needing behavior injection.
- Define Boundaries:
- Create a spreadsheet: Endpoint → Use Case → Target (Aggregate Root / App Service).
- Sketch package structure:
domain/aggregates, domain/services, application/services, adapters/controllers.
- Tools Setup:
- Static analysis (SonarQube, ArchUnit for layer enforcement).
- Refactoring IDE plugins (IntelliJ/Spring Tools).
Deliverable: Prioritized backlog (e.g., Jira tickets) with complexity scores.
Phase 2: Foundation and Test Harness (2-3 days)
- Boost Test Coverage:
- Unit test controllers end-to-end.
- Add integration tests for happy/sad paths.
- Aim for 90%+ coverage on targeted controllers.
- Introduce Application Service Layer (skeleton):
public interface OrderApplicationService {
OrderDto createOrder(CreateOrderRequest request);
}
- Delegate trivial calls from controllers (no logic move yet).
- Enforce Layers: Use annotations/open modules to prevent controller → domain leaks.
- Eventual Consistency Prep: If needed, introduce domain events for cross-aggregate pub/sub.
Milestone: Controllers call app services; tests pass unchanged.
Phase 3: Extract to Aggregate Roots (1 week per 3-5 endpoints)
Focus: Intra-aggregate logic (e.g., Order.calculateTotal(), Customer.validateDiscount()).
- Per Endpoint:
- Extract validations/calculations to aggregate methods.
// Before: Controller
if (order.getItems().size() > 10) { throw new ValidationException(); }
order.setTotal(items.stream().mapToDouble(Item::getPrice).sum());
// After: Aggregate Root
public class Order {
public void addItem(Item item) {
if (items.size() >= MAX_ITEMS) throw new DomainException("Too many items");
items.add(item);
recalculateTotal(); // Invariant enforcement
}
private void recalculateTotal() { /* business logic */ }
}
- Controller becomes:
@PostMapping("/orders")
public OrderDto createOrder(@RequestBody CreateOrderRequest req) {
Order order = Order.create(req.getCustomerId(), req.getItems());
orderApplicationService.save(order); // Delegates persistence
return OrderDto.from(order);
}
- Handle State Changes: Use factory methods (
Order.create()) or builder patterns for creation.
- Test: Unit tests on aggregates (e.g.,
assertThrows for invariants); refactor controller tests to use aggregates.
- Commit Per Endpoint: Merge after green tests + manual QA.
Milestone: 50% of prioritized endpoints have aggregate-enriched logic.
Phase 4: Introduce Application Services for Orchestration (1 week per 3-5 endpoints)
Focus: Cross-aggregate use cases (e.g., placeOrder() coordinating Order, Inventory, Payment).
- Identify Use Cases: One app service per bounded context/feature (e.g.,
OrderApplicationService).
- Extract Logic:
// Controller delegates fully
@PostMapping("/orders")
public OrderDto createOrder(@RequestBody CreateOrderRequest req) {
return orderApplicationService.placeOrder(req);
}
// App Service orchestrates
@Transactional
public OrderDto placeOrder(CreateOrderRequest req) {
Customer customer = customerRepository.findById(req.getCustomerId());
Order order = Order.create(customer, req.getItems());
inventoryService.reserveStock(order); // Domain service call if cross-aggregate
paymentGateway.charge(order);
orderRepository.save(order);
return OrderDto.from(order);
}
- Domain Services (if needed): Stateless utils for shared logic (e.g.,
DiscountCalculatorService).
- Persistence: Move to repositories (infrastructure layer); app services inject them.
- Error Handling: Centralized in app services (e.g.,
DomainException → HTTP 422).
- Test:
- Unit: Mock repositories/aggregates.
- Integration: In-memory DB slices.
Milestone: Controllers <50 LOC; all business logic in domain/app layers.
Phase 5: Polish, Verify, and Harden (3-5 days)
- Controller Cleanup:
- Input DTO validation (@Valid).
- Output mapping (MapStruct/ModelMapper).
- Auth/authorization (e.g., Spring Security).
- Cross-Cutting: Logging, metrics, caching in aspects/interceptors.
- Full Regression:
- Load tests.
- Chaos engineering (if advanced).
- Architecture Enforcement:
- Dependency inversion (app services depend on domain interfaces).
- Static checks: No direct repo access from controllers.
- Documentation: Update API docs (Swagger) reflecting thin controllers.
Deliverable: Architecture diagram + enforcement rules.
Phase 6: Deployment and Monitoring (Ongoing)
- Canary Releases: Roll out per feature flag (e.g., LaunchDarkly).
- Monitor:
- Metrics: Response time, error rates.
- Traces: Jaeger/OpenTelemetry for layer flows.
- Iterate: Handle edge cases; expand to remaining controllers.
- Team Training: Workshops on DDD patterns.
Potential Pitfalls and Mitigations
| Pitfall | Mitigation |
|---|
| Big Bang Temptation | Strict per-endpoint commits; feature flags. |
| Anemic Domain Bleeds Back | Aggregate workshops; code reviews. |
| Transaction Hell | @Transactional at app service; domain events for sagas. |
| Performance | Profile before/after; lazy loading in aggregates. |
| Legacy DB Constraints | Use repositories with query objects; evolve schema gradually. |
This roadmap transforms controllers into adapters, unlocking testability, scalability, and maintainability. Track progress with metrics like "LOC in controllers" dropping 70%+. If you provide code samples or tech stack details, I can refine with specifics.