Take a lending platform that has grown for fifteen years: one LOAN table and one Loan class, read and written by origination, servicing, collections and the month-end ledger run. A change to early repayment now needs four teams to agree. Domain-driven design gives that system a way forward: find where the meaning of "loan" changes, draw the boundaries there, and move the code behind them one part at a time.

What is domain-driven design, and why it matters most for legacy systems

Domain-driven design (DDD) is the approach Eric Evans set out in Domain-Driven Design: Tackling Complexity in the Heart of Software (Addison-Wesley, 2003): model the software on the business it serves, in the language of the people who run that business, and split a large system into parts that each keep one consistent model.

It comes in two halves.

Strategic design decides where the boundaries go: subdomains, bounded contexts and the relationships between them.

Tactical design shapes the code inside one boundary: aggregates, entities, value objects, domain events.

Most DDD writing starts from a blank page. A legacy system starts from the opposite end, because the model already exists, implicit in the tables and classes, and it is usually one model that tried to serve every department at once.

That is exactly what DDD warns against.

Martin Fowler quotes Evans: total unification of the domain model for a large system will not be feasible or cost-effective, and so DDD divides up a large system into Bounded Contexts, each of which can have a unified model (Fowler, Bounded Context). On a legacy system, DDD is therefore discovery first: finding the contexts that were always there and that the code blurred together.

The rest of this guide follows the lending platform from the first workshop to the first extracted module. The system is illustrative, a composite of the kind we meet in financial services; the techniques and the code are what we use.

Event storming the system you already have

Discovery starts in a workshop, before anyone opens the code, because the people who run the business know where its parts meet better than the code shows.

Event storming is a workshop format for mapping a business process as a sequence of domain events, written in the past tense on sticky notes along a wall: Application submitted, Loan approved, Funds disbursed, Instalment due, Payment missed. Alberto Brandolini came up with the EventStorming idea in 2013 (EventStorming), and it runs at three levels: big picture, process design and software design.

On a legacy system, run the big-picture level first, with two groups in the room: the people who run the business process and the engineers who know the code. The business side puts up the events. The engineers add, under each event, where it happens in the system today: the screen, the batch job, the stored procedure.

The wall that results is the first honest map of what the system does, including the steps that live in a nightly job nobody has opened for years.

The first sign of a boundary on that wall is a change of language. Capital One's engineers put it this way: If the language changes between events then that is a sign that you have crossed into a different bounded context (Capital One Tech). On the lending wall, the events up to Loan approved talk about applicants and decisions, the events after Funds disbursed about balances and schedules, and from Payment missed onwards about cases and contact history.

The second sign is the hotspot: a sticky note where the room disagrees, or where the engineers say "that part is in the old loan table and three jobs write to it". Hotspots are where the migration will hurt, and they go on the plan before any code moves.

Subdomains: what to build, what to buy, what to leave

The event wall also shows which parts of the business deserve the most engineering. DDD splits a domain into subdomains of three kinds. The core domain covers the parts of the domain which have the greatest potential for business differentiation or strategic significance (DDD Crew). Supporting subdomains are specific to the business but do not set it apart. Generic subdomains are the same in every company.

SubdomainKindLending exampleWhat to do with it
ServicingCoreRepayment rules, restructuring, early repayment pricingBuild, with the most careful modeling and the best engineers
OriginationSupportingApplication intake, document checks, the credit decision workflowBuild simply, or configure a product
CollectionsSupportingArrears cases, contact strategy, payment plansBuild simply, or configure a product
LedgerGenericDouble-entry accounting, period closeBuy, and conform to its model
Identity, notificationsGenericLogin, email and SMSBuy or use a platform service

Which subdomain is core depends on the business: a lender that competes on decision speed would put origination there instead. The classification decides where modernization money goes. The core domain gets new code and tactical DDD; generic subdomains get a product, and the legacy code that implemented them is retired rather than rewritten.

Bounded contexts and the context map

Subdomains say where the business divides. The next step is to draw the same lines through the software, which is what bounded contexts do. A bounded context is the part of the system inside which one model, and one meaning of each term, holds. On the lending platform, "loan" has four meanings, and each one is a context:

The word loan means four different things in four bounded contexts of a lending platform. In origination a loan is an application: applicant and income, amount requested, documents and the credit decision. In servicing, the core domain, a loan is an account: balance and rate, repayment schedule, payments received and early repayment. In collections a loan is a case: days past due, contact history, payment plan and write-off proposal. In the ledger a loan is a set of entries: principal, accrued interest, fees, debits and credits.ONE WORD, FOUR MODELS: “LOAN” IN EACH BOUNDED CONTEXTOriginationA loan is an applicationApplicant, incomeAmount requestedDocumentsCredit decisionServicingA loan is an accountBalance, rateRepayment schedulePayments receivedEarly repaymentCollectionsA loan is a caseDays past dueContact historyPayment planWrite-off proposalLedgerA loan is entriesPrincipalAccrued interestFeesDebits and credits
The same word in four bounded contexts of an illustrative lending platform. One shared Loan class has to carry all four models at once.

In the legacy code, those four models live in one class and one table, which is why every change needs four teams. Separating them does not mean four copies of the same data. Each context keeps only what its model needs and refers to the others by identifier: Collections needs the days past due and the contact history; the documents from the original application stay in Origination.

The context map records how the contexts relate. The DDD Crew's reference lists nine context map patterns and three different team relationships (DDD Crew, context mapping); a migration uses a handful of them most:

  • Anti-corruption layer: a translating layer that keeps another model, typically the legacy one, out of yours.
  • Open host service and published language: a context exposes a stable API or a set of events in a documented format, such as LoanApproved, that other contexts consume.
  • Conformist: the downstream context adopts the upstream model as it is, the usual relationship with a bought product such as an accounting package.
  • Shared kernel: two contexts share a small part of the model; the DDD Crew's advice is Keep this kernel small.
  • Separate ways: no integration at all, when duplicating a little is cheaper than coupling.

For the lending platform during the migration, the map looks like this:

Context map of an illustrative lending platform during its migration. Origination, a supporting subdomain, publishes a LoanApproved event to Servicing, the core domain, written as new code. Servicing publishes a PaymentMissed event to Collections, another supporting subdomain. Origination calls an external credit bureau API through an anti-corruption layer that translates the bureau's codes. Servicing reads the legacy loan core, the old monolith, through an anti-corruption layer that reads its old tables. Collections posts to a bought accounting package in that package's own format, a conformist relationship.CONTEXT MAP OF THE LENDING PLATFORM DURING THE MIGRATIONOriginationsupporting subdomainServicingcore domain, new codeCollectionssupporting subdomainCredit bureauexternal APILegacy loan corethe old monolithAccounting packagegeneric, boughtLoanApprovedPaymentMissedACLACLconformisttranslates codesreads old tablescore domainsupportinglegacyexternal or boughtACL: anti-corruption layer
Context map of the illustrative lending platform during the migration: new contexts talk through published events, and anti-corruption layers keep the legacy core and the credit bureau's codes out of the new models.

Boundaries pay off long after the first migration.

Uber, with thousands of microservices, introduced a domain-oriented architecture in 2020 that grouped them by business domain behind gateways. Its engineers reported that we were able to classify 2200 microservices into 70 domains and that platforms cut the onboarding time for a new feature by 25 to 50% (Uber Engineering, July 2020).

An anti-corruption layer around the legacy core

A context map shows where the boundaries should run. The legacy system, meanwhile, keeps taking payments every day, so the boundaries have to go into the code while it runs. The first context to move, Servicing in our example, cannot wait for the legacy core to disappear. For months it will need data that still lives in the old LOAN table. The anti-corruption layer (ACL) is how it reads that data without inheriting the old model. Microsoft's architecture guidance describes it as a facade or adapter layer between different subsystems that don't share the same semantics, and adds a rule worth keeping: focus the layer on translation and avoid placing business rules or orchestration in the layer (Azure Architecture Center).

In Java, the ACL is usually a small set of adapters behind interfaces that the new context owns. The new code depends on the interface, written in its own language; one class knows the legacy column names and status codes:

// Servicing's view of a loan, in Servicing's own language
public record LoanAccountView(LoanId id, CustomerId customer, Money balance,
                              InterestRate rate, AccountStatus status) {}

// The anti-corruption layer: the only class in Servicing that knows the legacy schema
@Component
class LegacyLoanTranslator implements LoanAccountViews {

    private final JdbcClient legacy;

    LegacyLoanTranslator(JdbcClient legacy) {
        this.legacy = legacy;
    }

    @Override
    public Optional<LoanAccountView> find(LoanId id) {
        return legacy.sql("""
                SELECT LN_NO, CUST_NO, PRIN_BAL, INT_RT, LN_STAT
                FROM LOAN WHERE LN_NO = :id""")
            .param("id", id.value())
            .query((rs, row) -> new LoanAccountView(
                new LoanId(rs.getString("LN_NO")),
                new CustomerId(rs.getString("CUST_NO")),
                Money.eur(rs.getBigDecimal("PRIN_BAL")),
                InterestRate.ofPercent(rs.getBigDecimal("INT_RT")),
                toStatus(rs.getString("LN_STAT"))))
            .optional();
    }

    // Translation only: the legacy codes mean nothing outside this class
    private static AccountStatus toStatus(String code) {
        return switch (code) {
            case "A", "R" -> AccountStatus.PERFORMING;   // active, rescheduled
            case "D"      -> AccountStatus.IN_ARREARS;
            case "W"      -> AccountStatus.WRITTEN_OFF;
            case "C"      -> AccountStatus.CLOSED;
            default -> throw new IllegalStateException("Unknown legacy loan status: " + code);
        };
    }
}

When the legacy table is finally retired, only the adapter changes. The same pattern works in the other direction, for legacy code that has to call the new context, and for external systems: Origination's ACL turns the credit bureau's response codes into Origination's own decision reasons. Microsoft also notes when the pattern is not worth it: when the new and legacy systems have no significant semantic differences. A context that conforms to the old model gains nothing from a translator.

Aggregates in the core domain

Inside the core context, tactical DDD shapes the code.

With the legacy data held behind the anti-corruption layer, Servicing can finally have a model built around its own rules. The central building block is the aggregate: a cluster of domain objects that can be treated as a single unit, loaded and saved as a whole, with one rule that matters more than the rest: Transactions should not cross aggregate boundaries (Fowler, DDD Aggregate).

In Servicing, a loan account and its repayment schedule form one aggregate. A payment must update the schedule and the balance together, so they belong in one transaction. The customer is a separate aggregate, referenced by its identifier. Anything that has to happen in another context, such as opening an arrears case, is announced as a domain event and handled later in that context's own transaction:

// Aggregate root of the Servicing context (simplified)
public class LoanAccount extends AbstractAggregateRoot<LoanAccount> {

    private LoanId id;
    private CustomerId customer;              // another aggregate: referenced by id, never loaded
    private Money balance;
    private AccountStatus status;
    private List<Instalment> schedule;        // entities that only change through the root

    public void applyPayment(Payment payment) {
        if (status == AccountStatus.CLOSED) {
            throw new IllegalStateException("Payment on a closed account " + id);
        }
        Money left = payment.amount();
        for (Instalment due : unpaidOldestFirst()) {
            left = due.settle(left);          // schedule and balance change in one transaction
        }
        balance = balance.minus(payment.amount().minus(left));
        if (balance.isZero()) {
            status = AccountStatus.CLOSED;
            registerEvent(new LoanRepaid(id, payment.receivedOn()));
        }
    }

    public void recordMissedInstalment(Instalment due, LocalDate today) {
        status = AccountStatus.IN_ARREARS;
        registerEvent(new PaymentMissed(id, due.number(), due.amount(), today));
    }
}

public record PaymentMissed(LoanId loan, int instalment, Money amount, LocalDate on) {}

AbstractAggregateRoot is Spring Data's base class: events registered with registerEvent are published when the repository saves the aggregate, and Collections handles PaymentMissed in its own module. The legacy Loan class, by contrast, is typically a set of getters and setters, with the rules spread across services that each read and write fields directly. Moving those rules into the aggregate is most of the tactical work, and characterization tests around the old behavior come first.

Two Java libraries make the building blocks explicit and checkable. jMolecules provides annotations and interfaces such as @ValueObject, @Entity, @Repository and AggregateRoot, and its ArchUnit rules verify the relationships between them; Spring Modulith optionally integrates with the jMolecules ArchUnit library and runs those DDD rules as part of its own verification (Spring Modulith documentation).

CQRS and event sourcing: where they pay in a legacy system

Two patterns often arrive with DDD and are easy to overuse. Both come up in almost every architecture discussion about a financial system, so it pays to know where each one earns its cost before the first workshop turns into a rewrite plan.

CQRS (command query responsibility segregation) splits the model that changes data from the model that reads it. Fowler's warning still holds: for most systems CQRS adds risky complexity, and it should only be used on specific portions of a system (a BoundedContext in DDD lingo) and not the system as a whole (Fowler, CQRS). In a legacy migration, its most useful form is modest: read models for the screens and reports that join data from several contexts. A customer statement needs Servicing's balances and Collections' payment plan; a read model kept up to date from both contexts' events serves it without either context querying the other's tables. While the data still sits in the legacy database, change data capture fills the same role: Debezium lets an application respond to all of the inserts, updates, and deletes that other apps commit to your databases (Debezium).

Event sourcing goes further: the events become the system of record, and current state is derived by replaying them. Microsoft's guidance is blunt: For most systems and most parts of a system, traditional data management is sufficient (Azure Architecture Center). A Danske Bank engineer put the same point more vividly: Using Event Sourcing for a simple CRUD-based application is like using a chainsaw instead of a butter knife to make a sandwich (Danske Bank).

Where it pays, it pays well.

LMAX's retail trading platform, built on the JVM platform, centers on a business logic processor that can handle 6 million orders per second on a single thread and runs entirely in-memory using event sourcing (Martin Fowler, 2011). Financial history, where every change has to be explained later, is the natural home of the pattern.

PatternUse it in a context whereAvoid it where
CQRS read modelsScreens and reports combine data from several contexts, or reads vastly outnumber writesOne context serves its own simple screens
CQRS with separate write and read storesWrite rules are complex and read needs differ sharplyThe domain or the business rules are simple (Microsoft's own limit for the pattern, Azure Architecture Center)
Event sourcingThe history is the product: ledgers, audit trails, positions that must be reconstructed at any past datePlain CRUD with no need for replay or historical reconstruction

On the lending platform, that puts event sourcing in at most one place, the account history inside Servicing, and CQRS read models where Servicing and Collections data meet. Origination stays a plain relational model.

A modular monolith first, then extraction where it pays

Bounded contexts do not have to become microservices.

For most legacy systems, the cheaper first step, and often the last one needed, is a modular monolith: one deployable, with each context as a module that has a public API, private internals and its own tables. In Spring Boot, Spring Modulith checks the rules in a test, rejecting cycles between modules and any reference to another module's internal packages (Spring Modulith documentation), and its Documenter generates C4 and UML component diagrams describing the relationships between the individual application modules (Spring Modulith documentation), so the context map stays in step with the code.

A context moves out into its own service only when it needs its own deployment cadence, its own scaling or its own team. Our guide to moving from a monolith to microservices covers the Spring Modulith setup, data decomposition and the transactional outbox in detail, and the strangler fig pattern guide covers routing traffic to an extracted context while the legacy core keeps serving the rest.

The ledger we built for Legerity, FastPost, which processes a billion financial transactions in under an hour, is built as a modular architecture. Modules with clear boundaries are what let a team change one part of a high-volume financial system without retesting all of it.

Domain-driven design checklist for a legacy Java system

For the lending platform, or any legacy Java system, the steps run in this order:

  1. Run a big-picture event storming session with the business and the engineers who know the code; note under each event where it happens today, and mark the hotspots.
  2. Mark where the language changes; those are the candidate bounded contexts.
  3. Classify the subdomains as core, supporting or generic, and decide build, configure or buy for each.
  4. Draw the context map as it is today, legacy core and external systems included, then as it should be after the migration.
  5. Pick the first context to move: valuable, with few inbound dependencies and clear data ownership.
  6. Put an anti-corruption layer between that context and the legacy core, with translation only.
  7. Model the core context's aggregates: one transaction per aggregate, references by identifier, domain events for everything that happens elsewhere.
  8. Enforce the module boundaries in CI with Spring Modulith or ArchUnit and jMolecules, from the first commit.
  9. Add CQRS read models where contexts' data meets; use event sourcing only where history is the product.
  10. Extract a context into its own service only when deployment, scaling or team ownership requires it.

If you want the boundaries of your own system mapped before anything moves, our microservices consulting starts with a fixed-fee architecture review: the contexts, the context map, the evidence behind each boundary, and whether your system needs services or a modular monolith, in the order to get there.