Skip to content

Domain-Driven Design for Service Boundaries

Intermediate 46 min read Part 10 of 18

Domain-driven design for complex business logic and service boundaries: ubiquitous language, bounded contexts, aggregates, events and context maps.

Summary#

Domain-driven design (DDD) is an approach to building software for complex business domains by modelling the code closely on how domain experts think and talk. Its strategic tools, namely ubiquitous language, bounded contexts and context maps, tell you where to draw the boundaries between modules or services. Its tactical tools, namely entities, value objects, aggregates and domain events, tell you how to structure the model inside each boundary so business rules stay consistent. The trade-off is effort: DDD pays off for complicated, long-lived domains and is overkill for simple CRUD.

Why It Exists#

Most software that fails does not fail because of a slow database or a wrong framework. It fails because the code stops matching the business. Developers and domain experts use different words for the same thing, or the same word for different things. Business rules end up scattered across controllers, stored procedures, front-end validation and batch jobs. Nobody can say where the rule "a premium customer's order ships free over 50 dollars" lives, so changing it means searching the whole codebase and hoping.

The boundary problem in microservices is a sharp version of the same issue. Split a system along the wrong lines and every feature crosses three services, every service needs data from every other service, and transactions that used to be one database commit become fragile sagas. Teams then blame microservices, when the real problem was that nobody understood the domain well enough to find its natural seams.

Eric Evans described the approach in "Domain-Driven Design: Tackling Complexity in the Heart of Software" (2003), often called the Blue Book. His central claims were:

  • the heart of complex software is the domain model, not the technology;
  • the model must be developed together with domain experts, in a shared language that appears directly in the code;
  • one model cannot serve a large business; models must be bounded, each valid within an explicit context, with explicit relationships between contexts.

Those ideas turned out to be exactly what microservice designers needed a decade later. A bounded context is the best single heuristic for a service boundary, and an aggregate is the best single heuristic for what must be consistent in one transaction.

How It Works#

DDD has two halves. Strategic design works at the scale of the whole business: what are the parts of the domain, which ones matter most, where are the boundaries between models, and how do they relate? Tactical design works inside one boundary: how to express the model in code with entities, value objects, aggregates, repositories and domain events. Service boundaries come mostly from strategic design; data consistency inside a service comes mostly from tactical design.

The sections below follow the order you would use them in practice: agree on language, find the subdomains and bounded contexts, map how contexts relate, then model each context with tactical patterns, and finally turn the result into service boundaries.

Ubiquitous language#

A ubiquitous language is a shared vocabulary, built by developers and domain experts together, that is used everywhere within a context: in conversations, requirement documents, diagrams, tests, and the code itself. If the shipping experts say a parcel is "manifested" when it has been assigned to a carrier's pickup list, the code has a manifest() method on a Parcel, not updateStatus(3) on a ShipmentRecord.

Why this matters:

  • Translation is where bugs hide. When experts say "cancel" and developers implement "delete", or experts distinguish "returns" from "refunds" and the code does not, the software silently does the wrong thing in edge cases.
  • The code becomes reviewable by experts. A domain expert can read if order.isEligibleForFreeShipping() and confirm the rule, but cannot review a 40-line conditional on status codes.
  • Conversations get sharper. Building the language forces questions such as "is a cancelled order the same as a rejected one?", which often reveals rules nobody had written down.

Ubiquitous language, in depth#

How to build it. The language comes from talking to domain experts about concrete scenarios, not from abstract data modelling. Useful practices:

  • Walk through real examples: "A customer orders three items; one is out of stock. What happens?" Note every noun and verb the expert uses, and every distinction they draw.
  • Keep a glossary per context, with definitions written by or approved by experts, versioned with the code.
  • Name code exactly as the experts speak: classes, methods, events, API endpoints and database tables. When the language changes, refactor the code.
  • Listen for awkwardness. If explaining a feature requires saying "well, technically in the system it's called a ticket, but it's really a booking", the model is wrong.
  • Watch for synonyms and homonyms. Two words for one concept, such as "client" and "customer", should be unified within a context. One word for two concepts, such as "order" meaning both a purchase and a sort order, should be split.

Language is bounded. A crucial point that is often missed: the ubiquitous language is ubiquitous within one bounded context, not across the whole company. "Customer" in the billing context, someone with a payment method and invoices, is legitimately different from "customer" in the support context, someone with tickets and a satisfaction score. Trying to create one enterprise-wide language and data model is the trap that sank many enterprise data-modelling projects. The next section is about drawing the lines between languages.

Event Storming. Alberto Brandolini's Event Storming, introduced in the early 2010s, is a workshop technique for building the language and discovering boundaries quickly. Developers and experts put sticky notes for domain events, things that happened, phrased in the past tense such as "Order Placed", "Payment Captured" and "Parcel Delivered", on a long timeline on a wall. Then they add the commands that cause events, the actors who issue them, policies, such as "whenever Payment Captured, then Reserve Stock", external systems and hot spots where people disagree. Within a few hours, clusters of events with their own vocabulary emerge, and those clusters are strong candidates for bounded contexts.

Subdomains: core, supporting and generic#

Before drawing model boundaries, DDD asks what the domain is made of. The domain is the area of business the software serves, such as online retail, ride hailing or insurance. It divides into subdomains, areas of business activity, and DDD classifies them by strategic value:

  • Core subdomain: what makes the business different and gives competitive advantage. For a ride-hailing company, matching riders to drivers and dynamic pricing. For a marketplace, search ranking and trust. This deserves the best engineers, the deepest modelling and custom software.
  • Supporting subdomain: necessary and specific to the business, but not a differentiator, such as driver onboarding paperwork or a merchant's catalogue tools. Build it, but simply.
  • Generic subdomain: problems every business has, solved well by others, such as authentication, email delivery, payments processing, accounting or search infrastructure. Buy or reuse them: an identity provider, a payment processor, an email service.

The classification directs effort. Teams that spend months building a custom identity system while their core pricing logic lives in a spreadsheet macro have their priorities reversed.

Bounded contexts#

A bounded context is an explicit boundary within which one model, with one ubiquitous language, applies consistently. Inside the boundary, every term has exactly one meaning, and the code, data and team that implement the model all belong to it. Outside the boundary, the same words may mean different things, and that is allowed.

The classic example is "Product" in an online retailer:

Each context has a model tailored to its job. They share an identifier, the SKU, so they can refer to the same real-world item, but not a single shared class or table. If one giant Product table carried every attribute for every context, every team's change would touch the same model, and the model would be incoherent: is "status" the catalogue's published flag, the inventory's discontinued flag or the shipping's restricted flag?

A bounded context is usually implemented as one module or one service, owned by one team, with its own data store or schema. It is the unit of model consistency, of language, of ownership and, very often, of deployment.

Bounded contexts, in depth#

Subdomain versus bounded context. The two are related but different. A subdomain is part of the problem space, the business as it exists. A bounded context is part of the solution space, a boundary in the software you build. Ideally they align one-to-one, but not always: a legacy system may implement three subdomains in one context, a big ball of mud, and a complex core subdomain may be split into several contexts as it grows.

Finding bounded contexts. Signals that you are crossing a context boundary:

  • The language changes. Different experts use different words, or the same word with a different meaning.
  • Different experts own the rules. The pricing team decides promotions; the warehouse team decides stock allocation.
  • Different rates of change. Promotions change weekly; tax rules yearly; product attributes constantly.
  • Different consistency needs. Stock reservation must be exact at checkout; recommendation data can be hours old.
  • Event Storming clusters. Groups of events and commands that refer mostly to each other, with few links to the rest.
  • Natural hand-offs in the business process. An order moves from Sales to Fulfilment to Billing, and each department takes ownership at a defined moment.

Size. There is no fixed size for a bounded context. It should be large enough to contain a coherent model and the invariants that belong together, and small enough for one team to own and understand. A common failure is making contexts too small, one per entity, which reintroduces the problems of an entity-split architecture. Another is making them too large, one "Core" context for everything, which brings back the ball of mud.

Bounded contexts and teams. Conway's law says that systems copy the communication structure of the organisation that builds them. DDD uses that deliberately: one team per context, or a few contexts per team, never one context shared by several teams. When two teams must constantly coordinate changes to one model, that is a sign the context should be split, or the teams merged. Matthew Skelton and Manuel Pais's "Team Topologies" (2019) builds on this idea with stream-aligned teams owning business-aligned slices and platform teams providing shared infrastructure.

Bounded contexts in a monolith. Contexts do not require microservices. In a modular monolith, each bounded context is a module with its own package, public interface and schema. The model boundaries, the language and the ownership are just as real; only the deployment is shared. Many teams find the contexts this way first and extract services later, where needed.

Context mapping#

A system has many bounded contexts, and they must exchange information. A context map is a diagram and a description of the bounded contexts and the relationships between them: who depends on whom, who adapts to whom, and how models are translated at each boundary. Relationships are described as upstream and downstream: the upstream context's decisions affect the downstream one, but not the other way around, like a river.

DDD names a set of relationship patterns:

  • Partnership: two contexts succeed or fail together, so their teams plan and release interdependent changes jointly.
  • Shared kernel: two contexts share a small, explicitly defined part of the model, such as a common Money type or a few core identifiers, which neither team changes without the other's agreement. Keep it tiny.
  • Customer-supplier: the upstream team (supplier) plans its work to meet the downstream team's (customer's) needs, with negotiated priorities and acceptance tests.
  • Conformist: the downstream team simply adopts the upstream model as is, because it has no influence over the upstream, such as a small team consuming a large vendor's API, and translation is not worth it.
  • Anti-corruption layer (ACL): the downstream team builds a translation layer that converts the upstream model into its own, so the upstream's concepts never leak in.
  • Open host service: the upstream offers a well-defined, documented protocol or API for many consumers, instead of building custom integrations for each.
  • Published language: a shared, documented exchange format, such as a public event schema, an industry standard such as an EDI format, or a versioned JSON or Protobuf schema, often used together with an open host service.
  • Separate ways: the contexts do not integrate at all, because integration costs more than duplication.
  • Big ball of mud: an honest label for an existing area with no clear model, which other contexts should protect themselves from, typically with an anti-corruption layer.

Context mapping, in depth#

Why the map matters. The context map makes politics and dependencies explicit. If Ordering is downstream of a Pricing team that never prioritises its requests, Ordering is in a conformist position whether anyone admits it or not, and the map shows the risk. If three contexts are partners, their release plans are coupled, and the map shows that too. Architects use the map to decide where to invest in translation layers, which APIs to stabilise as open host services, and which team relationships need to change.

Choosing a relationship. A rough guide:

SituationUsual pattern
Upstream is an external vendor or a much larger team you cannot influence, and its model is acceptableConformist
Upstream model is poor, legacy or would distort yoursAnti-corruption layer
Upstream has many consumersOpen host service plus published language
Two teams share a small, stable concept, such as MoneyShared kernel, kept tiny
Downstream needs are important to the upstream's successCustomer-supplier
Two contexts must always change togetherPartnership, or merge them
Integration costs more than duplicating a little logicSeparate ways

Integration mechanisms. The relationship patterns are about models and teams; the mechanisms are technical. Contexts integrate through synchronous APIs, such as REST or gRPC, for queries and commands needing an immediate answer, or through asynchronous domain events on a broker, for notifying others of facts. Events usually lead to looser coupling: the upstream publishes in its published language, and each downstream context translates the events into its own model, building local read models as needed. See Event-Driven Architecture.

Shared kernels are dangerous. A shared kernel is shared code, often a library, and shared code couples deployment and evolution. It is acceptable for genuinely stable concepts, such as a Money value object or ID formats, and harmful for evolving domain models. A common failure is a "common domain" library containing Customer, Order and Product classes that every service imports, which recreates the monolith's coupling across a network.

Entities and value objects#

Inside a bounded context, DDD's tactical patterns describe the building blocks of the model.

An entity is an object defined by its identity, which stays the same while its attributes change over time. A customer who changes their name and address is still the same customer; an order whose status moves from placed to shipped is still the same order. Entities have an ID, such as a customer ID or an order number, and equality is by ID: two Customer objects with the same ID represent the same customer even if one has a stale address.

A value object is an object defined only by its attributes, with no identity of its own. Two amounts of "10.00 EUR" are interchangeable; so are two identical addresses or two identical date ranges. Value objects are:

  • immutable: you never change a value object; you replace it with a new one, as you would replace the number 5 rather than mutating it;
  • compared by value: two Money objects are equal if amount and currency are equal;
  • self-validating: a Money cannot be created with a negative amount if the domain forbids it, and an EmailAddress cannot be created from an invalid string;
  • rich in behaviour: Money knows how to add another Money of the same currency, refuse to add a different currency, and round correctly.

The practical rule: make things value objects unless they need identity. Developers often model too much as entities, giving every address and price its own table row and ID, which adds needless lifecycle and update complexity.

Entities and value objects, in depth#

Primitive obsession. A common modelling smell is representing domain concepts as raw primitives: a price as a floating-point number, a currency as a string, an email as a string, a quantity as an integer that might be negative. Every function that receives them must re-validate, and nothing stops passing a price in cents where one in euros is expected. Wrapping them in value objects, such as Money, Currency, EmailAddress and Quantity, moves validation to one place and makes illegal states unrepresentable. Floating-point arithmetic for money is a bug in itself, because 0.1 plus 0.2 is not exactly 0.3 in binary floating point; Money should use integer minor units or a decimal type.

Persisting value objects. Value objects have no ID, so in a relational database they are usually stored as columns embedded in the owning entity's table, such as price_amount and price_currency on the order line, or as a JSON column for collections. Object-relational mappers support this directly, for example JPA embeddables and Entity Framework owned types. In a document database, value objects are naturally nested fields.

Identity generation. Entities need IDs, and in distributed systems it is often better for the domain to generate them up front, such as a UUID or a time-ordered ID, rather than waiting for a database auto-increment. That lets the entity exist, publish events and be referenced before it is saved. See Unique ID Generation.

Aggregates#

An aggregate is a cluster of entities and value objects that are treated as one unit for data changes. Each aggregate has one entity at its top, the aggregate root, which is the only object outside code may hold a reference to or call. All changes to anything inside the aggregate go through the root, which enforces the aggregate's invariants: business rules that must be true at the end of every transaction.

An Order aggregate, for example:

  • Root: Order, an entity with an order ID.
  • Inside: OrderLine entities, which have identity only within this order, and value objects such as Money for prices, Quantity and a ShippingAddress.
  • Invariants: the order total equals the sum of its lines; an order has at least one line; lines cannot be changed after the order is submitted; a discount cannot make the total negative.
  • References to other aggregates by ID only: the order holds a customerId, not a Customer object, and a SKU for each line, not a Product object.

The aggregate is DDD's answer to "what must be consistent immediately, in one transaction?" Everything inside one aggregate is changed atomically: you load the aggregate, call a method on its root, and save the whole aggregate in one transaction. Anything between aggregates is made consistent eventually, through domain events. This makes the aggregate the natural unit of a database transaction, of locking, of sharding and of concurrency control.

Aggregates, in depth#

Vaughn Vernon's rules. Vernon's "Implementing Domain-Driven Design" (2013) and his essays "Effective Aggregate Design" (2011) gave widely followed rules:

  1. Model true invariants in consistency boundaries. Put things in the same aggregate only if a business rule requires them to be consistent at the end of every transaction.
  2. Design small aggregates. Large aggregates load slowly, lock too much and cause concurrency conflicts. Most aggregates should be a root plus a few value objects and perhaps a few child entities.
  3. Reference other aggregates by identity, not by object reference. This keeps aggregates independent, makes boundaries obvious and lets aggregates live in different databases or services.
  4. Use eventual consistency outside the boundary. If a rule spans aggregates, such as "when an order is placed, reserve stock", use a domain event and a separate transaction.

One aggregate per transaction. The corollary of these rules is that a single transaction should modify one aggregate instance. If a use case seems to require updating two aggregates atomically, ask the domain expert whether a short delay would really be a problem. Usually it would not: if loyalty points appear a second after the order, nobody is harmed. If it really must be atomic, the two things probably belong in one aggregate.

Why small aggregates matter for scale. Consider a design where Product is an aggregate that contains all its reviews. Every new review loads and saves the whole product with thousands of reviews, and two reviews posted at the same moment conflict on the same product's version. Making Review its own aggregate, referencing the product by ID, removes the contention: reviews are written independently, and the product's average rating is updated asynchronously from ReviewPosted events. This is the same reasoning behind sharded counters and hot-key mitigations elsewhere in system design.

Concurrency control. Because an aggregate is the unit of change, it is also the unit of optimistic concurrency: store a version number on the aggregate root, and save with "update where id = ? and version = ?". If another transaction changed the aggregate in between, the update affects zero rows and the command is retried or rejected. See Concurrency Control and Database Locking.

Aggregates and storage. An aggregate maps naturally to a document in a document database, an item collection under one partition key in DynamoDB, or a root row plus child rows in one partition of a relational database. In a sharded database, the aggregate's ID is a natural shard key, since all data for one aggregate is accessed and changed together. In event-sourced systems, each aggregate has its own event stream, and its state is rebuilt by replaying that stream. See Event Sourcing and CQRS.

Invariants that span many aggregates. Some rules seem to require a huge aggregate, such as "a username must be unique among all users" or "total stock across all orders cannot exceed the warehouse quantity". Common solutions are a dedicated aggregate for the constraint, such as a Username registry keyed by username, or a StockItem aggregate per SKU that orders reserve from; a database uniqueness constraint as a pragmatic enforcement; or accepting eventual detection and compensation, where the business tolerates it, such as overselling by a few units and apologising, which airlines and retailers often do deliberately.

Repositories, domain services and factories#

Three more tactical patterns support aggregates:

  • A repository provides collection-like access to aggregates: orderRepository.get(orderId) and orderRepository.save(order). There is one repository per aggregate type, not per table, and it hides the persistence technology from the domain model.
  • A domain service holds domain logic that does not naturally belong to one entity or value object, such as "calculate the shipping cost from these parcels, the destination and the carrier contracts", or "transfer funds between two accounts". It is stateless and named in the ubiquitous language.
  • A factory encapsulates complex creation logic, building a valid aggregate from inputs, so the aggregate is never observed in an invalid state.

An application service, sometimes called a use-case handler, sits above the domain. It loads aggregates through repositories, calls their methods, saves them, and publishes the resulting events, all inside one transaction. It contains no business rules itself; those live in the domain objects.

Domain events#

A domain event records that something meaningful to domain experts has happened, named in the past tense in the ubiquitous language: OrderPlaced, PaymentCaptured, ParcelDispatched, SubscriptionCancelled. It carries the data needed to understand the fact, such as the order ID, customer ID, lines and total, plus metadata such as an event ID and a timestamp.

Domain events serve three purposes:

  1. Decoupling aggregates within a context. When an Order is placed, a policy reacts to OrderPlaced by reserving stock in a separate transaction, keeping each transaction to one aggregate.
  2. Integrating bounded contexts. Other contexts subscribe to published events, such as Fulfilment and Billing reacting to OrderPlaced, without the Ordering context knowing about them.
  3. Recording history. Events are a natural audit log, and in event-sourced systems, the system of record itself.

Domain events, in depth#

Domain events versus integration events. Many teams distinguish two kinds. Domain events are internal to a bounded context, and can be rich and change freely along with the model. Integration events, sometimes called public events, are published to other contexts in the published language, versioned and kept backward compatible, because consumers you do not control depend on them. Translating internal events into a smaller set of stable public events protects consumers from your internal refactors, and protects you from being frozen by them.

Thin versus fat events. A thin event, "Order 42 placed", forces consumers to call back for details, which couples them to your API and your availability. A fat event carries the data consumers need, the lines, totals and customer ID, letting them act without calling back. Fat events are usually preferred for integration, with care not to include data that consumers should not see, such as personal data beyond what they need.

Publishing reliably. An aggregate's state change and its event must be published together: if the order is saved but OrderPlaced is lost, Billing never invoices. Writing to the database and to a broker separately is the dual-write problem. The standard solution is the transactional outbox: the application service writes the aggregate and the event into an outbox table in the same database transaction, and a relay or change data capture process publishes outbox rows to the broker. Consumers must be idempotent, because the relay may publish an event more than once. See Change Data Capture and the Outbox Pattern.

Events and process managers. A business process that spans contexts, such as order to payment to fulfilment, can be choreographed, with each context reacting to the previous one's events, or managed by a process manager, a component that listens for events, tracks the state of the process and sends the next commands. Process managers are DDD's term for what microservice literature calls saga orchestrators. See Distributed Transactions: 2PC, Sagas and Outbox.

Event naming is modelling. Events named after database operations, such as OrderUpdated or RowChanged, carry no business meaning and force consumers to diff the data. Events named after domain facts, such as OrderShippingAddressCorrected or OrderCancelledByCustomer, say exactly what happened and why, and consumers can react precisely. Choosing event names is a good test of whether the ubiquitous language is rich enough.

Anti-corruption layer#

An anti-corruption layer (ACL) is a translation layer that a downstream context builds between itself and an upstream system whose model it does not want to adopt. The ACL calls the upstream system, or consumes its messages, and translates its concepts, formats and quirks into the downstream context's own model, so nothing from the upstream model "corrupts" the clean model inside.

Typical cases:

  • Legacy systems: a 25-year-old warehouse system that represents a shipment as a fixed-width record with status codes 1 to 17 and a free-text notes field used for five different purposes.
  • External vendors: a payment processor whose API uses "charges", "intents" and "sources", while your Billing context speaks of "payments" and "settlements".
  • Big balls of mud inside your own company, which you cannot fix yet but must integrate with.
  • Migrations: during a strangler-fig migration, the new service uses an ACL to talk to the monolith, so the new model is not shaped by the old one.

Anti-corruption layer, in depth#

Structure. Evans described an ACL as typically made of three parts: a facade that offers a simplified interface to the upstream system, adapters that handle the technical connection, such as SOAP calls, file drops or queue messages, and translators that convert data and concepts between the two models. In hexagonal architecture terms, the downstream context defines a port, an interface in its own language such as WarehouseGateway.requestPickup(shipment), and the ACL is the adapter that implements it against the legacy system.

What translation involves. Translation is rarely just renaming fields. It often requires:

  • Mapping codes to concepts: legacy status 7 means "picked" unless field 23 is "R", in which case it means "returned to shelf".
  • Splitting and merging: one legacy record becomes a Shipment and several Parcels, or several legacy calls combine into one domain operation.
  • Filling gaps: deriving values the upstream does not provide, such as computing a delivery estimate from carrier and region.
  • Handling errors and quirks: retries, timeouts, idempotency for an upstream that does not support it, and normalising inconsistent error formats.
  • Caching and buffering: shielding the downstream from a slow or unreliable upstream.

Where the ACL runs. For a module in a monolith, the ACL is a package inside the downstream module. For services, it can be a set of classes inside the downstream service, or a separate small service when several downstream contexts need the same translation, or when the upstream needs special connectivity, such as access to a mainframe network. A separate ACL service also isolates the downstream from the upstream's outages, by queueing requests.

Costs. An ACL is code to write, test and maintain, and it adds a hop and latency. It is worth it when the upstream model is genuinely poor, unstable or foreign to your domain, or when you plan to replace the upstream, since the ACL becomes the seam for the replacement. It is not worth it when the upstream model is good and stable; then a conformist relationship is simpler.

ACLs in migrations. During a strangler-fig migration, an ACL in the new service talks to the monolith's API or database, so the new service's model is designed for the future and the translation absorbs the past. When the monolith's functionality is finally removed, you delete or replace the ACL, and nothing inside the new model needs to change. The ACL is what makes the migration incremental at the model level, just as the routing facade makes it incremental at the traffic level.

Using DDD to find service boundaries#

DDD provides the most reliable method for deciding where services, or modules, should begin and end. The core heuristics:

  • A bounded context is the primary candidate for a service, or for a small group of services owned by one team. Inside the context, the model and language are consistent; across contexts, they may differ, and the integration is explicit.
  • An aggregate is the smallest unit you can safely split out. Never split an aggregate across services, because its invariants need one transaction. A service usually contains several aggregates of one context.
  • Domain events are the integration contract between services, published in a stable published language.
  • The context map is the dependency map between services and teams, showing which relationships need translation layers, stable APIs or close collaboration.
  • Subdomain type guides investment: build core contexts in-house with your strongest team; keep supporting ones simple; buy generic ones.

A practical process:

  1. Run an Event Storming workshop, or a similar collaborative modelling session, covering the main business flows end to end.
  2. Cluster the events and commands into areas with their own language and experts. Mark pivotal events where responsibility passes from one area to another, such as OrderPlaced handing over from Sales to Fulfilment.
  3. Name candidate bounded contexts and write a short purpose statement for each, along with its glossary.
  4. Classify each as core, supporting or generic, and decide build, buy or simplify.
  5. Identify aggregates and invariants inside each context, to check that no invariant spans two contexts. If one does, move the boundary.
  6. Draw the context map: upstream and downstream, relationship patterns, events and APIs exchanged.
  7. Assign team ownership: each context to one team.
  8. Decide deployment: modules in a monolith first, or separate services where scaling, isolation or independence demands it.
  9. Revisit: boundaries evolve as understanding grows; re-run the analysis when features keep crossing boundaries.

Using DDD to find service boundaries, in depth#

A worked example: a food delivery platform. Suppose you are designing a food delivery app that connects customers, restaurants and couriers. An Event Storming session over the order flow might produce, in time order:

  • Customer Registered, Address Added, Restaurant Searched, Menu Viewed;
  • Cart Item Added, Order Placed, Payment Authorised;
  • Order Accepted by Restaurant, Order Rejected by Restaurant, Preparation Started, Order Ready for Pickup;
  • Courier Offered Job, Courier Accepted Job, Courier Arrived at Restaurant, Order Picked Up, Order Delivered;
  • Payment Captured, Restaurant Payout Scheduled, Courier Earnings Credited;
  • Rating Submitted, Refund Requested, Refund Issued.

Clustering by language and experts suggests these contexts:

Bounded contextKey languageMain aggregatesSubdomain type
Restaurant catalogueRestaurant, menu, item, option, opening hoursRestaurant, MenuSupporting
OrderingCart, order, line, order statusCart, OrderCore
Kitchen operationsTicket, preparation, ready timeKitchenTicketSupporting
DispatchJob, offer, courier, route, ETADeliveryJob, CourierShiftCore
PaymentsAuthorisation, capture, refundPaymentGeneric, via a processor
Payouts and earningsPayout, statement, earning, adjustmentRestaurantLedger, CourierLedgerSupporting
Customer accountsCustomer, address, preferenceCustomerGeneric or supporting
Ratings and supportRating, complaint, refund requestRating, SupportCaseSupporting

Several modelling decisions follow from the language:

  • "Order" means different things. In Ordering it is a purchase with lines and prices. In Kitchen operations it is a ticket with items to cook and a ready time. In Dispatch it is a delivery job with pickup and drop-off locations. Each context has its own model, linked by the order ID.
  • Dispatch is core. Matching couriers to jobs quickly and efficiently is where the business wins or loses, so it gets a dedicated team, custom algorithms and the most careful model. It also has very different scaling needs, with frequent location updates and geospatial queries, a good reason for it to be a separate service. See Geospatial Indexing and Proximity Search.
  • Payments is generic. It integrates with an external processor through an anti-corruption layer that translates the processor's charges and intents into Payment aggregates.
  • Invariants stay within contexts. "An order's total equals the sum of its lines plus fees" lives in the Order aggregate. "A courier has at most one active job" lives in the CourierShift aggregate in Dispatch. "A restaurant's payout equals its orders minus commission and refunds" lives in the RestaurantLedger in Payouts.
  • Cross-context rules use events. OrderPlaced leads to PaymentAuthorised; OrderAcceptedByRestaurant leads Dispatch to create a DeliveryJob; OrderDelivered leads Payments to capture and Payouts to record earnings.

The resulting services would be, at first, perhaps five or six, one per core or substantial context, with smaller contexts such as Ratings living as modules inside a larger service until they need independence.

Heuristics beyond the basics. Experienced practitioners use additional checks:

  • The "pivotal event" heuristic: events where responsibility passes between departments, such as OrderPlaced or OrderPickedUp, mark boundaries.
  • The "who decides" heuristic: if two rules are decided by different experts, they likely belong in different contexts.
  • The "change together" heuristic: features that would change together belong together. Look at past change requests.
  • The "data needed to decide" heuristic: a context should own the data it needs to make its decisions. If a context must ask another for data on every decision, either the boundary is wrong or it should hold a replicated read model.
  • The "linguistic boundary" heuristic: where the meaning of a term changes, there is a boundary.

Boundaries evolve. Initial boundaries are hypotheses. As the business changes, a context may need to split, such as Dispatch splitting into Courier Management and Job Matching as the team grows, or merge, such as two contexts that always change together. Keeping contexts as modules within one deployable for as long as possible makes these corrections cheap. See Monolith vs Microservices.

DDD in a system design interview. You rarely have time for full DDD in an interview, but its ideas make designs sharper. When you list the core entities, group them by context. When you split services, justify the split by different language, different owners, different scaling or consistency needs. When asked how services stay consistent, answer with aggregates, events and the outbox. When integrating a third party, mention an anti-corruption layer.

When to Use It#

Use DDD, at least its strategic parts, when:

  • the domain has complex, evolving business rules, such as insurance underwriting, logistics, trading, healthcare, lending or marketplace operations, where getting the rules right is the main difficulty;
  • the system is long-lived, so the cost of modelling is repaid over years of change;
  • domain experts are available and willing to collaborate;
  • you are splitting a monolith or designing services, and need defensible boundaries;
  • multiple teams must work on one system and need clear ownership;
  • you are integrating legacy or external systems whose models must not leak into new code.

Strategic DDD, meaning language, contexts and maps, is useful almost everywhere boundaries matter. Tactical DDD, meaning rich aggregates, value objects and events, is most valuable in core subdomains with real rules.

When NOT to Use It#

  • Simple CRUD applications, such as an admin panel over a few tables or a content site, where there are few rules; a plain data model and framework conventions are faster and clearer.
  • Generic subdomains you should buy rather than build, such as authentication, email or accounting.
  • Purely technical systems with little business logic, such as a log pipeline, a cache or a proxy, where the "domain" is infrastructure.
  • Short-lived prototypes where learning speed matters more than model quality.
  • When domain experts are unavailable; DDD without experts becomes developers inventing a vocabulary and calling it ubiquitous.
  • As a ritual: applying every tactical pattern to every class, with factories, repositories and domain services for trivial logic, adds ceremony without value.

How to Implement It#

  1. Start with the business, not the code. Run collaborative modelling sessions, such as Event Storming or domain storytelling, with domain experts on the main flows.
  2. Build a glossary per area, and agree on terms; resolve synonyms and homonyms.
  3. Identify subdomains and classify them as core, supporting or generic, to decide where to invest.
  4. Define bounded contexts, each with a purpose, a glossary, an owning team and a list of the decisions it makes.
  5. Draw the context map: relationships, upstream and downstream, published events and APIs, anti-corruption layers.
  6. Model each core context tactically: aggregates with explicit invariants, value objects for concepts without identity, domain events for facts that others care about.
  7. Implement the architecture around the model: ports and adapters so the domain does not depend on frameworks, repositories per aggregate, application services as use-case handlers, and an outbox for events.
  8. Enforce the boundaries: separate modules or services, separate schemas, and integration only through public APIs and events.
  9. Keep refining: refactor the model as the language evolves, and adjust boundaries when features keep crossing them.

A small Order aggregate in TypeScript, with a value object, invariants and a domain event:

class Money {
  private constructor(readonly cents: number, readonly currency: string) {}
  static of(cents: number, currency: string) {
    if (!Number.isInteger(cents) || cents < 0) throw new Error("invalid amount");
    return new Money(cents, currency);
  }
  add(o: Money) {
    if (o.currency !== this.currency) throw new Error("currency mismatch");
    return new Money(this.cents + o.cents, this.currency);
  }
}
 
type OrderPlaced = { type: "OrderPlaced"; orderId: string; customerId: string; total: Money };
 
class Order {                                   // aggregate root
  private lines: { sku: string; qty: number; price: Money }[] = [];
  private status: "DRAFT" | "PLACED" = "DRAFT";
  readonly events: OrderPlaced[] = [];
  constructor(readonly id: string, readonly customerId: string, private currency: string) {}
 
  addLine(sku: string, qty: number, price: Money) {
    if (this.status !== "DRAFT") throw new Error("order already placed");
    if (qty <= 0) throw new Error("quantity must be positive");
    this.lines.push({ sku, qty, price });
  }
  total(): Money {
    return this.lines.reduce((t, l) => t.add(Money.of(l.price.cents * l.qty, l.price.currency)),
                             Money.of(0, this.currency));
  }
  place() {
    if (this.lines.length === 0) throw new Error("order needs at least one line");
    this.status = "PLACED";
    this.events.push({ type: "OrderPlaced", orderId: this.id, customerId: this.customerId, total: this.total() });
  }
}
// Application service: load via repository, call place(), save order and events in one transaction (outbox).
TechnologyFits when
Event Storming with a wall or Miro, domain storytellingDiscovering language, events and context boundaries with experts
Context Mapper, the DDD Crew bounded context canvasDocumenting contexts and context maps
Axon Framework (Java), EventFlow and Marten (.NET)Aggregates, events and event sourcing with framework support
Spring Modulith, ArchUnit, Packwerk, Nx boundariesEnforcing bounded-context modules inside a monolith
Kafka, RabbitMQ, EventBridge, SNS and SQSPublishing integration events between contexts
Debezium and transactional outbox librariesReliable event publishing from aggregates
Avro, Protobuf, JSON Schema with a schema registryPublished languages for events and APIs
Temporal, AWS Step FunctionsProcess managers and sagas spanning contexts

Trade-offs#

OptionProsConsPick when
Full DDD, strategic plus tacticalModel matches the business; rules are explicit and testable; clear boundariesNeeds expert time and modelling skill; more code and conceptsComplex core subdomains that will live for years
Strategic DDD onlyGood boundaries and language at low cost; works with any code styleLogic inside contexts may still be messyMost multi-team systems; supporting subdomains
Transaction script or CRUDFastest to write; easy to follow for simple flowsRules scatter and duplicate as complexity growsSimple subdomains, admin tools, prototypes
One enterprise-wide modelOne schema, no translationHuge, ambiguous, slow to change; every team couples to itAlmost never; small single-team systems at most
Shared kernel between contextsNo translation for the shared part; consistentJoint ownership; every change needs both teamsTwo closely cooperating teams, a tiny stable shared model
Anti-corruption layerProtects your model; isolates legacy and vendorsExtra code and latency; must evolve with upstreamIntegrating legacy or third-party models
ConformistNo translation costUpstream's model and its quirks leak inUpstream's model is good, or you have no leverage and low stakes
Large aggregatesRules enforced in one transactionContention, big loads, lock conflictsRarely; only when the invariant is real and traffic is low
Small aggregates plus eventual consistencyScale, low contentionCross-aggregate rules need events, sagas and compensationThe default for most designs

Common Pitfalls#

  • The anemic domain model. Entities are bags of getters and setters, and all logic lives in "service" classes that manipulate them. Martin Fowler named this anti-pattern in 2003. The model then cannot protect its invariants, because anything can set any field. Put behaviour, such as order.place(), on the aggregate.
  • Giant aggregates. Putting a customer, all their orders and all their addresses in one aggregate causes huge loads, lost-update conflicts and lock contention. Design small aggregates around true invariants, and reference other aggregates by ID.
  • One model for the whole enterprise. A single canonical "Customer" or "Product" that serves sales, billing, shipping and support satisfies nobody and couples everyone. Accept several models with translation.
  • Bounded contexts drawn around technical layers or entities. A "Customer Service" that just does CRUD on the customer table is an entity service; every business flow then crosses several services. Draw contexts around capabilities and language.
  • Shared kernel abuse. A "common" library of domain classes shared by all services grows until it is a distributed monolith in disguise; every change ripples everywhere. Keep shared code to technical utilities and published event schemas.
  • Tactical-only DDD. Adopting repositories, factories and value objects without the strategic work gives ceremony without better boundaries, which is where most of DDD's value lies.
  • Modelling without experts. Developers inventing the language produce a model that matches the database, not the business.
  • Leaking internal events. Publishing every fine-grained domain event as an integration event couples other contexts to your internal model. Publish a stable, deliberately designed set.
  • Treating the first boundaries as final. Early contexts are guesses; revisit them as you learn, and keep them cheap to change by starting as modules.
  • Over-engineering simple subdomains. Full tactical DDD for a settings screen is waste; use CRUD where it fits.

Real-World Examples#

These illustrate typical uses; details are summarised from public talks and posts, and practices vary across teams.

  • Event Storming in many companies. Alberto Brandolini's technique is widely used in industry workshops to discover domain events and boundaries before splitting systems; the DDD Crew's open-source templates, such as the bounded context canvas, come from this community.
  • Uber's Domain-Oriented Microservice Architecture (DOMA). Uber's 2020 engineering post described grouping thousands of microservices into domains, then into layers, with a single gateway per domain and extension points, to reduce coupling. It is DDD's bounded-context thinking applied at very large scale.
  • Shopify's modular monolith. Shopify organised its Rails monolith into components around business areas, such as orders, billing and shipping, with enforced boundaries using its Packwerk tool, an example of bounded contexts inside one deployable.
  • Typical scenario: an insurance company. Policy administration, claims, underwriting and billing each have rich, different meanings of "policy" and "customer"; teams that model them as separate contexts with translation, and an ACL around the decades-old mainframe, can replace pieces of the legacy system one context at a time.
  • Typical scenario: an e-commerce migration. A team splitting a monolith runs Event Storming, discovers that "order", "shipment" and "invoice" are separate contexts, extracts the shipping context first behind events, and keeps catalogue and ordering in the monolith as modules until a reason to split appears.

In the Interview#

Deep Dive: From Event Storming to services, step by stepShow

The worked food delivery example above can be traced into concrete decisions.

1. Big-picture Event Storming (half a day). Experts from customer support, restaurant operations, courier operations, finance and product put about 150 orange event stickies on a timeline. Hotspots, in red, show disagreements: "When exactly is an order 'confirmed'?", "Who decides a refund?", "What happens when a courier cancels after pickup?" Each hotspot is a modelling question, and many reveal boundaries, because different people answer them differently.

2. Pivotal events and swimlanes. The group marks pivotal events, OrderPlaced, OrderAccepted, OrderPickedUp and OrderDelivered, where responsibility moves between departments. Swimlanes by department emerge naturally: customer, restaurant, courier, finance.

3. Candidate contexts. Events cluster into the eight contexts in the table above. The group gives each a one-line purpose, such as "Dispatch: get every ready order to the customer quickly, at low cost per delivery".

4. Process-level storming. For Dispatch, the team adds commands, policies, read models and aggregates: the command OfferJob is handled by the DeliveryJob aggregate; the policy "when an offer is not accepted within 30 seconds, offer to the next courier" becomes a process; the read model "couriers near restaurant" comes from a geospatial index fed by location updates.

5. Aggregate design. DeliveryJob holds the order ID, pickup and drop-off, status, assigned courier and offer history. Its invariants are: a job has at most one assigned courier; status moves only along allowed transitions. CourierShift holds the courier's status and current job; its invariant is "at most one active job". Assignment touches two aggregates, so it is a small process: reserve the courier, then assign the job, with compensation if the second step fails.

6. Context map. Ordering is upstream of Kitchen and Dispatch, publishing OrderPlaced and OrderCancelled as a published language. Payments sits behind an ACL over the processor. Payouts is downstream of Ordering and Dispatch, conformist to their events. Customer accounts is upstream of most contexts through an open host API.

7. Deployment. The team starts with three deployables: an Ordering service including Kitchen and Ratings as modules, a Dispatch service because of its distinct scaling and real-time needs, and a Finance service containing Payments and Payouts. Location updates, perhaps hundreds of thousands per minute at peak, go to Dispatch only, so the rest of the system is unaffected by their volume.

8. Later splits. If restaurant integrations grow complex, with tablets and POS systems, Kitchen operations is extracted with its own team. Because it was already a module with its own schema and events, the split is mostly a deployment change.

Deep Dive: Aggregate sizing and concurrency, with numbersShow

Aggregates are the unit of consistency, so their size directly determines contention.

Conflict probability. With optimistic concurrency, two updates to the same aggregate within the same window conflict, and one retries. If an aggregate receives updates at rate λ per second and each transaction takes t seconds from read to commit, the chance that a given transaction conflicts is roughly 1 − e^(−λt), about λt when small. For an Order aggregate updated twice a minute with 50 ms transactions, λt ≈ 0.033 × 0.05 ≈ 0.0017, a conflict about once in 600 updates: negligible. For a "Product" aggregate that also contains its stock level, updated 200 times a second during a flash sale, λt = 200 × 0.05 = 10: almost every transaction conflicts and throughput collapses.

The fix is in the model. Stock is not part of the product's description; it has a different invariant, "stock never goes negative", a different rate of change and often a different owner. Move it to an InventoryItem aggregate, and for very hot items, split stock into buckets, such as ten sub-counters of 100 units each, so updates spread across ten aggregates. Each bucket keeps its own non-negative invariant, and the total is the sum. See Dealing with Contention.

Load size. An aggregate is loaded whole for every command. A Customer aggregate containing 5,000 orders of 2 KB each loads 10 MB to change a phone number. Splitting orders into their own aggregates, referencing the customer by ID, makes each load a few kilobytes.

Collections that grow without bound are a warning sign: comments on a post, members of a group, entries in a ledger. Model the growing part as separate aggregates or as an append-only event stream, with the parent holding only the counters or limits its invariants need.

Version checks in SQL. Optimistic concurrency is usually a version column:

UPDATE orders
SET    status = 'PLACED', total_cents = 4599, version = version + 1
WHERE  id = 'ord_123' AND version = 7;
-- 0 rows updated means someone else changed the order: reload and retry, or report a conflict

When the invariant really spans aggregates, such as "a user has at most three active subscriptions", options are: a small dedicated aggregate, such as UserSubscriptionLimit, that every subscription command must update; a unique constraint in the database as a backstop; or accepting eventual consistency with a compensating action when a violation is detected. Pick based on the cost of a temporary violation. See Concurrency Control and Locking.

Deep Dive: DDD with event sourcing and CQRS, and the history of the ideasShow

Event-sourced aggregates. In event sourcing, an aggregate's state is not stored directly; its events are. Loading an Order means reading its event stream, OrderCreated, LineAdded, LineAdded, OrderPlaced, and applying them in order. A command produces new events, which are appended with an expected version, the stream's optimistic lock. DDD and event sourcing fit naturally: domain events are already the language of the business, aggregates are already the consistency boundary, and each aggregate maps to one stream. Snapshots, every hundred or so events, keep loads fast for long-lived aggregates. See Event Sourcing and CQRS.

CQRS with DDD. Aggregates are designed for enforcing rules on writes, not for queries. Command Query Responsibility Segregation separates the two: commands go to aggregates, and queries go to read models built from domain events, such as an "order history for customer" table or a search index. This lets aggregates stay small, while screens get exactly the shape they need.

An aggregate's lifecycle as a state machine. Many aggregates are naturally state machines, and drawing them clarifies invariants and events:

Each transition is a command handled by the aggregate, each guard is an invariant, and each arrival in a state publishes a domain event.

A short history.

  • Eric Evans, "Domain-Driven Design: Tackling Complexity in the Heart of Software" (Addison-Wesley, 2003), the "blue book", introduced ubiquitous language, bounded contexts, context maps, aggregates, entities, value objects, repositories and the layered architecture around them. Its strategic chapters were initially overlooked in favour of the tactical patterns.
  • Vaughn Vernon, "Implementing Domain-Driven Design" (Addison-Wesley, 2013), the "red book", made the ideas concrete, including the rules for effective aggregate design from his 2011 essays, and gave domain events a central role.
  • Evans' "Domain-Driven Design Reference" (2015) summarised the patterns, adding domain events as a first-class building block.
  • Greg Young popularised CQRS and event sourcing in the DDD community from around 2010.
  • Alberto Brandolini introduced Event Storming around 2013, making strategic discovery fast and collaborative.
  • Microservices, from around 2014, made bounded contexts the standard answer to "how big should a service be?", and brought DDD to a much wider audience. Later books, such as Vlad Khononov's "Learning Domain-Driven Design" (O'Reilly, 2021), refocused on strategic design and subdomain types.
Deep Dive: Testing, architecture and code organisation for a domain modelShow

Testing the model directly. A rich domain model can be tested without databases, networks or frameworks, which is one of its biggest practical benefits. Tests read like business rules, in a given-when-then shape:

  • Given a draft order with no lines, when the customer places it, then it is rejected with "order needs at least one line".
  • Given a placed order, when a line is added, then it is rejected.
  • Given an order with two lines of 1,000 and 2,500 cents, when it is placed, then an OrderPlaced event with a total of 3,500 cents is recorded.

With event-sourced aggregates the shape is even cleaner: given these past events, when this command, then these new events, or this error. Thousands of such tests run in seconds, so the team can refactor the model freely as the language evolves. Property-based tests suit value objects: for any two Money values in the same currency, addition is commutative and the result is never negative.

Ports and adapters around the model. The domain layer should not import the web framework, the ORM or the message broker. The usual structure is hexagonal, introduced by Alistair Cockburn in 2005:

  • the domain contains aggregates, value objects, domain events and domain services, as plain code;
  • the application layer contains use-case handlers, such as PlaceOrderHandler, that load aggregates through repository interfaces, call domain methods, and save results and events in one transaction;
  • adapters implement the interfaces: a PostgreSQL repository, a Kafka publisher reading the outbox, an HTTP controller, a payment-provider ACL.

Dependencies point inwards, so the domain can be tested alone and infrastructure can be swapped. Tools such as ArchUnit for Java, dependency-cruiser for TypeScript and Packwerk for Ruby can fail the build when a domain package imports an adapter, turning the rule into a checked constraint.

Folders by context, then by layer. A codebase organised as controllers/, services/, models/ at the top level hides bounded contexts; every feature touches every folder. Organising first by context, such as ordering/, dispatch/, payments/, each with its own domain, application and adapters, makes the boundaries visible, keeps changes local, and makes a later extraction to a separate service mostly a matter of moving one folder. Each context also gets its own database schema, so cross-context joins become impossible by construction.

Read models need not follow the domain model. Screens that list, search and summarise data are often better served by simple SQL views or dedicated read tables than by loading aggregates. Rich modelling belongs on the write side, where rules are enforced; the read side can be as plain as the query needs.

Measuring model health. Useful signals that the model is drifting from the business include: features that need changes in many contexts at once, frequent translations or special cases in ACLs, aggregates that keep growing new fields for unrelated features, and domain experts who no longer recognise the terms in the code. Each is a prompt to revisit the language or the boundaries, ideally in another short modelling session with the experts.

Deep Dive: Discovery techniques beyond Event StormingShow

Event Storming is the best-known discovery technique, but several others complement it, and teams often combine them.

Domain Storytelling. Developed by Stefan Hofer and Henning Schwentner, described in their 2021 book "Domain Storytelling", a domain expert tells a concrete story, such as "the dispatcher sees a delayed order, calls the restaurant, and reassigns the courier", while a moderator draws it as a pictographic sequence of actors, work objects and activities. It is especially good at surfacing who does what and where work passes between people, which reveals context boundaries and the language each group uses.

Example Mapping. Matt Wynne's technique for refining a single user story: one card for the story, blue cards for its rules, green cards for concrete examples of each rule, and red cards for open questions. It turns vague requirements into the given-when-then examples that become domain tests, and it often exposes rules nobody had written down.

The Bounded Context Canvas. Published by the DDD Crew, a community led by Nick Tune and colleagues, the canvas documents one context on one page: its name and purpose, its strategic classification as core, supporting or generic, its business role, such as revenue generator or compliance enforcer, its ubiquitous language, the business decisions it makes, the inbound and outbound messages, and open questions. Filling it in forces clarity, and reviewing canvases across teams shows overlaps and gaps.

Context Mapper and other modelling languages. Context Mapper, an open-source DSL and tool from the University of Applied Sciences of Eastern Switzerland, lets teams write context maps as text, generate diagrams, and even derive service decomposition suggestions. Text-based maps can be reviewed and versioned like code.

Wardley Mapping. Simon Wardley's technique positions the components of a business on two axes: how visible they are to the user, and how evolved they are, from genesis through custom-built, product and commodity. It complements subdomain classification: a component in genesis or custom-built that users value is likely core, worth building and modelling carefully; a commodity is generic, worth buying.

Choosing between them. Big-picture Event Storming suits early exploration of a whole business with many stakeholders. Domain Storytelling suits processes with many human hand-offs and experts who think in stories. Example Mapping suits refining individual features. The canvas and Context Mapper document results. Wardley maps guide build-versus-buy decisions. A practical sequence for a new system is: big-picture Event Storming over a day, a canvas for each candidate context, process-level storming for the core contexts, and Example Mapping for each feature as it is built.

Running sessions remotely. Since 2020, many teams run these workshops on digital whiteboards such as Miro or Mural. The same rules apply: real domain experts in the room, a timeline, colour-coded notes, a facilitator who keeps the discussion on the business, and short sessions of two to three hours instead of a full day, since remote attention spans are shorter.

Key Takeaways#

  • DDD puts the business domain at the centre: model it with experts, in a shared ubiquitous language used in conversation and code.
  • Subdomains describe the business: invest in core, keep supporting simple, buy generic.
  • A bounded context is a boundary within which one model and language apply; the same word can mean different things in different contexts, and that is healthy.
  • Context maps describe how contexts relate: customer-supplier, conformist, anti-corruption layer, open host and published language, shared kernel, partnership, separate ways.
  • Aggregates are consistency boundaries: small, with explicit invariants, referenced by ID, one per transaction, protected with optimistic versions.
  • Domain events record business facts; publish them reliably with an outbox, and coordinate cross-aggregate rules through events and sagas.
  • An anti-corruption layer keeps legacy and vendor models out of your code.
  • Bounded contexts are the best starting point for service boundaries: split by capability and language, not by entity or layer, and start as modules.
  • Use DDD where complexity lives; use CRUD where it does not.