Software Architecture

Domain-Driven Design: Ubiquitous Language, Aggregates and Bounded Contexts

Advanced9 min readUpdated

Domain-driven design is a way of letting the shape of the business drive the shape of the code, and a vocabulary for negotiating boundaries between teams. This guide covers the strategic side — bounded contexts, context maps, subdomains — and the tactical side with a worked Java model, then shows how hexagonal layering keeps the domain free of frameworks.

What you will learn

  • Build a ubiquitous language with domain experts and keep it visible in the code
  • Model entities, value objects and aggregates with invariants that hold at every commit
  • Draw bounded contexts around language boundaries and document the relationships in a context map
  • Publish and consume domain events without leaking the internal model
  • Apply hexagonal layering so that the domain depends on no framework

Most software that becomes unmaintainable does so for the same reason: the code stopped describing the business. Class names drift away from what people actually say in meetings, rules end up in whichever service happened to be open at the time, and after two years the only reliable way to answer "what happens when an order is cancelled after dispatch?" is to read four thousand lines. Domain-driven design is a set of practices for preventing that, built on a claim that sounds obvious and is very hard to sustain: the model in the code and the model in the domain experts' heads should be the same model.

DDD has two halves that are usually taught together and adopted separately. The strategic half is about boundaries — which parts of the business get their own model, how those models relate, and where to invest scarce design effort. The tactical half is a set of building blocks for expressing a model in code. Strategic DDD is where most of the value is, and it is the part teams skip.

The ubiquitous language

A ubiquitous language is a vocabulary shared by developers and domain experts, used identically in conversation, in documentation and in code. Not a glossary that lives in a wiki nobody opens — a working language that changes when the team's understanding changes.

Its practical test is simple. Sit with a domain expert and describe what the code does using only the words in the code. If you find yourself translating — "what we call a TransactionRecord is what you call a settlement instruction, except when it is a reversal" — the translation is a permanent tax and a permanent source of defects, because every translation is an opportunity to translate wrongly.

Building the language is mostly listening for distinctions. Experts rarely say "we have two kinds of customer"; they say "for a corporate we need the mandate before we can debit". That sentence contains a distinction (corporate versus individual), a concept (mandate) and a rule (debit requires mandate), and all three belong in the model. Techniques such as event storming — putting every domain event on a wall in time order with the whole team — exist to surface exactly that kind of sentence at speed.

Once the language exists, defend it. When a developer proposes OrderProcessor, ask what the business calls that activity; if nobody can answer, the class is probably a bucket for unrelated behaviour. When an expert uses a word the code does not have, that is a modelling gap, not a naming problem.

Tactical building blocks

The tactical patterns give the language somewhere to live.

Value object. Defined entirely by its attributes, immutable, without identity. Money, IBAN, DateRange, Quantity. Two value objects with equal attributes are interchangeable. Value objects are where most domain rules can live cheaply: an amount that cannot be negative, a currency pair that must match before addition, an interval whose end cannot precede its start. Making them immutable removes an entire category of aliasing bug, and giving them behaviour keeps that behaviour out of services.

Entity. Has an identity that persists across changes of state. Two orders with identical contents are still two orders. Equality is by identifier, never by field values.

Aggregate. A cluster of entities and value objects with one entity designated the root. Everything outside references only the root, and the root is responsible for the invariants across the whole cluster. The aggregate is the unit of loading, saving and locking, which makes it the transactional consistency boundary and therefore one of the most consequential decisions in the model.

Repository. A collection-like interface for retrieving and persisting aggregate roots, expressed in domain terms. orders.findAwaitingDispatch(), not select * from orders where status = 3. The interface belongs to the domain; the implementation belongs to infrastructure.

Domain service. Behaviour that belongs to the domain but not naturally to any single entity — a transfer between two accounts, a pricing calculation over several aggregates. Use sparingly; a domain full of services and empty of behaviour is the anaemic model.

Factory. Encapsulates creation when building a valid aggregate is non-trivial. Often a static method on the root itself.

Domain event. A record of something meaningful that happened, named in the past tense: OrderDispatched, PaymentDeclined, MandateRevoked. Events are how one aggregate causes work in another without being coupled to it.

A worked model

The rules: an order may only be confirmed when it has at least one line and a valid delivery address; lines cannot be added after confirmation; the total is the sum of the lines and must not exceed the customer's credit limit, which is checked outside the aggregate.

// Value object: immutable, self-validating, behaviour included.
public record Money(BigDecimal amount, Currency currency) {
    public Money {
        if (amount.scale() > currency.getDefaultFractionDigits())
            throw new IllegalArgumentException("too many decimals for " + currency);
    }
    public Money plus(Money other) {
        if (!currency.equals(other.currency))
            throw new CurrencyMismatch(currency, other.currency);
        return new Money(amount.add(other.amount), currency);
    }
    public boolean exceeds(Money limit) { return amount.compareTo(limit.amount) > 0; }
}

// Aggregate root: the only thing outside code may hold a reference to.
public class Order {

    private final OrderId id;
    private final CustomerId customer;
    private final List<OrderLine> lines = new ArrayList<>();
    private DeliveryAddress address;
    private OrderStatus status = OrderStatus.DRAFT;
    private final List<DomainEvent> events = new ArrayList<>();

    public void addLine(Sku sku, int quantity, Money unitPrice) {
        if (status != OrderStatus.DRAFT)
            throw new OrderAlreadyConfirmed(id);          // invariant, enforced here and nowhere else
        lines.stream().filter(l -> l.sku().equals(sku)).findFirst()
             .ifPresentOrElse(l -> l.increaseBy(quantity),
                              () -> lines.add(new OrderLine(sku, quantity, unitPrice)));
    }

    public void confirm(Clock clock) {
        if (lines.isEmpty())  throw new EmptyOrder(id);
        if (address == null)  throw new MissingDeliveryAddress(id);
        status = OrderStatus.CONFIRMED;
        events.add(new OrderConfirmed(id, customer, total(), clock.instant()));
    }

    public Money total() {
        return lines.stream().map(OrderLine::lineTotal)
                    .reduce(Money::plus).orElseThrow();
    }

    public List<DomainEvent> pullEvents() {          // drained by the application layer after save
        List<DomainEvent> drained = List.copyOf(events);
        events.clear();
        return drained;
    }
}

// Repository interface: domain vocabulary, no persistence technology.
public interface Orders {
    Optional<Order> byId(OrderId id);
    List<Order> awaitingDispatch(DeliveryZone zone);
    void save(Order order);
}

Three things are worth noticing. Every rule about an order lives inside Order, so there is one place to read and one place to change. Nothing outside can reach an OrderLine directly, so no caller can bypass addLine. And there is not a single framework annotation in the domain — persistence mapping lives in an infrastructure adapter, which is what the next section is about.

The credit-limit check is deliberately absent from the aggregate. It needs the customer aggregate, and reaching across aggregates inside one transaction is how aggregates grow until every order in the system contends on one customer row. Instead the application layer loads both, or the check happens asynchronously in response to OrderConfirmed with a compensating cancellation if it fails — the saga shape discussed in distributed transactions and consistency.

Bounded contexts

A single model that covers an entire enterprise collapses under its own weight, because the same word means different things to different departments. To sales, a "customer" is a prospect with a pipeline stage. To billing, a customer is a legal entity with a tax identifier and a payment method. To support, a customer is whoever is on the phone. Forcing one Customer class to serve all three produces a type with sixty fields, most of them null, and rules that contradict each other.

A bounded context is an explicit boundary inside which one model and one language apply consistently. Outside it, the same words may mean something else, and that is fine as long as the boundary is explicit and translation happens at it. A context has a team, a codebase, its own storage and its own vocabulary.

This makes bounded contexts the best available guide to service boundaries. A context boundary is where the language changes, which is exactly where an interface should be, so contexts and services usually map one to one — though a context may be implemented as several services, and in a modular monolith it is simply an enforced module.

Related is the distinction between kinds of subdomain, which tells you where to spend effort:

SubdomainWhat it isInvestment
CoreWhat differentiates the businessBest people, deepest modelling, build in-house
SupportingNecessary, specific to you, not differentiatingBuild simply, keep it boring
GenericSolved problems: identity, accounting, emailBuy or use an existing service

Applying full tactical DDD to a generic subdomain is a common and expensive mistake. Nobody wins by hand-modelling a currency conversion table.

Context maps

Once you have several contexts you have relationships, and the relationship pattern determines how much pain each change causes. Naming them makes an implicit power structure explicit.

  • Partnership — two teams succeed or fail together and coordinate releases deliberately.
  • Shared kernel — a small model deliberately shared by two contexts, changeable only by agreement. Keep it tiny; it couples release cycles.
  • Customer/supplier — the downstream team is a paying customer whose requirements enter the upstream team's backlog.
  • Conformist — downstream adopts the upstream model as-is because it has no influence. Cheap, and it imports upstream's design decisions wholesale.
  • Anti-corruption layer (ACL) — downstream builds a translation layer so that the upstream model never enters its own. The most valuable pattern when integrating with a legacy system or an external provider.
  • Open host service — upstream publishes a deliberately designed protocol for many consumers rather than bespoke integrations.
  • Published language — a well-documented shared interchange format, often paired with an open host service.
  • Separate ways — the contexts do not integrate at all, because the cost exceeds the benefit.

The anti-corruption layer deserves emphasis. When a service consumes a partner API or a system of record whose model is nothing like yours, translating at the edge — one adapter that maps their CUST_REC_TYPE_3 into your Customer — keeps the foreign model from spreading through your code. Without it, in a year, the partner's field names are in your database.

Hexagonal layering

The tactical patterns only survive if infrastructure cannot creep into the domain, and that is a dependency-direction problem. Hexagonal architecture — equivalently ports and adapters, or the onion and clean architectures — states the rule plainly: dependencies point inward, toward the domain, and the domain depends on nothing.

  • Domain — entities, value objects, aggregates, domain services, domain events, repository interfaces. No framework imports, no SQL, no HTTP, no JSON.
  • Application — use cases that orchestrate the domain: load an aggregate, call a method, save, publish events, manage the transaction boundary. Thin by design.
  • Adapters — the outside world in both directions. Driving adapters (REST controllers, message listeners, scheduled jobs) call the application; driven adapters (JPA repositories, HTTP clients, broker publishers) implement interfaces the domain declared.
// Application layer: one use case, transaction boundary, no business rules of its own.
@Service
class ConfirmOrder {
    private final Orders orders;              // domain port
    private final DomainEventPublisher publisher;

    @Transactional
    public void handle(OrderId id) {
        Order order = orders.byId(id).orElseThrow(() -> new UnknownOrder(id));
        order.confirm(Clock.systemUTC());     // the rule lives in the aggregate
        orders.save(order);
        publisher.publishAll(order.pullEvents());
    }
}

The practical payoff is testability. The domain has no container to start and no database to seed, so its tests run in milliseconds and read like specifications of the business rules. The layering ideas here connect directly to layered and n-tier architecture, and the dependency inversion that makes it work is the same mechanism described in Spring's IoC container.

One pragmatic note about persistence. Purists keep JPA annotations out of the domain by maintaining separate persistence entities and mapping between them; that is genuinely cleaner and genuinely more code. Annotating the domain classes directly is a defensible compromise for a team that will not otherwise maintain the mapping, provided the model's design is driven by the domain and not by what maps conveniently. What is not defensible is letting lazy-loading behaviour, cascade settings or generated identifiers decide your aggregate boundaries.

Common mistakes

Tactical patterns without strategic design. Adding @ValueObject everywhere in one enormous shared model produces ceremony without benefit. Contexts first.

The god aggregate. A Customer aggregate containing orders, invoices and tickets means every operation locks the customer. Split by invariant, connect by event.

Repositories returning rows. A repository that exposes a query language, projections and pagination over arbitrary fields is a DAO with a fashionable name. Query needs that do not fit are legitimate — serve them with a separate read model rather than by distorting the aggregate.

Publishing internal events as the public contract. Every consumer becomes coupled to your field names. Translate domain events into deliberately designed integration events at the boundary.

Modelling in isolation. A model built by developers from a specification document, without a domain expert in the room, encodes the specification's ambiguities. The language is built in conversation or it is not built at all.

Key takeaways

  • The ubiquitous language is the core practice: one vocabulary in conversation, documentation and code, revised whenever understanding changes.
  • Value objects carry rules cheaply, entities carry identity, and aggregates define the consistency boundary — keep them small and change one per transaction.
  • Bounded contexts make it legitimate for the same word to mean different things in different parts of a business, and they are the most reliable guide to service boundaries.
  • A context map names each relationship — conformist, customer/supplier, anti-corruption layer — and makes coupling and power visible before it hurts.
  • Spend modelling effort on the core subdomain; buy the generic and keep the supporting subdomains boring.
  • Hexagonal layering keeps frameworks out of the domain, which is what makes the model testable in milliseconds and durable across technology changes.

Sources and further reading

Frequently asked questions

Does DDD require microservices?
Not at all. DDD predates microservices and applies perfectly well inside a single deployable, where bounded contexts become enforced modules. The relationship runs the other way: if you are splitting a system into services, bounded contexts are the best available guide to where the seams belong, because a context boundary is exactly where the language and the model change.
How big should an aggregate be?
As small as the invariants allow. An aggregate is a consistency boundary loaded and saved as a unit, so a large one means large transactions and contention on the root. If a rule genuinely requires two entities to change together atomically, they belong in one aggregate; if the rule can tolerate a short delay, split them and connect the pieces with a domain event.
Is an anaemic domain model always wrong?
It is wrong when the domain has interesting rules and they end up scattered across services and controllers instead of living with the data they constrain. For genuinely simple CRUD — reference data, configuration screens — a thin model with a service layer is appropriate and DDD ceremony would be waste. Apply the tactical patterns to the complex core, not uniformly.
What is the difference between a domain event and an integration event?
A domain event describes something that happened inside one bounded context, uses that context's language, and may carry internal identifiers. An integration event is a deliberately designed public message for other contexts, with a stable schema and a vocabulary meaningful outside. Publishing your domain events directly onto the shared broker couples every consumer to your internal model; translate at the boundary.