Codebase architecture series: 1. Layered, hexagonal, onion, clean · 2. DDD and package structure
Part 1 answered “which way do dependencies point”; this post answers the next question: how many parts is the domain split into, and which package does each part live in. The answer comes from Domain-Driven Design (DDD), applied to a flight-booking codebase skeleton (Java 21, compiled and run, with 4 ArchUnit 1.4.1 rules).
1. Packages by layer or by feature
Key idea: splitting by layer is easy to start with but encapsulates nothing. Splitting by feature keeps each business change in one package and lets the compiler block cross-access.
1.1. Package-by-layer
com.example.shop
├── controller (OrderController, ProductController, UserController, ...)
├── service (OrderService, ProductService, UserService, ...)
├── repository (OrderRepository, ProductRepository, ...)
├── entity
└── dto
Classes of the same technical kind live together. With 40 features:
- One business change (adding a discount code to orders) touches 4–5 packages.
- Every class has to be
public, so nothing is internal:ProductServicecallsOrderRepositorydirectly and nothing stops it. - The package names don’t say what the application does, only “this is a Spring app”.
1.2. Package-by-feature (by domain)
com.example.shop
├── order (OrderController, OrderService, Order, OrderRepository, ...)
├── catalog (ProductController, Product, ...)
├── customer
└── shared (Money, utilities that are genuinely shared)
Changes to orders stay inside order. Internal classes can be package-private (no public, visible only inside the same package), and the compiler stops other packages from using them. The folder tree tells you what the application does: Robert Martin calls this “screaming architecture”.
Inside each feature package you can still split by layer (order.domain, order.application, order.adapter). The course’s sample repo uses the reverse hybrid: api, app, domain.<feature>, infrastructure at the top, and inside domain a split into booking, homestay, user.
That leaves the question: by what criteria do you split “features” (are order and payment one or two? flight and seat?). DDD answers it.
2. What DDD is
Key idea: DDD (Eric Evans, 2003) puts the business at the centre of the design; the framework and database are details. Class and method names in the code should match how business people talk.
DDD is both a set of techniques and a way of working: developers and domain experts build the model together. It has two parts:
- Strategic design: splitting the system into bounded contexts and the relationships between them. It decides the top-level packages and the service boundaries.
- Tactical design: the building blocks inside one context: entities, value objects, aggregates, domain services, repositories, domain events.
3. Strategic design
Key idea: find the areas where each word has one meaning (bounded contexts), give each its own model and language, and let them talk only through public APIs, never by reading each other’s tables or internal classes.
3.1. Bounded context
A bounded context is an area that groups related functions and concepts, inside which every word has exactly one meaning. A flight-booking example: to sales, a “Booking” is a reservation with passengers and a price; to flight operations it’s a row holding a seat on the seat map; to accounting it’s a receivable. Cramming all three meanings into one Booking class gives you a 60-field class that everyone is afraid to touch.
Each context has its own model (same class names, different meanings are fine) and runs independently: analytics going down doesn’t take sales down with it. Context boundaries are candidates for top-level packages in a monolith, and for separate services if you later split into microservices. How to find service boundaries and carve up a monolith step by step is in Microservices: when to split and finding service boundaries.
The “letter” and “credit” examples, and finding boundaries with Event Storming
The slides’ two examples of one word, two meanings:
- A “letter” at the post office is a written letter on paper; in education (teaching spelling) it’s a character of the alphabet.
- “Credit” in lending is the ability to buy now and pay later based on trust; in accounting it’s the receiving side of an entry.
Common ways to find the boundaries:
- Event Storming: developers and business people stick business events (“Seats held”, “Payment succeeded”, “Ticket issued”) on a wall in time order, then group them. How to run the workshops, spot pivotal events and go from the wall to module boundaries: Discover the domain: Event Storming and Domain Storytelling.
- Look for where the same word changes meaning and where ownership changes hands.
- Look for where data must be consistent immediately versus where some delay is acceptable.
3.2. Ubiquitous language
Within a context, developers and the business share one ubiquitous language: the same words in meetings, in documents and in code. If the business says “hold the seats for 10 minutes, then they expire”, the code has Booking.hold(...), holdUntil and an EXPIRED status, not insertTempRecord() or status = 3.
Modelling together forces developers to understand the problem, and shows the business where their own model contradicts itself (“can a refunded ticket still be changed?”).
3.3. Relationships between contexts
The public API can be an interface, REST or events. The calling side should have an anti-corruption layer: an adapter that translates the other context’s model into its own language, so changes over there don’t leak in. In section 6, FlightSeatInventoryAdapter is that layer.
4. Tactical design
Key idea: inside a context, business rules live in entities, value objects and aggregates; domain services hold rules that belong to no single object; application services only orchestrate; repositories are the aggregate’s way in and out.
flowchart LR
AS[Application service] -->|load, save| REPO[Repository]
AS -->|call methods| AR[Aggregate root Booking]
AS -->|apply rules| DS[Domain service FarePolicy]
F[Factory Booking.hold] -->|create| AR
AR --> E[Entity Ticket]
E --> VO[Value objects SeatNo, Money]
AR -->|record| EV[Domain event BookingConfirmed]
4.1. Entity
An object with an identity (ID) and a lifecycle: two entities with identical attributes are still different, and an entity whose attributes change is still the same one. Examples: User, Flight, Booking. equals/hashCode are based on the ID.
4.2. Value object
An object identified only by its value: no ID, immutable, shareable by many entities. Two Money(100000, VND) instances are equal and interchangeable. Examples: Address, Money (amount, currency), SeatNo, DateRange, configuration, enums.
A Java 21 record suits value objects: immutable, value-based equals/hashCode for free, and a compact constructor to check invariants:
public record Money(BigDecimal amount, Currency currency) {
public Money {
if (amount.signum() < 0) throw new IllegalArgumentException("negative");
}
public Money plus(Money o) {
if (!currency.equals(o.currency)) throw new IllegalArgumentException("currency");
return new Money(amount.add(o.amount), currency);
}
}
public record SeatNo(String value) {
public SeatNo {
if (!value.matches("[0-9]{1,2}[A-K]")) throw new IllegalArgumentException("bad seat " + value);
}
}
Use value objects instead of bare String/BigDecimal when a concept has rules (money, seat numbers, email, date ranges) and for aggregate IDs.
When to wrap a primitive in a value object
4.3. Aggregate
An aggregate is a cluster of entities and value objects treated as one unit to protect business invariants (an invariant: something that must always be true). All outside access goes through the aggregate root; nobody holds references to the objects inside. It is the transactional consistency boundary: one transaction modifies and saves one whole aggregate.
Example: Booking is the root and holds a list of Tickets (seat, passenger, fare). Invariants: 1–9 seats per booking, and it can only be confirmed while HELD and before the hold expires.
public class Booking { // aggregate root
private final BookingId id;
private final FlightRef flight; // reference another aggregate by ID
private final List<Ticket> tickets;
private BookingStatus status;
private final Instant holdUntil;
public static Booking hold(FlightRef flight, Map<SeatNo, Passenger> seats, Money farePerSeat, Instant now) {
if (seats.isEmpty() || seats.size() > 9) throw new IllegalArgumentException("1..9 seats per booking");
List<Ticket> t = seats.entrySet().stream()
.map(e -> new Ticket(e.getKey(), e.getValue(), farePerSeat)).toList();
return new Booking(BookingId.newId(), flight, t, now.plusSeconds(600));
}
public void confirm(Instant now) {
if (status != BookingStatus.HELD) throw new IllegalStateException("cannot confirm " + status);
if (now.isAfter(holdUntil)) { status = BookingStatus.EXPIRED; throw new IllegalStateException("hold expired"); }
status = BookingStatus.CONFIRMED;
}
public Money total() { return tickets.stream().map(Ticket::fare).reduce(Money::plus).orElseThrow(); }
record Ticket(SeatNo seat, Passenger passenger, Money fare) {} // inner entity, package-private
// private constructor, read-only getters
}
There is no setStatus(): changing state goes through a method with a business name, and that method checks the invariants.
4.4. Domain services and application services
- Domain service: rules that don’t naturally belong to any entity, usually involving several aggregates or a policy (fares by seats left, whether a passenger may fly a route). Stateless, ideally pure, no I/O.
- Application service (the slides just call it a “service”, e.g.
BookingService): orchestrates a use case: loads aggregates through repositories, calls the domain, saves, publishes events, manages transactions. It doesn’t know the business rules; a business-ruleifhere means the rule is in the wrong place.
4.5. Repository
A repository feels like a collection of aggregates (findById, save). The interface lives in the domain, the implementation in infrastructure: BookingRepository in the domain, BookingRepositoryImpl (or JpaBookingRepositoryAdapter) in infrastructure. One repository per aggregate root; a TicketRepository (a repository for an inner entity) is a sign the aggregate boundary has been broken.
4.6. Factories and domain events
- Factory: creates an aggregate with its invariants satisfied from the start; when simple it’s a static method on the root (
Booking.hold(...)), when complex a separate class. - Domain event: a business event that has happened, named in the past tense (
BookingConfirmed,SeatsReleased). The aggregate records it, the application service publishes it after saving, and other contexts listen to update their own models. Publishing reliably needs an outbox (see Observer and Spring events).
5. The DDD layers
Key idea: DDD splits code into four layers so business rules don’t mix with technical concerns. The domain sits at the centre and depends on no other layer.
| Layer | Responsibility | Examples |
|---|---|---|
| User interface | Accept input, present output | REST controllers, CLIs, consumers |
| Application | Orchestrate use cases, transactions, security; doesn’t know business rules | HoldSeatsService, commands, results |
| Domain | Business rules and the domain model | aggregates, entities, value objects, domain services, repository interfaces |
| Infrastructure | The technical capabilities the application needs | JPA repositories, caches, messaging, external API calls |
The slides draw dependency arrows from UI down to Infrastructure, like classic layered architecture; don’t read them literally, because the domain belongs at the centre.
Rereading the slides’ four-layer diagram
6. Homework: a flight-booking codebase skeleton
Key idea: two bounded contexts, Booking and Flight, each with its own domain, application and adapters; Booking touches Flight only through one public API, and ArchUnit checks that in CI.
The exercise (paraphrased): build a clean architecture + DDD codebase for flight booking, with packages and classes only. I added just enough logic to run one flow (hold two seats, then a second customer holding the same seat gets rejected) and checked it with ArchUnit.
6.1. Splitting the bounded contexts
Three contexts (the exercise only builds the first two):
- Booking (sales): hold seats for passengers, compute the price, confirm on successful payment, expire after 10 minutes.
- Flight (flight operations, seat inventory): schedules, seat maps, the state of each seat. The source of truth for seats.
- Payment: create payment links, receive IPNs, reconcile. Here it’s only an outbound port from Booking; details in VNPay integration.
6.2. The package tree
com.example.flightbooking
├── booking # Booking bounded context
│ ├── domain
│ │ ├── model Booking (aggregate root), Ticket, BookingId, BookingStatus,
│ │ │ FlightRef, Passenger, SeatNo, Money
│ │ ├── port BookingRepository, SeatInventory, PaymentGateway (interfaces)
│ │ └── service FarePolicy (domain service, pure)
│ ├── application HoldSeatsUseCase (inbound port), HoldSeatsService,
│ │ HoldSeatsCommand, HoldSeatsResult
│ └── adapter
│ ├── in/web BookingController (+ HoldRequest)
│ └── out
│ ├── persistence InMemoryBookingRepository (real version: JPA + mapper),
│ │ FlightSeatInventoryAdapter (anti-corruption layer to Flight)
│ └── payment FakePaymentGateway (real version: VnpayPaymentGateway)
├── flight # Flight bounded context
│ ├── api SeatHoldApi (the context's only public API)
│ ├── application SeatHoldService
│ └── domain/model FlightSeatMap (aggregate: one flight's seat map)
└── config Main (composition root; @Configuration in Spring)
Four decisions worth remembering:
- Outbound ports live in
domain.port: they speak Booking’s language (SeatInventory.holdAll), not JPA’s or Flight’s. Bookingreferences the flight with aFlightRef(flight number + date) and doesn’t hold the other context’sFlightobject.- Booking doesn’t hold seats itself: it asks Flight through the
SeatInventoryport, and theFlightSeatInventoryAdaptertranslates that intoSeatHoldApi. If Flight becomes its own service, only the adapter changes, to HTTP. - The use case has an interface (
HoldSeatsUseCase) so controllers and tests depend on an abstraction; a small team can drop it and call the service directly.
6.3. The application service
HoldSeatsService has no business if apart from translating a failure. The seat-count rule is in Booking.hold, the pricing rule in FarePolicy, the double-booking rule in FlightSeatMap.
public class HoldSeatsService implements HoldSeatsUseCase {
private final BookingRepository bookings;
private final SeatInventory inventory;
private final PaymentGateway payment;
private final FarePolicy fares;
private final Clock clock;
// the constructor takes all 5 dependencies: Spring injects them, tests pass fakes
@Override
public HoldSeatsResult hold(HoldSeatsCommand cmd) {
FlightRef flight = new FlightRef(cmd.flightNo(), cmd.date());
Map<SeatNo, Passenger> seats = cmd.seatToPassengerName().entrySet().stream()
.collect(Collectors.toMap(e -> new SeatNo(e.getKey()), e -> new Passenger(e.getValue(), "N/A")));
Booking booking = Booking.hold(flight, seats, fares.farePerSeat(flight, 50), clock.instant());
if (!inventory.holdAll(flight, seats.keySet(), booking.id())) throw new IllegalStateException("SEAT_UNAVAILABLE");
bookings.save(booking);
return new HoldSeatsResult(booking.id().value().toString(),
booking.total().amount().toPlainString(), payment.createPaymentUrl(booking.id(), booking.total()));
}
}
Running Main (the composition root, where everything is newed and wired):
HoldSeatsResult[bookingId=809bf539-..., total=2400000, paymentUrl=https://pay.example/checkout?ref=809bf539-...&amount=2400000]
second hold: SEAT_UNAVAILABLE
The trap to remember: if holding seats succeeds but saving the booking fails, the seats are held for nobody; once Flight is a separate service, the ordering and compensation (a mini saga) must be part of the design.
Orphaned seat holds: three ways out
6.4. Checking the boundaries with ArchUnit
Four rules on the bytecode, all passing:
- The domain depends on no application, adapter or framework code.
- The Booking context has the onion shape.
- Other contexts reach Flight only through
flight.api. - There are no dependency cycles between contexts.
In a Spring project they live in an @AnalyzeClasses test class and run in CI alongside the unit tests.
The four ArchUnit 1.4.1 rules, their output and the failing first run
// 1. a pure domain: no dependencies on application/adapter code or frameworks
noClasses().that().resideInAPackage("..domain..")
.should().dependOnClassesThat().resideInAnyPackage("..application..", "..adapter..",
"org.springframework..", "jakarta.persistence..");
// 2. the onion shape of the Booking context, excluding the composition root
onionArchitecture()
.domainModels("..booking.domain.model..")
.domainServices("..booking.domain.service..", "..booking.domain.port..")
.applicationServices("..booking.application..")
.adapter("web", "..booking.adapter.in.web..")
.adapter("persistence", "..booking.adapter.out.persistence..")
.adapter("payment", "..booking.adapter.out.payment..")
.ignoreDependency(resideInAPackage("..config.."), DescribedPredicate.alwaysTrue());
// 3. other contexts may only reach Flight through flight.api
noClasses().that().resideOutsideOfPackages("..flight..", "..config..")
.should().dependOnClassesThat().resideInAnyPackage("..flight.domain..", "..flight.application..", "..flight.adapter..");
// 4. no dependency cycles between contexts
slices().matching("com.example.flightbooking.(*)..").should().beFreeOfCycles();
OK domain is framework-free and depends on nothing outward
OK Onion architecture consisting of
OK other contexts use only flight.api
OK slices matching 'com.example.flightbooking.(*)..' should be free of cycles
0 rule(s) failed
- On the first run, rules 2 and 3 failed on
Mainbecause the composition root knows every implementation. The fix: move it intoconfigand exclude it. - Adding a domain class with a field of an adapter type makes rules 1 and 2 fail, naming the field.
6.5. What a senior would improve
Five directions: a real Payment context via events, idempotency with requestId, seat holds in the database, rounding money, Spring Modulith.
The five improvements in detail
- Add a real Payment context with a
PaymentSucceededevent → Bookingconfirm, through an outbox; the handler is idempotent by transaction ID. - The
requestIdin the command isn’t used yet: store it with a unique constraint so repeated requests (double clicks, retries) don’t create two bookings (see idempotency keys). - The in-memory
FlightSeatMapusessynchronized; the real version is a seat table withUPDATE ... WHERE holder IS NULLorSELECT ... FOR UPDATE ORDER BY seat_no(see concurrent seat holds). - Fares are returned as unrounded
BigDecimals: define scale and rounding inMoneyper currency (VND has 0 decimal places). - Spring Modulith (
ApplicationModules.of(App.class).verify()) can replace rules 3 and 4, with an auto-generated module diagram.
Remember
- Explain why package-by-feature encapsulates better than package-by-layer, and what package-private buys you.
- Define a bounded context with a “one word, several meanings” example, and say how two contexts talk.
- Tell an entity from a value object, and an application service from a domain service.
- Know how to draw aggregate boundaries (small, by ID, one aggregate per transaction), and why a
Flightholding every seat is wrong. - Read the dependency direction of the four DDD layers correctly: the domain at the centre, depending on nothing.
Interview questions
Mid
How does an entity differ from a value object? Give examples.
An entity has an identity and a lifecycle and is compared by ID; a value object is just a value, immutable, compared by all its attributes.
Two bookings are different even with the same data, and a booking is still the same booking when its status changes. Two Money(100000, VND) instances are interchangeable. Entity examples: User, Flight, Booking; value object examples: Money, Address, SeatNo, DateRange. In Java 21, value objects fit naturally as records.
What is a bounded context? Why do you need one?
An area of the system with its own model and language, inside which each word has exactly one meaning.
The same word (“Booking”, “credit”) means different things in different departments; one shared model for all of them grows bloated and contradictory. Each context has its own model, communicates through APIs or events and runs independently. Context boundaries become top-level packages in a monolith and candidates for separate services.
What does package-by-feature give you over package-by-layer?
A feature change stays inside one package, and internal classes can be package-private so the compiler blocks cross-access.
The folder structure tells you about the business, and it’s easy to hand a package to one team and split it into a service later. Package-by-layer forces everything to be public and spreads a single change across many packages.
How does an application service differ from a domain service?
A domain service holds business rules; an application service orchestrates a use case and holds no rules.
A domain service covers rules that don’t belong to a specific entity (pricing policies, flight eligibility checks); it is stateless and ideally pure. An application service loads aggregates, calls the domain, saves, publishes events and manages transactions and security.
Senior
What is an aggregate, and how do you design aggregate boundaries?
A cluster of entities and value objects treated as one consistency unit, accessed through the aggregate root, with one transaction modifying one aggregate.
Design it as small as possible while still protecting the invariants that must be consistent immediately; reference other aggregates by ID; keep aggregates consistent with each other through events. A big aggregate (a Flight containing every seat and booking) causes lock contention and slow loading.
Where does the repository interface live, and why?
In the domain layer (or next to the use case), with the implementation in infrastructure: that’s dependency inversion.
The domain defines what it needs in its own language, and infrastructure depends on the domain to implement it. So the domain can be tested with an in-memory version, and switching storage technology doesn’t touch the domain. One repository per aggregate root, none for inner entities.
How do two bounded contexts talk to each other without becoming tightly coupled?
Through the called context’s public API, never by reading each other’s tables or internal classes, with an anti-corruption layer on the calling side.
The API can be an interface in a monolith, REST/gRPC, or events. The anti-corruption layer translates the other model into the caller’s language. Prefer events for things that can be eventually consistent, and synchronous calls for things that need an immediate answer (holding seats), with error handling and compensation, because there is no shared transaction.
Would you apply DDD to every project?
No. DDD is worth it when the business logic is complex and a competitive advantage, when there are domain experts to model with, and when the project will live a long time.
Good fits: pricing, booking, payments. For CRUD, internal tools or “generic” subdomains (sending email, authentication), use off-the-shelf solutions and a lean architecture. The strategic part (bounded contexts, a shared language) is useful far more widely than the tactical part.
Useful phrases for interviews
- “Domain-driven design pays off when the business rules are the hard part, not the plumbing.”
- “Booking and Flight are separate bounded contexts, each with its own model, linked by IDs and events.”
- “The ubiquitous language shows up directly in our class and method names, like hold, confirm and expire.”
- “All changes go through the aggregate root, which enforces invariants such as one to nine seats per booking.”
- “I keep aggregates small and reference other aggregates by ID, so two customers don’t fight over one lock.”
- “Money is a value object, so we model it as an immutable record that validates itself.”
- “An anti-corruption layer keeps the other context’s model out of ours.”
- “Across aggregates and contexts we accept eventual consistency through domain events and an outbox.”
- “With package-by-feature, internals stay package-private and the folder tree screams flight booking, not Spring.”
- “We enforce context boundaries with ArchUnit in CI, so other contexts can only reach Flight through its public API.”
Notes based on the Advanced Backend course (Ronin Engineer), rewritten in my own words.