Skip to content
webtechos

Domain-Driven Design for Microservice Architectures: Where to Draw the Lines

Learn how to use domain-driven design to draw microservice boundaries that hold: bounded contexts, aggregates, events, sagas, and migration tactics.

15 Sept 2026·16 min read·General

Microservice projects tend to go wrong at the boundaries, not in the technology. Cut a monolith along technical layers or database tables and you end up with a pricing change that still needs coordinated deploys across four services, three services reading the same table, and one incident that pages half the engineering org. The infrastructure bill went up, the coupling stayed, and the network added new ways to fail. The usual name for the result is a distributed monolith.

The fix is to draw boundaries around the business instead. Domain-driven design (DDD) is one of the most widely used methods for doing that, and this guide shows how to apply it to microservices: finding boundaries, modeling the inside of each service, connecting services without re-coupling them, and deciding when and how to split a monolith. Claims from outside sources are linked in the Sources list at the end.


Why services fail without a domain model

Splitting by technical layer ("the API service," "the database service," "the validation service") produces services that cannot change independently, because every feature cuts through all of them. Splitting by noun ("the User service") fails more quietly: the noun ends up meaning something different to every team, so the service grows until it owns everything anyone ever called a user.

Uber described the cost at scale in its 2020 write-up on domain-oriented microservice architecture. At around 2,200 critical microservices, finding the root cause of one problem meant working through roughly 50 services across 12 teams, and services that looked independent sometimes had to be deployed together to change anything safely, a pattern Uber calls a networked monolith. Its summary of the trade: an operational benefit bought at the expense of performance.

Chatty call chains make the performance side concrete. Take a checkout request that passes through seven services in sequence, each 99.9% available on its own (about 44 minutes of downtime a month). If failures are independent and nothing has a fallback, the request succeeds only when all seven are up: 0.999^7 ≈ 99.3%, or roughly five hours of monthly downtime. Add 20 ms per hop and 140 ms is gone before any real work happens. Retries, caching and fallbacks soften this in practice, but every hop on the critical path still costs something.

The aim, then, is to cut along lines where the business already separates, so most requests are served inside one service. The front-end techniques in our web performance guide help at the edge, but they cannot win back time lost to a chatty call graph behind it.


DDD in microservice terms

Eric Evans introduced domain-driven design in his 2003 book. Its strategic half (subdomains, bounded contexts, context maps) decides where service boundaries go. Its tactical half (entities, value objects, aggregates, domain events) shapes what lives inside each service. Martin Fowler calls the bounded context a central pattern of the strategic half.

DDD concept

What it means for a microservice

Bounded context

The service boundary and, ideally, the team boundary

Ubiquitous language

Names used in code, APIs, event types, and database schemas

Aggregate

The transaction and consistency boundary; the unit of data ownership

Domain event

A business fact other contexts react to; once published across services, a contract

Context map

Who depends on whom, and who has to adapt

Anti-corruption layer

The translator that keeps a foreign model out of yours


Strategic design: finding boundaries that hold

Sort subdomains by where you win

Start by listing what the business does, then label each area:

  • Core subdomains are what makes the company different: pricing for a marketplace, routing for a logistics company, underwriting for an insurer. Put your best engineers here and build it yourself.

  • Supporting subdomains are necessary but not differentiating, like internal back-office tooling. Build them simply.

  • Generic subdomains are solved problems: authentication, email delivery, invoicing, document generation. Buy or adopt.

Chris Richardson's decompose-by-subdomain pattern uses the same three-way sort. It shapes how many services you need and how much care each deserves. A generic subdomain rarely deserves a bespoke service at all; plenty of notification and back-office glue can be handled by a workflow automation tool such as n8n instead of a custom service you now have to own, version, and monitor. Spend your service budget on the core.

Bounded contexts and the "Customer" problem

The word "customer" is the classic trap. Fowler notes that "customer" and "product" are the words that most often carry different meanings in different parts of a large organization. In a retail platform it looks like this:

Context

What "Customer" means there

Support

Contact details, open tickets, satisfaction history

Ordering

A buyer reference and a delivery preference

Billing

Legal entity, tax ID, payment methods

Shipping

A recipient name and a physical address

A single shared Customer model across all four has to carry every attribute, every rule, and every team's change requests. A bounded context gives each team its own small model and lets them evolve independently. The contexts share an identifier (a customerId) and little else. The line between two contexts usually sits where the language changes, and Fowler points to human culture as the dominant factor that draws it.

Bounded context vs microservice

A bounded context is a modeling boundary; a microservice is a deployment boundary. They often line up one to one, but not always: a context can span several services, and early on it can live as a module inside a monolith. A common sizing heuristic is that a service should be no smaller than one aggregate and no larger than one bounded context.

Run an event storming session

Alberto Brandolini's EventStorming is one of the quickest ways to find contexts. Block out a long session and put developers, product people, and the people who actually run the business in one room with a very long wall and orange sticky notes.

  1. Write domain events in past tense: OrderPlaced, PaymentCaptured, ShipmentDispatched. No one is allowed to design anything yet.

  2. Order them on a timeline and argue about gaps. Disagreement is the point; it surfaces the places where two teams mean different things by the same word.

  3. Add the commands and actors that trigger each event (PlaceOrder, by a buyer).

  4. Cluster events around the nouns that own them. Those clusters are your aggregate candidates.

  5. Draw lines where the language changes. Where "customer" shifts meaning, there is a context boundary. Where a cluster is mostly hand-offs to another cluster, you may have drawn a line in the wrong place.

The output is a draft context map and a shared glossary, which is your ubiquitous language in its first form.

Map how contexts relate

Once you have contexts, decide how each pair relates. These are the patterns from Evans's strategic design worth knowing:

Pattern

When to use it

Customer-supplier

Upstream provides, downstream depends. Downstream gets a voice in the contract.

Conformist

Downstream accepts the upstream model as is. Common with third-party APIs you cannot influence.

Anti-corruption layer (ACL)

Downstream translates the upstream model into its own. Essential around legacy systems.

Open host service / published language

Upstream publishes a stable, documented contract for many consumers.

Shared kernel

Two contexts share a small piece of model. Use sparingly; it couples release cycles.

Partnership

Two teams succeed or fail together and coordinate closely.

Separate ways

Two contexts do not integrate at all because the integration is not worth its cost.

Write the map down and keep it in the repo. When a dependency shows up that is not on the map, that is a design conversation, not a quiet pull request.

A worked example: a retail platform

The rest of this guide uses one small platform. Six contexts, each owning one aggregate, talking mostly through events:

Context

Aggregate

Publishes

Consumes

Catalog

Product

ProductListed, PriceChanged

Nothing (Ordering reads prices through Catalog's API)

Ordering

Order

OrderPlaced, OrderConfirmed, OrderCancelled

StockReservationFailed, PaymentCaptured, PaymentFailed

Inventory

StockItem

StockReserved, StockReservationFailed

OrderPlaced, OrderCancelled

Billing

Payment

PaymentCaptured, PaymentFailed

StockReserved

Shipping

Shipment

ShipmentDispatched

OrderConfirmed

Support

Ticket

TicketOpened

OrderPlaced, ShipmentDispatched

Every arrow between contexts is an event or a deliberate API call, never a table read.


Tactical design: what lives inside a service

Aggregates are your transaction boundary

An aggregate is a cluster of objects that must be consistent together, guarded by one root. It matters for microservices because it tells you what can be changed atomically. Vaughn Vernon's "Effective Aggregate Design" essays lay out the rules of thumb most teams follow:

  • Keep aggregates small. Build them around true invariants that must hold within a single transaction, not around convenient object graphs.

  • Reference other aggregates by identity, never by object.

  • Aim for one aggregate per transaction. Vernon calls this a rule of thumb, not an absolute law.

  • Use eventual consistency between aggregates, and especially between services.

Here is a compact example from the Ordering context. Behavior lives on the aggregate, and the rule that an order cannot change after it is placed is enforced in one spot:

ts

class Order {
  private lines: OrderLine[] = [];
  private status: "draft" | "placed" | "cancelled" = "draft";

  private constructor(
    readonly id: OrderId,
    private readonly customerId: CustomerId, // reference by ID, not by object
  ) {}

  static draft(id: OrderId, customerId: CustomerId): Order {
    return new Order(id, customerId);
  }

  addLine(sku: Sku, qty: number, unitPrice: Money): void {
    if (this.status !== "draft") throw new Error("Order already placed");
    if (qty <= 0) throw new Error("Quantity must be positive");
    this.lines.push(new OrderLine(sku, qty, unitPrice));
  }

  place(): OrderPlaced {
    if (this.status !== "draft") throw new Error("Order already placed");
    if (this.lines.length === 0) throw new Error("Cannot place an empty order");
    this.status = "placed";
    return new OrderPlaced(this.id, this.customerId, this.total());
  }

  cancel(): OrderCancelled {
    if (this.status === "cancelled") throw new Error("Order already cancelled");
    this.status = "cancelled";
    return new OrderCancelled(this.id, this.customerId);
  }

  private total(): Money {
    return this.lines.reduce((sum, l) => sum.add(l.subtotal()), Money.zero());
  }
}

If your aggregates are mostly getters and setters with the rules scattered across "service" classes, you have an anemic domain model. It is a common tactical failure, and one reason DDD can start to feel like ceremony.

Value objects and events

Model concepts with no identity as immutable value objects: Money (amount plus currency), Address, EmailAddress. They remove a surprising amount of validation code and bugs like adding euros to dollars.

Domain events are facts about something that already happened, and they become the vocabulary services use to talk to each other. Keep them apart from product-analytics events (clicked_checkout_button), which belong in a tool like PostHog rather than in business workflows; mixing the two lets analytics-shaped payloads drive business logic.

Keep the domain layer free of infrastructure

Inside each service, a hexagonal or layered structure keeps business rules away from frameworks: the domain layer defines a repository interface, and the infrastructure layer implements it with a database. That makes the rules testable without a database and turns a message-broker swap into an infrastructure change instead of a domain rewrite.


Connecting services without re-coupling them

Events between contexts, calls inside them

Inside a service, plain method calls are fine. Between services, prefer publishing domain events and let consumers decide what to do with them. Use a synchronous call when the caller cannot proceed without the answer, such as Ordering reading a current price from Catalog, and treat each one as a small availability tax (the arithmetic is above).

Two practices keep event-driven systems honest:

  • Transactional outbox. Write the event to an outbox table in the same database transaction as the aggregate change, and have a separate relay publish it. This closes the "saved the order, crashed before publishing" gap.

  • Idempotent consumers. Brokers can deliver a message more than once, and the outbox relay itself can publish twice if it crashes after publishing but before recording that it did. Every handler must tolerate seeing the same event twice, for example by tracking the IDs of events it has already processed.

Handle transactions across services with sagas

A single ACID transaction cannot span several services' databases, and two-phase commit across services and a message broker is usually not an option. So a multi-service process becomes a saga: a sequence of local transactions, each publishing an event that triggers the next, with compensating transactions that undo earlier steps when a later one fails.

domain-driven-design-context-map

The order saga from the worked example. Solid arrows are the happy path; dashed arrows are the compensation path.

The order of steps matters. Stock is reserved before money is taken, so the step that is hardest to undo comes last and a failed reservation never needs a refund. The order sits in a pending state until PaymentCaptured arrives, the simplest defence against other processes treating it as final.

Richardson lists two costs of the pattern. There is no automatic rollback, so you design each compensating transaction yourself. And there is no isolation, so concurrent sagas can see each other's intermediate state and need countermeasures.

The diagram shows choreography, where each service reacts to events. Orchestration puts a coordinator in charge of the process state instead. Choreography keeps services decoupled but spreads the flow across many handlers; orchestration centralizes it, which tends to be easier to follow as steps and branches multiply. Whichever you pick, write the saga as named states and transitions first. LangGraph applies the same discipline to agent workflows, where every transition is something you wrote rather than something the model improvised.

Own your data, and plan your queries

Each service owns its data and no other service reads its tables. If Billing needs a customer's legal name, it keeps a small local copy fed by events or asks the owning service through its API. A shared database quietly rebuilds the coupling you were trying to remove: the schema becomes an undocumented API that nobody can change.

Data ownership rules out cross-service joins, so plan for those queries early. Two common answers: API composition, where a gateway or backend-for-frontend calls several services and assembles the result, and read models, where a service keeps its own denormalized copy of other contexts' data, updated from events. Support's view of a customer's orders is a read model built from OrderPlaced and ShipmentDispatched.

An event's name and payload are a public API. Version them, prefer additive changes, and use consumer-driven contract tests so a provider learns it broke a consumer before production does. Pact is a common tool for this, built around contracts generated from the consumer's own tests.


How big should a service be, and when to split

The honest answer is "bigger than you think at the start." Microservices carry real fixed costs: deployment pipelines, observability, contract testing, on-call surface, and the data-consistency work above. Conway's Law says systems tend to mirror the communication structure of the organization that builds them, so align service boundaries with team boundaries instead of fighting it.

Fowler's 2015 "Monolith First" note makes the sequencing argument. He observed that almost all the successful microservice stories he had heard began as a monolith that grew too big, while systems built as microservices from scratch often ran into serious trouble, partly because even experienced architects struggle to get boundaries right early. He also flagged caveats: you cannot assume an arbitrary monolith splits cleanly, the route works best when the monolith was well modularized from the start, and the evidence is anecdotal and contested.

A pragmatic path:

  1. Start with a modular monolith whose modules match your bounded contexts, with enforced boundaries and no cross-module table access. ArchUnit (a Java library whose rules run as ordinary unit tests) or dependency-cruiser (for JavaScript and TypeScript, which can check dependency rules in a build pipeline) can flag a module that reaches across a boundary.

  2. Extract a context into a service only when you have a concrete reason: independent scaling, a different release cadence, a team that needs autonomy, or a compliance boundary. Fowler also describes starting with a couple of coarse-grained services and splitting them as boundaries stabilize.

  3. Keep generic and supporting subdomains coarse. Merge them into a few services, or buy them.


Migrating a monolith without a rewrite

Fowler coined the term strangler fig for the usual alternative to a big-bang rewrite: build new functionality alongside the legacy system and move behavior across gradually. He reports that simple replacement plans fail most of the time, because replacements take long, users cannot wait for new features, and the old system's real behavior is hard to pin down.

  1. Model the monolith's real contexts first. Run event storming against the existing system and compare the result with the code; the gap is your roadmap.

  2. Pick one seam with high change frequency and few inbound dependencies. Avoid the most tangled core on your first attempt.

  3. Put an anti-corruption layer between old and new. The new service speaks its own model; the ACL translates to and from the legacy schema.

  4. Route traffic gradually through a facade, moving one capability at a time and keeping the ability to roll back.

  5. Retire the old code and data once the new service is authoritative. Leaving duplicated ownership in place is how migrations silently rot.


Where AI coding tools fit

AI coding tools do not choose your boundaries; that conversation needs people who know the business. They help once the boundaries exist, if they can see them. Put the glossary and context map where the tool reads them every session: a CLAUDE.md file for Claude Code, which loads it at the start of each session, or .cursor/rules and AGENTS.md for Cursor. Then use the agent for mechanical work such as renaming a concept to match the glossary, extracting a module behind an interface, or drafting contract tests, and review its diffs against the context map.

Treat those instruction files as context, not enforcement; Claude Code's own documentation says as much. The architecture tests above remain the hard check. Which style suits your team, a terminal coding agent or an AI-native editor, is the question our Cursor vs Claude Code comparison answers.


Before you split: a checklist

  • Can you describe each context's responsibility in one sentence without using "and"?

  • Does each context have a glossary and an owning team, and can the team define every term the same way twice?

  • Does each service own its data, with no outside reads or writes and no shared "common" library of domain types? Such a library is a shared kernel in disguise.

  • Do most user-facing requests complete inside one service?

  • Is every cross-service interaction either an event or a deliberate, documented API call?

  • Does every multi-service process have a written saga with a pending state and compensation steps?

  • Is every event published through an outbox and consumed idempotently?

  • Is full tactical DDD reserved for the core, with plain CRUD in generic and supporting subdomains?

  • Do you have a concrete reason for each extraction, and a recurring slot to revisit the glossary and context map as the business changes?


Questions

Frequently asked questions

Is DDD required for microservices?

No, but you need a principled way to choose boundaries. Subdomain-based decomposition is the minimum. DDD goes further, with a shared language per context and explicit relationships between contexts. Teams that skip all of it tend to split by technical layer or by entity.

How does domain-driven design differ from domain-oriented microservice architecture (DOMA)?

DDD is a modeling approach that works with monoliths or microservices. DOMA, which Uber described in a 2020 engineering post, is an architecture style for organizing very large microservice estates into domains, layers, gateways, and extension points. Uber says it draws on DDD, Clean Architecture, and service-oriented design, and reported grouping about 2,200 services into 70 domains. DDD helps you find boundaries; DOMA adds structural rules around them at scale.

What is the difference between a domain event and an integration event?

A domain event stays inside one bounded context. It is usually dispatched in-process, often within the same transaction, to make side effects across aggregates explicit. An integration event crosses a boundary to other services, travels over a message broker, and should be published only after the data is persisted. A domain event handler is the usual place to publish an integration event, as Microsoft's eShop reference application does.

Do I need event sourcing or CQRS to use DDD?

No. DDD requires neither. Event sourcing is one alternative to the transactional outbox for updating state and publishing events atomically, and read models are a lightweight form of CQRS. Adopt them when a specific problem calls for them, not as part of the starting kit.

How do I know my service boundaries are wrong?

Look for four signs: two services always deploy together, they fail together, one cannot answer a request without calling the other, or a change that should touch one context keeps touching three. In the first three cases you have one service with a network in the middle, and merging them is usually cheaper than coordinating them. The fourth usually means the line sits in the wrong place.

When should I not use DDD?

For simple CRUD applications with little business logic, full tactical DDD adds more ceremony than value. Even then, the strategic ideas (a shared vocabulary, explicit boundaries) cost little and are worth keeping.


Final Verdict

Domain-driven design helps teams build microservices that can evolve independently without creating unnecessary dependencies. The goal is not to create more services, but to define clear business boundaries, establish data ownership, and reduce the need for coordinated changes across teams.

Start by identifying a workflow that frequently requires changes across multiple services. Use event storming to uncover bounded contexts, compare them with your existing architecture, and document the gaps. Get the boundaries right before splitting services, and extract them only when there is a clear technical or business reason.

WebTechOS accepts no payment for coverage, placement or scores. Where a piece references pricing, it reflects published list rates at the date shown.