Software Architecture

Domain-Driven Design: Microservices—how to design services aligned with business boundaries.

Compare a modular monolith with separating Sales, Payments, and Inventory. Design contracts in TypeScript and Express and understand partial failures, eventual consistency, idempotency, Outbox, and Sagas without introducing complex infrastructure.

Updated on October 29, 2026

Content explored 0%
18px

The indicator keeps the furthest percentage explored; marking the article complete is your choice.

Three services do not guarantee three autonomous capabilities

Sales, Payments, and Inventory run in separate processes. Yet every purchase calls all three in a chain, all read the same tables, and any change requires deploying the entire system.

We have a distributed application, but little autonomy.

The alternative is not to decide that microservices are always a mistake either. Perhaps Payments needs an independent delivery cycle, Inventory has a different workload, and teams can operate those capabilities separately.

The question is what concrete benefit justifies introducing deployment boundaries and network communication, and which new responsibilities we will need to assume.

In this article, we will start with a modular monolith and explore one possible separation. The diagrams and examples are instructional proposals, not a recommendation to migrate our real store.

What characterizes a microservices architecture

A microservices architecture organizes an application into independently deployable, capability-oriented services. That independence requires contracts and operational boundaries; it does not appear merely by dividing a repository.

Lewis and Fowler describe common characteristics such as organization around business capabilities, independent deployment, and decentralized data management. They do not propose measuring a microservice by a fixed line count. Microservices.

Potential advantages include evolving or scaling capabilities differently. Costs include remote communication, more operational elements, and partial outcomes.

“Potential” matters: extracting code can increase cost without achieving independence if it retains dependencies requiring coordination for every change.

Four boundaries that must not be confused

Bounded Context: defines a model and its meaning.

Module: organizes responsibilities within code.

Aggregate: protects decisions and consistency within a model.

Microservice: introduces a unit of execution, deployment, and operation.

A context can be implemented with several modules and aggregates. It can live inside a monolith or distribute certain capabilities across more than one service when there is a reason.

There is no “one aggregate, one microservice” or “one context, one server” rule. Maintaining model coherence and avoiding unnecessary fragmentation remain design decisions.

Microsoft's guidance recommends starting with the domain and checking candidates against team, data, availability, and scaling needs, revisiting separations and groupings. That guides analysis; it does not make every model candidate a mandatory service. Identifying microservice boundaries.

The starting point: a modular monolith

Our store maintains one deployment with separate responsibilities:

commerce application
  |
  +-- Sales
  |    +-- order model
  |    +-- use cases
  |    +-- adapters
  |
  +-- Payments
  |    +-- payment model
  |    +-- use cases
  |    +-- adapters
  |
  +-- Inventory
       +-- stock and reservation model
       +-- use cases
       +-- adapters

Separation must be reflected in dependencies and data ownership. One folder per context is not enough if Sales writes directly to Payments tables.

A modular monolith can have explicit contracts between contexts. In this collection's examples, integrations use HTTP ACLs and consumer contracts, without importing other contexts' entities.

If the HTTP call targets the same deployment, it still needs error handling. Physical location does not create a shared transaction.

Retaining one deployment can simplify operations and delivery for a small team. It does not prevent modeling boundaries we can revisit later.

Proposing candidates with a verifiable reason

Suppose these needs exist, pending confirmation:

  • Payments needs to evolve its financial integration without deploying the entire store.
  • Inventory receives intensive queries and has a different load pattern.
  • Sales can operate and display pending states without always obtaining an immediate response from everyone.
  • Owners can maintain contracts and handle failures for each service.

Separation would be a candidate if evidence supports those conditions.

Before approving it, ask:

  1. Which changes can truly be delivered separately?
  2. Does the capability retain cohesive rules, or require constant calls to its neighbors?
  3. Who owns its data and migrations?
  4. What result does the user see if a dependency fails?
  5. Can we observe and operate the complete workflow?
  6. Which costs does separation avoid, and which does it introduce?

If the only answer is “we want something modern,” a business or operational reason is missing.

One possible separation

Client
  |
  v
Sales Service -------------------> Inventory Service
  |                                  |
  |                               Inventory data
  |
  +------------------------------> Payments Service
  |                                  |
  |                               Payments data
  |
Sales data

Payments -- PaymentConfirmed contract --> Sales

Query arrows and published facts represent different contracts. The drawing requires no specific broker and does not describe the entire purchase coordination process.

One project structure could be:

services/
  sales/
    src/domain/
    src/application/
    src/adapters/
  payments/
    src/domain/
    src/application/
    src/adapters/
  inventory/
    src/domain/
    src/application/
    src/adapters/

Each service can choose an appropriate internal organization. We will not repeat the previous article's layers here; distributing processes does not replace protecting their rules.

Separate repositories or different languages are not mandatory either. Introducing different tools unnecessarily adds maintenance, not autonomy by definition.

Owned data and public contracts

Sales maintains orders. Payments maintains payments and attempts. Inventory maintains reservations and stock.

A service should not write to another's tables to avoid a call. Nor should it depend on another's schema through operational joins.

Data ownership can be implemented with separate databases or schemas and appropriate permissions. Sharing a physical instance does not necessarily mean sharing ownership, but controls and independence of changes must be maintained.

If everyone can query and modify any table, process separation loses much of its purpose.

Reports needing to combine information require explicit design. An administrative query does not justify indiscriminately opening every service's operational storage.

Synchronous communication: a question with a wait limit

Sales queries availability:

GET /integration/v1/availability/BAG-URBAN
Accept: application/json

Inventory responds:

{
  "sku": "BAG-URBAN",
  "reservableQuantity": 8
}

Semantics matter: observing eight units reserves none. The quantity can change before the next operation.

The consumer defines a port and keeps contract interpretation in an adapter. The following example is for reading and assumes Node.js with fetch and TypeScript configured for its APIs.

In inventory-availability.ts:

export interface Availability {
  readonly sku: string;
  readonly reservableQuantity: number;
}

export interface AvailabilityReader {
  read(sku: string): Promise<Availability>;
}

export class InventoryUnavailableError extends Error {}
export class UnknownSkuError extends Error {}
export class InventoryContractError extends Error {}

export function parseAvailability(
  raw: unknown,
  expectedSku: string,
): Availability {
  if (
    typeof raw !== "object" ||
    raw === null ||
    Array.isArray(raw)
  ) {
    throw new InventoryContractError();
  }

  const data = raw as Record<string, unknown>;
  const quantity = data.reservableQuantity;

  if (
    data.sku !== expectedSku ||
    typeof quantity !== "number" ||
    !Number.isSafeInteger(quantity) ||
    quantity < 0
  ) {
    throw new InventoryContractError();
  }

  return { sku: expectedSku, reservableQuantity: quantity };
}

export class InventoryHttpAvailability implements AvailabilityReader {
  constructor(
    private readonly origin: string,
    private readonly authenticationHeaders:
      () => Promise<Record<string, string>>,
  ) {
    const url = new URL(origin);
    if (
      url.protocol !== "https:" ||
      url.username !== "" ||
      url.password !== "" ||
      url.pathname !== "/" ||
      url.search !== "" ||
      url.hash !== ""
    ) {
      throw new Error("Origen de Inventory inválido");
    }
  }

  async read(sku: string): Promise<Availability> {
    if (!/^[A-Za-z0-9_-]{1,64}$/.test(sku)) {
      throw new Error("SKU inválido");
    }

    const url = new URL(
      "/integration/v1/availability/" + encodeURIComponent(sku),
      this.origin,
    );

    const headers = await this.authenticationHeaders();
    let response: Response;

    try {
      response = await fetch(url, {
        headers: { ...headers, accept: "application/json" },
        signal: AbortSignal.timeout(3000),
        redirect: "error",
        cache: "no-store",
      });
    } catch {
      throw new InventoryUnavailableError();
    }

    if (response.status === 404) throw new UnknownSkuError();
    if (!response.ok) throw new InventoryUnavailableError();

    const raw: unknown = await response.json();
    return parseAvailability(raw, sku);
  }
}

Origin configuration and credentials come from controlled administrative sources, not a user-supplied URL. The provider must authenticate and authorize those calls.

The example sets an instructional timeout and does not follow redirects. It does not implement response size limits, observability, or complete JSON error handling; those must be addressed before production.

The important distinction is that an inaccessible service does not mean an unknown product or zero availability.

There are no automatic retries. Even a read needs a total waiting budget and a policy that does not multiply load when the provider fails.

Requesting changes requires additional guarantees

A reservation could use this illustrative contract:

POST /integration/v1/reservations
Content-Type: application/json

{
  "requestId": "checkout-100-reservation",
  "sku": "BAG-URBAN",
  "quantity": 2
}

Inventory must define what repeating the request means, how it links it to the consumer, and what happens if it is reused with different data.

If idempotency is promised, the request record and its effect must be coordinated durably and atomically. A requestId in JSON does not implement that guarantee.

If Sales loses the response, it does not automatically know the reservation failed. It may need to query or repeat according to the contract, preserving the same logical identity.

Network availability changes use case design. A remote function is not merely a slower local function.

Asynchronous communication: sharing a fact, not an entity

Payments can publish a confirmation through the integration language already studied:

interface PaymentConfirmedV1 {
  readonly type: "payment.confirmed";
  readonly schemaVersion: 1;
  readonly messageId: string;
  readonly paymentId: string;
  readonly orderId: string;
  readonly amountMinor: number;
  readonly currency: "EUR";
  readonly status: "CONFIRMED";
  readonly occurredAt: string;
}

The snippet represents a contract; it does not validate a network message. It retains the collection's meaning: recorded full capture, gross amount in EUR cents, and UTC confirmation timestamp.

An internal Domain Event can originate that information. The Integration Event selects a public representation consumers can interpret without importing the Payments aggregate.

The consumer needs to verify sender, format, identity, and correspondence with its operation. It must not confirm any order simply because it receives a document with that name.

Asynchronous integration allows services not to be available at the same instant to process work, if transport preserves messages appropriately. In exchange, it introduces delays, duplicates, and possible ordering differences that must be managed.

Eventual consistency with understandable states

Payments can record payment while Sales still displays “processing confirmation.” During that interval, their models do not reflect the same information.

Eventual consistency does not mean everything will magically resolve. It needs delivery, processing, retry, and resolution mechanisms for operations that get stuck.

The experience must distinguish pending, rejected, and unknown. Hiding an intermediate state by showing success prematurely does not improve consistency.

A Sales Express API could query a local progress view, avoiding calls to every service whenever the user refreshes the screen.

This snippet uses Express 5 and mandatory reading and authorization dependencies:

import express, { type Request } from "express";

interface OrderProgress {
  readonly orderId: string;
  readonly status: "PROCESSING" | "CONFIRMED" | "REQUIRES_REVIEW";
}

interface OrderProgressReader {
  read(orderId: string): Promise<OrderProgress | null>;
}

export function createProgressApp(
  progress: OrderProgressReader,
  authorize: (request: Request, orderId: string) => Promise<void>,
) {
  const app = express();

  app.get("/orders/:id/progress", async (req, res) => {
    const orderId = req.params.id;
    if (
      typeof orderId !== "string" ||
      !/^[A-Za-z0-9_-]{1,64}$/.test(orderId)
    ) {
      res.status(400).json({ error: "INVALID_ORDER_ID" });
      return;
    }

    await authorize(req, orderId);
    const result = await progress.read(orderId);

    if (!result) {
      res.status(404).json({ error: "ORDER_NOT_FOUND" });
      return;
    }

    res.set("Cache-Control", "no-store").json({
      orderId: result.orderId,
      status: result.status,
    });
  });

  return app;
}

The reader must obtain Sales data, not data from other services' tables. Authorization must verify permission for the order. The final error middleware is omitted and no server is started: this is not a complete production application.

The local view must be updated and allow detection of overly old states. Reading locally reduces a dependency chain but does not eliminate integration work.

Transactional Outbox: closing a local gap

A classic problem appears when saving a payment and then attempting to publish its confirmation. The write can succeed while publication fails.

Transactional Outbox records the change and a pending notification in the same local transaction. Another process subsequently delivers the message. This prevents one of those two local writes from being committed without the other. AWS: Transactional Outbox.

Local transaction in Payments:
  save confirmation
  record pending message in outbox
  commit transaction

Afterward:
  deliver pending message
  record delivery progress

Duplicates can occur if delivery is repeated. The consumer needs an appropriate, durable idempotency strategy.

Outbox does not create atomicity between Payments and Sales databases. Nor does it replace rules for ordering or interpreting different facts. Here, we only introduce its purpose; we do not implement the mechanism.

Sagas: coordinating steps without promising global rollback

A purchase may require reserving, collecting payment, and confirming. If one part fails, the business needs to decide how to continue or compensate.

A Saga organizes a sequence of local transactions and recovery or compensation actions. It can be coordinated through an orchestrator or collaboration among participants. AWS documentation describes the orchestrated alternative and its trade-offs. Saga orchestration.

Releasing a reservation or requesting a refund are business actions, not an instantaneous rollback of a common transaction. They can fail, take time, or require intervention.

Not every operation is reversible in the same way. Shipping a package is not undone by deleting a row.

Before introducing a Saga, describe the acceptable outcome and who resolves each situation. It is not a word you can add to a diagram to declare consistency.

Workflow observability and testing

When a purchase crosses services, you need to connect what happened without logging secrets.

Maintain business references and technical correlation, each attempt's states, and signals for pending operations. Traces help follow calls; metrics show trends, and logs provide context.

Distinguish expected rejections from technical failures. An increase in rejected reservations does not necessarily mean Inventory is down.

Tests also have levels:

  • Local rules with controlled dependencies.
  • Contracts checking consumer and provider expectations.
  • Integrations in isolated environments.
  • Failure and recovery scenarios.

For example, these proposed assertions verify only the earlier client's parser. They have not been run as part of this article:

import assert from "node:assert/strict";
import { parseAvailability } from "./inventory-availability.js";

assert.deepEqual(parseAvailability({
  sku: "BAG-URBAN",
  reservableQuantity: 0,
}, "BAG-URBAN"), {
  sku: "BAG-URBAN",
  reservableQuantity: 0,
});

assert.throws(() => parseAvailability({
  sku: "OTHER",
  reservableQuantity: 8,
}, "BAG-URBAN"));

assert.throws(() => parseAvailability({
  sku: "BAG-URBAN",
  reservableQuantity: "8",
}, "BAG-URBAN"));

Lost responses, repeated messages, and unavailable dependencies must also be tested. A green test with mocks does not demonstrate that the entire system can recover.

When to retain the modular monolith

Retaining one deployment may be appropriate when boundaries keep changing, the team is small, or there is no clear need for independent delivery and operations.

It may also be the best option if separation would produce too many calls for every decision or if there is not yet capacity to maintain the resulting services.

A monolith with clear boundaries can offer more code autonomy than several services sharing tables and always deploying together.

If a justified candidate exists, gradually extracting one capability lets you verify the benefit before fragmenting the entire application. Data ownership, transition, and operations must be planned; avoid two writers without an explicit agreement.

It is unwise to distribute coupling that is not yet understood.

Signs of a tightly coupled distributed system

Review these situations:

  • A service is created per entity without a clear operational capability.
  • Every change requires modifying and deploying several services.
  • A request chains Sales, Payments, and Inventory for every read.
  • Services write to other services' tables.
  • Shared libraries require coordinating every model.
  • Nobody owns a purchase left pending.
  • Mutations are retried without a repetition guarantee.

A remote call can cross a coherent boundary. Many calls to reconstruct a small decision may indicate a boundary needing review.

Two contrasting examples

Education: isolating a specific workload

A platform may have an assessment capability needing resources and operations very different from course management. That difference may justify studying a separate service if its contract and failures are clear.

It does not imply separating every question, attempt, and grade into different processes. Capability cohesion still matters.

Reservations: fragmenting a decision too early

A small application separates availability and reservation into services that must constantly query each other to prevent overlaps on the same resource.

Before adding more distributed coordination, review whether that decision should stay together within one model or service.

Both cases teach looking for a concrete reason for autonomy, not a minimum code size.

Preventing AI from fragmenting by default

For Cursor, Codex, or Claude, provide requirements and permitted alternatives.

To analyze boundaries:

Compare retaining this modular monolith with extracting one capability. Justify every candidate through cohesion, data, team, and deployment. Do not assign a microservice to every aggregate. Distinguish evidence from hypotheses and identify new costs.

To generate an integration:

Implement only the Sales HTTP adapter according to this Inventory contract. Validate unknown data and distinguish unknown product, zero availability, and technical failure. Do not import external entities or assume a shared transaction. Do not add mutation retries without documented guarantees.

To review the process:

Walk through this purchase with a lost response and duplicate message. Identify intermediate states, owners, and outstanding guarantees. Do not claim Outbox delivers exactly once or that a Saga automatically reverses remote effects.

A person must review operational feasibility and business boundaries. A collection of AI-generated folders and Dockerfiles does not demonstrate an autonomous architecture.

Exercises

1. The shared database

Payments writes its table, but Sales updates it directly to resolve incidents. Which autonomy has been compromised?

2. The payment timeout

Sales receives no response to a payment request. Can it start another attempt with a new reference, assuming the previous one failed?

3. A service per aggregate

A context has five aggregates. The team automatically proposes five microservices. What analysis is missing?

Reasoned solutions

1. Data ownership and the ability to evolve rules and schema without consumers bypassing them. Incident resolution needs an authorized capability or explicit procedure, not arbitrary cross-service writes.

2. No. Payment may have occurred. Query or repeat according to the same logical operation's contract, avoiding another effect caused by not knowing the result.

3. Functional cohesion, decision dependencies, data ownership, deployment needs, team, and operations. Aggregates can guide candidates but do not determine service units by themselves.

Distribute when autonomy outweighs the cost

DDD provides boundaries and language for discussing business-aligned services. Network, deployment, and operations add decisions those conceptual boundaries do not automatically resolve.

Before separating, check what independence you will gain, which data each service will own, and how you will recognize partial failures.

Both a modular monolith and a microservices architecture can respect well-designed models. The choice must be justified by system needs and the ability to sustain its guarantees.

Loading conversation…

Keep learning