Software Architecture

Domain-Driven Design: Open Host Service—how to design stable integration interfaces between Bounded Contexts.

Design a common Inventory interface for Sales, Shipping, and Marketplace. Define availability and reservations with TypeScript and Express, validate inputs and errors, and plan testing and evolution without exposing the internal model.

Updated on October 29, 2026

Content explored 0%
18px

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

Three consumers, three ways to bypass Inventory

Sales queries a table to display availability. Shipping imports an internal service to prepare shipments. Marketplace requests an exclusive endpoint that returns almost the entire inventory entity.

Each integration seems quick on its own. Then Inventory reorganizes its locations and breaks all three: its internal decisions had become unintended contracts.

An Open Host Service, or OHS, offers a coherent integration protocol so that several consumers can use a context's capabilities without depending on its internal structure. It does not mean exposing every existing method or publishing an unauthenticated API.

We will design that offering for Inventory using TypeScript, Node.js, and Express. We will work with availability queries and reservation requests. Storage logic will remain behind an explicit port: the article focuses on the public interface, its guarantees, and its evolution.

What an Open Host Service offers

Evans proposes OHS when a context receives enough integration needs that maintaining a separate translation for each consumer becomes costly. The provider establishes a service protocol consumers can use and maintains its coherence as it expands. Highly specific needs can be handled separately instead of complicating the common protocol. DDD Reference: Open-host Service, page 35 of the document.

In our proposal:

Sales -----------+
Shipping --------+----> Inventory: integration interface
Marketplace -----+        - query availability
                          - request reservation
                                  |
                                  v
                         internal application and model

The lines represent consumers of a published capability. They do not describe repository access or shared tables.

The proposal does not require everyone to use every operation. Shipping may later need a separate shipping capability; it must not receive it through a hidden reservation parameter.

“Open” does not mean anonymous access

The protocol is available to authorized consumers that need to integrate. It may be internal, require credentials, and restrict capabilities by identity.

Sales can query and reserve, while Marketplace only queries until specifically authorized. A common interface does not remove those permission differences.

Nor does it require a new process. A modular monolith can offer this interface and keep its internal models isolated.

A REST API can be OHS, but not simply because it has endpoints

REST describes an interaction style. OHS describes an integration decision: offering a maintained, consistent interface usable by several consumers.

A set of endpoints that copies tables or grows through routes such as /stock-for-sales and /stock-for-marketplace, each with different meanings, may still maintain bespoke integrations.

By contrast, a small API with stable capabilities, clear responsibilities, and documented evolution can fulfill the pattern's purpose.

You do not need many current consumers to design an interface carefully. But building a universal platform is also unwise if there is only one small, well-defined need.

Start with the capability, not the entity

The problematic design allows consumers to do this:

// Contraejemplo conceptual: expone la estructura interna.
interface InventoryRow {
  id: number;
  sku: string;
  warehouse_id: number;
  physical_units: number;
  blocked_units: number;
  internal_review_flag: boolean;
}

function publicResponse(row: InventoryRow) {
  return row;
}

Now Sales must decide whether blocked units count, Marketplace interprets an internal flag, and Shipping depends on the warehouse identifier.

Improvement starts by asking what Inventory can promise:

  • A query reports reservable units at the time of reading.
  • A request attempts to reserve a quantity for the authorized consumer.
  • The reservation response indicates an actual result, not a copy of columns.
  • Distribution across warehouses belongs to the internal model.

The provider maintains its rules. The consumer receives information with sufficient meaning to make its next decision.

Input and output contracts

Querying availability

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

200 response:

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

A known SKU without units returns zero. An unknown SKU returns 404 with a stable code. The query does not reserve units or guarantee that they will remain available afterward.

We do not expose locations, table names, or internal blocking rules.

Requesting a reservation

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

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

201 response for a new reservation:

{
  "reservationId": "reservation-900",
  "sku": "BAG-URBAN",
  "quantity": 2,
  "status": "RESERVED"
}

The consumer's identity comes from authentication, not the body. requestId identifies a logical request within that identity.

For the example, we agree that an identical repetition returns the same reservation with 200. Reusing the reference with different data returns 409. This guarantee requires atomic, persistent implementation: adding a field to the DTO does not provide it.

Reservation release and validity rules must be defined before using the real capability. Here we do not implement the full lifecycle; the response does not mean that the product has been shipped or sold either.

An internal port for operations

The public interface delegates to Inventory's application. This port is not delivered as a library to external consumers.

In inventory-integration.ts, we define:

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

export interface ReservationDto {
  readonly reservationId: string;
  readonly sku: string;
  readonly quantity: number;
  readonly status: "RESERVED";
}

export interface InventoryOperations {
  availability(sku: string): Promise<AvailabilityDto>;

  reserve(input: {
    consumerId: string;
    requestId: string;
    sku: string;
    quantity: number;
  }): Promise<{
    created: boolean;
    reservation: ReservationDto;
  }>;
}

export class InventoryPublicError extends Error {
  constructor(
    readonly code:
      | "SKU_NOT_FOUND"
      | "INSUFFICIENT_STOCK"
      | "REQUEST_CONFLICT",
  ) {
    super(code);
  }
}

The implementation must calculate and persist reservations safely under concurrency. It cannot check stock, wait for an asynchronous operation, and deduct later without protection.

It must also retain the result associated with the consumer and request, and detect discrepancies. This article does not include that domain or database implementation; the port makes the missing work visible.

An Express interface with explicit validation

The following blocks complete the same file. They assume Express 5, its types, and TypeScript compilation with appropriate module interoperability. They do not include project configuration or a production-ready server.

Express supports mounting routes and middleware and processing JSON bodies. Received content needs its own validation; enabling the parser does not turn the body into trustworthy data. Official Express documentation.

First, we declare the security dependency:

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

type Operation = "availability:read" | "reservations:create";

export type Authorize = (
  request: Request,
  operation: Operation,
) => Promise<string>;

export class AccessError extends Error {
  constructor(readonly status: 401 | 403) {
    super("Access denied");
  }
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null &&
    !Array.isArray(value);
}

function validReference(value: unknown): value is string {
  return typeof value === "string" &&
    /^[A-Za-z0-9_-]{1,64}$/.test(value);
}

Authorize is a mandatory dependency. Its implementation must verify credentials and the requested permission, and return a stable identity obtained from a trusted source. Directly returning a client-supplied header is not sufficient.

Then we build the routes:

export function createInventoryIntegration(
  operations: InventoryOperations,
  authorize: Authorize,
) {
  const app = express();
  app.disable("x-powered-by");

  app.get("/integration/v1/availability/:sku", async (req, res) => {
    await authorize(req, "availability:read");

    const sku = req.params.sku;
    if (!validReference(sku)) {
      res.status(400).json({ error: { code: "INVALID_REQUEST" } });
      return;
    }

    const result = await operations.availability(sku);
    res.set("Cache-Control", "no-store").json({
      sku: result.sku,
      reservableQuantity: result.reservableQuantity,
    });
  });

  app.post(
    "/integration/v1/reservations",
    express.json({ limit: "8kb" }),
    async (req, res) => {
      const consumerId = await authorize(req, "reservations:create");
      const body: unknown = req.body;

      if (
        !isRecord(body) ||
        Object.keys(body).some(
          key => !["requestId", "sku", "quantity"].includes(key),
        ) ||
        !validReference(body.requestId) ||
        !validReference(body.sku) ||
        typeof body.quantity !== "number" ||
        !Number.isSafeInteger(body.quantity) ||
        body.quantity < 1 ||
        body.quantity > 1000
      ) {
        res.status(400).json({ error: { code: "INVALID_REQUEST" } });
        return;
      }

      const result = await operations.reserve({
        consumerId,
        requestId: body.requestId,
        sku: body.sku,
        quantity: body.quantity,
      });

      const reservation = result.reservation;
      res.status(result.created ? 201 : 200).json({
        reservationId: reservation.reservationId,
        sku: reservation.sku,
        quantity: reservation.quantity,
        status: reservation.status,
      });
    },
  );

  const errors: ErrorRequestHandler = (error: unknown, _req, res, _next) => {
    if (error instanceof AccessError) {
      res.status(error.status).json({
        error: {
          code: error.status === 401 ? "UNAUTHENTICATED" : "FORBIDDEN",
        },
      });
      return;
    }

    if (error instanceof InventoryPublicError) {
      const status = error.code === "SKU_NOT_FOUND" ? 404 : 409;
      res.status(status).json({ error: { code: error.code } });
      return;
    }

    if (isRecord(error) && error.type === "entity.too.large") {
      res.status(413).json({ error: { code: "REQUEST_TOO_LARGE" } });
      return;
    }

    if (isRecord(error) && error.type === "entity.parse.failed") {
      res.status(400).json({ error: { code: "INVALID_JSON" } });
      return;
    }

    res.status(500).json({ error: { code: "INTERNAL_ERROR" } });
  };

  app.use(errors);
  return app;
}

The thousand-unit limit is a public decision of this interface, not a universal rule. If another consumer needs larger quantities, the scope must be reviewed rather than adding a silent exception based on its name.

Serialization enumerates public fields. It does not return the result using a spread that might leak internal properties added later.

Express 5 propagates asynchronous handler rejections to error handling. The example depends on that behavior; it should not be copied without adaptation to an environment that does not support it.

The parser runs before POST authorization, with a size limit. A production composition can authenticate first and add traffic limits, timeouts, and auditing. Those implementations are omitted here; the route must not be published with fake authorization.

Errors consumers can interpret

The contract must distinguish different problems:

  • 400: invalid request; the consumer must correct the data.
  • 401 or 403: missing authentication or permission.
  • 404 with SKU_NOT_FOUND: Inventory does not recognize the SKU.
  • 409 with INSUFFICIENT_STOCK: that reservation cannot be fulfilled.
  • 409 with REQUEST_CONFLICT: a reference was reused with another request.
  • 413: body too large.
  • 500: unexpected error; it does not imply that an operation did not occur.

The example's codes are protocol decisions. Consumers should not parse database error messages.

A timeout after submitting a reservation can leave the consumer unaware of the result. It must not invent a failure or create new requests indiscriminately. Repeating the same reference is safe only when the agreed guarantee is implemented and verified.

A reservation does not confirm an order in Sales either. Each context maintains its responsibility, and HTTP does not create a shared transaction.

A contract test against the real interface

A transport test can start the Express application with controlled operations. That verifies routes, validation, and response shape without requiring a database.

This proposed example uses built-in Node.js APIs in addition to Express. It assumes the previous file compiled to ESM JavaScript. It has not been run as part of this article.

import test from "node:test";
import assert from "node:assert/strict";
import { once } from "node:events";
import {
  createInventoryIntegration,
  type InventoryOperations,
} from "./inventory-integration.js";

test("expone la reserva sin filtrar datos internos", async () => {
  const operations: InventoryOperations = {
    async availability(sku) {
      return { sku, reservableQuantity: 8 };
    },
    async reserve(input) {
      assert.equal(input.consumerId, "sales-test");

      return {
        created: true,
        reservation: {
          reservationId: "reservation-900",
          sku: input.sku,
          quantity: input.quantity,
          status: "RESERVED",
        },
      };
    },
  };

  // Autorización ficticia exclusiva de esta prueba.
  const app = createInventoryIntegration(
    operations,
    async () => "sales-test",
  );
  const server = app.listen(0, "127.0.0.1");

  try {
    await once(server, "listening");
    const address = server.address();
    if (!address || typeof address === "string") {
      throw new Error("No se pudo obtener el puerto de pruebas");
    }

    const response = await fetch(
      "http://127.0.0.1:" + address.port +
        "/integration/v1/reservations",
      {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          requestId: "checkout-100",
          sku: "BAG-URBAN",
          quantity: 2,
        }),
        signal: AbortSignal.timeout(3000),
      },
    );

    assert.equal(response.status, 201);
    assert.deepEqual(await response.json(), {
      reservationId: "reservation-900",
      sku: "BAG-URBAN",
      quantity: 2,
      status: "RESERVED",
    });
  } finally {
    await new Promise<void>((resolve, reject) => {
      server.close(error => error ? reject(error) : resolve());
    });
  }
});

This is a test of the provider's HTTP interface with its business application replaced. It does not demonstrate reservation atomicity, persistence, or real authentication.

Completing verification requires cases for permissions, invalid data, unknown SKUs, stock conflicts, and repeated requests. Inventory's real implementation needs concurrent and durable tests for the reservation guarantee.

In addition, consumers must check their expectations against a provider version in an isolated environment. A test that constructs an ideal response does not, by itself, prove compatibility between systems.

Protocol compatibility and evolution

Suppose Inventory adds observedAt to availability. It may be compatible if consumers tolerate new properties and the previous meaning is retained.

Saying “we only added a field” is not enough: how Sales, Shipping, and Marketplace deserialize must be verified.

By contrast, removing reservableQuantity, turning it into a string, or starting to include blocked units changes what consumers can expect.

Responsible evolution can:

  1. Identify affected consumers and capabilities.
  2. Document the change and examples.
  3. Temporarily retain the previous representation when feasible.
  4. Verify version combinations.
  5. Agree on migration and verify it before retiring support.

A v2 route distinguishes protocols, but does not explain their semantics or resolve adoption.

If Marketplace requests a commercial score combining availability with historical sales, it does not necessarily belong as a field in Inventory's protocol. It may require external composition or a specific integration, keeping the common service small.

OHS and its companion patterns

Published Language provides the documented exchange language: what reserving means, how quantities are expressed, and what each response represents. OHS is the offering of capabilities and protocol; they can complement each other.

Customer/Supplier describes how teams negotiate needs. Inventory can offer OHS and maintain specific agreements with some consumers without giving them access to its internal model.

Anti-Corruption Layer protects the consumer. Sales can translate Inventory's public interface into its own language even if the provider already has a consistent protocol.

A domain service expresses model behavior. OHS is not another name for that class; it is an integration interface that can invoke use cases and preserve their rules.

OHS is not a generic CRUD interface over repositories either. Offering capabilities does not require offering arbitrary writes to any entity.

The protocol can use other mechanisms

HTTP is one option for queries and requests. Messaging, RPC, or document exchange protocols can also exist.

The important decision is what capability is offered and how consumers learn its results and guarantees. A set of internal events published without a contract does not automatically become OHS.

If a reservation is requested asynchronously, receipt of the request must be distinguished from an effective reservation. An accepted message does not demonstrate that stock has been reserved.

We do not need to introduce a broker to learn the pattern. Protocol design precedes that technical decision.

Two additional situations for assessing scope

Education: querying places for several applications

An academic context offers place availability to enrollment, a public portal, and a guidance tool. A common interface can prevent each consumer from reconstructing rules through table queries.

The public portal should receive only information authorized for that scope. Sharing a protocol does not mean exposing academic records or personal data to everyone.

The lesson is to design common capabilities with appropriate permissions and representations.

Logistics: avoiding a premature universal protocol

A warehouse needs to send one daily report to a specific system. A focused exchange may be sufficient if the volume and need justify it.

Creating a universal API from the outset with dozens of operations, versions, and extensions could cost more than maintaining that specific integration.

OHS adds value when there is an integration offering worth maintaining in common. Not every point of contact must become a platform.

Guiding AI toward a coherent interface

For Cursor, Claude, or Codex, attach capabilities, contracts, and internal model boundaries.

To design:

Inventory serves Sales, Shipping, and Marketplace. Propose a common interface for availability and reservations. Distinguish shared needs from specific exceptions. Do not expose entities, tables, or internal methods. Explain guarantees and permissions per capability.

To implement:

Implement Express routes for these contracts, delegating to application ports. Validate unknown data, limit the body, and serialize explicit fields. Consumer identity must come from verified authorization. Do not implement a false reservation guarantee using an in-memory Map.

To review:

Review this protocol change against known consumers. Look for meaning changes, internal property leakage, and extensions requiring consumer updates. Distinguish what HTTP tests cover from what needs persistence and concurrency verification.

A person must check the meaning of the capabilities and the actual guarantees of their implementation. An endpoint responding 201 does not, by itself, demonstrate that it protected stock.

Exercises

1. The convenient internal field

Sales asks to include warehouse_id so it can decide where to reserve. Inventory already offers the reservation capability. What would you review?

2. The special consumer

Marketplace needs a commercial calculation no other consumer uses. Must it always be added to the common contract?

3. The reservation that is not durable

The route returns 201 and stores a reference in memory. After a restart, the same request creates another reservation. Which guarantee is missing?

Reasoned solutions

1. I would review whether Sales has a real need to choose a location or is assuming an internal Inventory responsibility. If a permitted selection exists, it must be modeled as an explicit public capability, rather than leaking a persistence key.

2. No. Evaluate whether it belongs to Inventory and has shared meaning. A specific composition or integration can resolve the exception without turning the common protocol into a collection of special cases.

3. The request identity and its result must be persisted and applied atomically within the authorized scope. The repetition contract is not fulfilled by accepting a requestId. It is also necessary to verify that deducting or blocking units maintains its rules under concurrency.

A stable offering without freezing the domain

An Open Host Service is useful when you can offer coherent capabilities to several consumers and sustain their contract over time.

Check that operations speak in terms of public needs, internal data remains private, and every guarantee has an appropriate implementation and test.

The model can evolve internally. Stability means managing what other contexts can expect, not preventing every change.

Loading conversation…

Keep learning