DDD and package structure: bounded contexts, aggregates and a flight-booking codebase skeleton
Splitting a codebase by business capability: package-by-layer versus package-by-feature, bounded contexts, the ubiquitous language, entities, value objects, aggregates, the DDD layers, and a flight-booking codebase skeleton with its boundaries checked by ArchUnit.
On this page
1. The problem
A booking codebase is split by layer: controller, service, repository, entity. The Booking class has 60 fields, half of them null depending on who uses it: sales needs passengers and fares, flight operations needs seat holds, accounting needs receivables. Adding a discount code touches 5 packages, and a PR from the accounting team breaks the seat-hold flow.
2. Key idea
DDD (Domain-Driven Design) puts the business at the center. Strategically: find bounded contexts, areas where each word has one meaning, and give each its own model (SeatHold, Receivable instead of one shared Booking), linked by bookingId. Within a context, code uses the business's exact words (ubiquitous language): "hold seats for 10 minutes, then expire" becomes Booking.hold(...), holdUntil, EXPIRED, not status = 3.
| Building block | What it is | Example |
|---|---|---|
| Entity | has an ID and lifecycle; equals by ID |
Flight, Booking |
| Value object | just a value, immutable | Money, SeatNo |
| Aggregate | a cluster keeping one invariant, changed through its root | Booking holding Tickets |
| Domain service | a rule owned by no entity, no I/O | FarePolicy |
| Application service | load, call the domain, save, transaction | BookingService |
2.1 How to lay out packages?
| Approach | Use when | Don't use when |
|---|---|---|
By layer (controller, service) |
small CRUD apps, little business logic | many features, many teams |
By feature, layers inside (booking.domain, booking.application, booking.adapter) |
backends with real business logic | a few-screen app |
| Large aggregate (Flight holding every seat) | hundreds booking one flight: everyone fights one lock |
3. In Java
public class Booking { // aggregate root
private final BookingId id;
private final FlightRef flight; // another aggregate: ID only
private final List<Ticket> tickets;
private BookingStatus status;
private final Instant holdUntil;
public static Booking hold(FlightRef flight, Map<SeatNo, Passenger> seats, Instant now) {
if (seats.isEmpty() || seats.size() > 9) throw new DomainException("1–9 seats");
return new Booking(BookingId.next(), flight, Ticket.of(seats), HELD, now.plus(Duration.ofMinutes(10)));
}
public void confirm(Instant now) { // the invariant lives here, not in a service
if (status != HELD) throw new DomainException("not held");
if (now.isAfter(holdUntil)) throw new DomainException("hold expired");
status = CONFIRMED;
}
}A context's internal classes stay package-private, invisible to other packages. Other languages: Go splits by business package and internal/ directories; TypeScript uses feature modules with eslint-plugin-boundaries.
Context maps, DDD layers and boundary checks
- Two contexts talk through a public interface, REST or events. The caller has an anti-corruption layer translating the other model (e.g.
FlightSeatInventoryAdapterturns the flight context's DTO into the booking context'sSeatAvailability). - Layers: the domain (aggregates, value objects, repository interfaces) depends on nothing; the application layer orchestrates; adapters (REST, JPA, Kafka) implement the domain's interfaces.
- Domain events are named in the past tense (
BookingConfirmed); other contexts listen instead of calling directly. - ArchUnit checks: the domain imports no Spring or JPA; context A imports nothing internal to context B; no dependency cycles between contexts.
- Find context boundaries with Event Storming: put business events on a wall and group them where words change meaning.
4. Working with AI
Hand to AI: a package skeleton by context, value objects for primitives, ArchUnit boundary rules, tests for aggregate invariants.
Check yourself in AI-written code:
- Top-level packages are contexts, not
controller/service. - Invariants live in the aggregate, not scattered across application services.
- Aggregates reference other aggregates by ID, not by object.
- One transaction changes one aggregate; more than one means domain events.
- The domain imports no Spring, JPA or other contexts' classes (checked by ArchUnit).
5. Exercises
Exercise 1: Review a Flight aggregate
The AI makes Flight the aggregate root holding List<Seat> (180 seats) with book(seatNo, passenger), saying "proper DDD: every change goes through the root". When sales open, 300 people book the same flight at once. What happens? Propose a different design.
Solution 1
- Each booking loads all 180 seats, changes one, and saves the whole aggregate under one version: 300 people fight over one lock (or version), and most fail with optimistic locking or queue with pessimistic locking.
- Aggregates should be small, covering just the invariant that must be immediately consistent. "One seat, one passenger" is a per-seat invariant, not a per-flight one.
- Alternative:
Bookingis the aggregate, each seat is aseat_availabilityrow held with a conditional UPDATE;Flightholds only schedule and capacity. "Don't sell beyond capacity" is kept with a conditional counter, not by loading every seat.
Exercise 2: Choose a model for three departments
Sales, flight operations and accounting all need "booking". The AI offers (A) one shared Booking entity, adding fields as needed; (B) three models Booking, SeatHold, Receivable in three contexts, linked by bookingId and events. Pick one, give the reason and when the choice flips.
Solution 2
Pick B. Each department means something different by "booking"; one shared model becomes a God class every team edits, where any change can break another team. With B, accounting listens to BookingConfirmed to create a Receivable without touching sales code.
Pick A for a small system with one team and an unsplit business: three models plus events cost more than they return. Split once you see fields that are null depending on the user, and one team's PRs breaking another team's flow.
Summary
- Top-level packages by context, layers inside; internal classes package-private.
- Bounded context: one word, one meaning, one model per context.
- Entities have IDs; value objects are immutable and validate on creation.
- Small aggregates, changed through the root, one per transaction, referenced by ID.
- Rules live in the domain; application services only orchestrate.
Further reading: Layered, hexagonal, onion, clean.
Practice interview questions on this topic
- What are entities, value objects and aggregates in DDD, and how do you draw aggregate boundaries?
- How does an application service differ from a domain service, and where should repository interfaces live?
- What is a bounded context, and how do two contexts communicate without tight coupling?
- When should you not apply DDD or clean architecture, and how do you stay simple without closing off the future?
- What is layered architecture? Package by layer or by feature?
- What is hexagonal architecture (ports and adapters), and what fundamentally separates onion/clean from layered?
Comments
Community rules